source
stringlengths
3
92
c
stringlengths
26
2.25M
CLHelper.h
//------------------------------------------ //--cambine:helper function for OpenCL //--programmer: Jianbin Fang //--date: 27/12/2010 //------------------------------------------ #ifndef _CL_HELPER_ #define _CL_HELPER_ #include <CL/cl.h> #include <fstream> #include <iostream> #include <string> #include <vector> using std::string; using std::ifstream; using std::cerr; using std::endl; using std::cout; //#pragma OPENCL EXTENSION cl_nv_compiler_options:enable #define WORK_DIM 2 // work-items dimensions struct oclHandleStruct { cl_context context; cl_device_id *devices; cl_command_queue queue; cl_program program; cl_int cl_status; std::string error_str; std::vector<cl_kernel> kernel; }; struct oclHandleStruct oclHandles; char kernel_file[100] = "Kernels.cl"; int total_kernels = 2; string kernel_names[2] = {"BFS_1", "BFS_2"}; int work_group_size = 512; int device_id_inused = 0; // deviced id used (default : 0) int read_kernel_file(const char* filename, uint8_t** data, size_t* size) { if (nullptr == filename || nullptr == data || 0 == size) return -1; FILE* fp = fopen(filename, "r"); if (NULL == fp) { fprintf(stderr, "Failed to load kernel."); return -1; } fseek(fp , 0 , SEEK_END); long fsize = ftell(fp); rewind(fp); *data = (uint8_t*)malloc(fsize); *size = fread(*data, 1, fsize, fp); fclose(fp); return 0; } /* * Converts the contents of a file into a string */ string FileToString(const string fileName) { ifstream f(fileName.c_str(), ifstream::in | ifstream::binary); try { size_t size; char *str; string s; if (f.is_open()) { size_t fileSize; f.seekg(0, ifstream::end); size = fileSize = f.tellg(); f.seekg(0, ifstream::beg); str = new char[size + 1]; if (!str) throw(string("Could not allocate memory")); f.read(str, fileSize); f.close(); str[size] = '\0'; s = str; delete[] str; return s; } } catch (std::string msg) { cerr << "Exception caught in FileToString(): " << msg << endl; if (f.is_open()) f.close(); } catch (...) { cerr << "Exception caught in FileToString()" << endl; if (f.is_open()) f.close(); } string errorMsg = "FileToString()::Error: Unable to open file " + fileName; throw(errorMsg); } //--------------------------------------- // Read command line parameters // void _clCmdParams(int argc, char *argv[]) { for (int i = 0; i < argc; ++i) { switch (argv[i][1]) { case 'g': //--g stands for size of work group if (++i < argc) { sscanf(argv[i], "%u", &work_group_size); } else { std::cerr << "Could not read argument after option " << argv[i - 1] << std::endl; throw; } break; case 'd': //--d stands for device id used in computaion if (++i < argc) { sscanf(argv[i], "%u", &device_id_inused); } else { std::cerr << "Could not read argument after option " << argv[i - 1] << std::endl; throw; } break; default:; } } } //--------------------------------------- // Initlize CL objects //--description: there are 5 steps to initialize all the OpenCL objects needed //--revised on 04/01/2011: get the number of devices and // devices have no relationship with context void _clInit() { printf("_clInit()\n"); int DEVICE_ID_INUSED = device_id_inused; cl_int resultCL; oclHandles.context = NULL; oclHandles.devices = NULL; oclHandles.queue = NULL; oclHandles.program = NULL; cl_uint deviceListSize; //----------------------------------------------- //--cambine-1: find the available platforms and select one cl_uint numPlatforms = 1; cl_platform_id targetPlatform = NULL; cl_platform_id *allPlatforms = (cl_platform_id *)malloc(numPlatforms * sizeof(cl_platform_id)); resultCL = clGetPlatformIDs(numPlatforms, allPlatforms, NULL); if (resultCL != CL_SUCCESS) throw(string("InitCL()::Error: Getting platform ids (clGetPlatformIDs)")); // Select the target platform. Default: first platform targetPlatform = allPlatforms[0]; /*for (int i = 0; i < numPlatforms; i++) { char pbuff[128]; resultCL = clGetPlatformInfo( allPlatforms[i], CL_PLATFORM_VENDOR, sizeof(pbuff), pbuff, NULL); if (resultCL != CL_SUCCESS) throw (string("InitCL()::Error: Getting platform info (clGetPlatformInfo)")); //printf("vedor is %s\n",pbuff); } free(allPlatforms);*/ //----------------------------------------------- //--cambine-2: create an OpenCL context /*cl_context_properties cprops[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)targetPlatform, 0 }; oclHandles.context = clCreateContextFromType(cprops, CL_DEVICE_TYPE_GPU, NULL, NULL, &resultCL); if ((resultCL != CL_SUCCESS) || (oclHandles.context == NULL)) throw (string("InitCL()::Error: Creating Context (clCreateContextFromType)")); //----------------------------------------------- //--cambine-3: detect OpenCL devices // First, get the size of device list oclHandles.cl_status = clGetDeviceIDs(targetPlatform, CL_DEVICE_TYPE_GPU, 0, NULL, &deviceListSize); if(oclHandles.cl_status!=CL_SUCCESS){ throw(string("exception in _clInit -> clGetDeviceIDs")); } if (deviceListSize == 0) throw(string("InitCL()::Error: No devices found.")); printf("OK1()\n"); //std::cout<<"device number:"<<deviceListSize<<std::endl;*/ // Now, allocate the device list deviceListSize = 1; oclHandles.devices = (cl_device_id *)malloc(deviceListSize * sizeof(cl_device_id)); if (oclHandles.devices == 0) throw(string("InitCL()::Error: Could not allocate memory.")); //* Next, get the device list data oclHandles.cl_status = clGetDeviceIDs(targetPlatform, CL_DEVICE_TYPE_DEFAULT, deviceListSize, oclHandles.devices, NULL); if (oclHandles.cl_status != CL_SUCCESS) { throw(string("exception in _clInit -> clGetDeviceIDs-2")); } oclHandles.context = clCreateContext(NULL, deviceListSize, oclHandles.devices, NULL, NULL, &resultCL); if ((resultCL != CL_SUCCESS) || (oclHandles.context == NULL)) throw(string("InitCL()::Error: Creating Context (clCreateContext)")); //----------------------------------------------- //--cambine-4: Create an OpenCL command queue oclHandles.queue = clCreateCommandQueue( oclHandles.context, oclHandles.devices[DEVICE_ID_INUSED], 0, &resultCL); printf("resultCL=%d, queue=0x%x\n", resultCL, oclHandles.queue); if ((resultCL != CL_SUCCESS) || (oclHandles.queue == NULL)) throw(string("InitCL()::Creating Command Queue. (clCreateCommandQueue)")); //----------------------------------------------- //--cambine-5: Load CL file, build CL program object, create CL kernel object /*std::string source_str = FileToString(kernel_file); const char * source = source_str.c_str(); size_t sourceSize[] = { source_str.length() };*/ //oclHandles.program = clCreateProgramWithBuiltInKernels( // oclHandles.context, 1, &oclHandles.devices[DEVICE_ID_INUSED], // "BFS_1;BFS_2", &resultCL); /*oclHandles.program = clCreateProgramWithSource(oclHandles.context, 1, &source, sourceSize, &resultCL);*/ // read kernel binary from file uint8_t *kernel_bin = NULL; size_t kernel_size; cl_int binary_status = 0; if (0 != read_kernel_file("kernel.pocl", &kernel_bin, &kernel_size)) std::abort(); oclHandles.program = clCreateProgramWithBinary( oclHandles.context, 1, &oclHandles.devices[DEVICE_ID_INUSED], &kernel_size, (const uint8_t**)&kernel_bin, &binary_status, &resultCL); free(kernel_bin); if ((resultCL != CL_SUCCESS) || (oclHandles.program == NULL)) throw(string("InitCL()::Error: Loading Binary into cl_program. " "(clCreateProgramWithBinary)")); // insert debug information // std::string options= "-cl-nv-verbose"; //Doesn't work on AMD machines // options += " -cl-nv-opt-level=3"; resultCL = clBuildProgram(oclHandles.program, deviceListSize, oclHandles.devices, NULL, NULL, NULL); if ((resultCL != CL_SUCCESS) || (oclHandles.program == NULL)) { cerr << "InitCL()::Error: In clBuildProgram" << endl; size_t length; resultCL = clGetProgramBuildInfo(oclHandles.program, oclHandles.devices[DEVICE_ID_INUSED], CL_PROGRAM_BUILD_LOG, 0, NULL, &length); if (resultCL != CL_SUCCESS) throw(string("InitCL()::Error: Getting Program build " "info(clGetProgramBuildInfo)")); char *buffer = (char *)malloc(length); resultCL = clGetProgramBuildInfo( oclHandles.program, oclHandles.devices[DEVICE_ID_INUSED], CL_PROGRAM_BUILD_LOG, length, buffer, NULL); if (resultCL != CL_SUCCESS) throw(string("InitCL()::Error: Getting Program build " "info(clGetProgramBuildInfo)")); cerr << buffer << endl; free(buffer); throw(string("InitCL()::Error: Building Program (clBuildProgram)")); } // get program information in intermediate representation #ifdef PTX_MSG size_t binary_sizes[deviceListSize]; char *binaries[deviceListSize]; // figure out number of devices and the sizes of the binary for each device. oclHandles.cl_status = clGetProgramInfo(oclHandles.program, CL_PROGRAM_BINARY_SIZES, sizeof(size_t) * deviceListSize, &binary_sizes, NULL); if (oclHandles.cl_status != CL_SUCCESS) { throw(string("--cambine:exception in _InitCL -> clGetProgramInfo-2")); } std::cout << "--cambine:" << binary_sizes << std::endl; // copy over all of the generated binaries. for (int i = 0; i < deviceListSize; i++) binaries[i] = (char *)malloc(sizeof(char) * (binary_sizes[i] + 1)); oclHandles.cl_status = clGetProgramInfo(oclHandles.program, CL_PROGRAM_BINARIES, sizeof(char *) * deviceListSize, binaries, NULL); if (oclHandles.cl_status != CL_SUCCESS) { throw(string("--cambine:exception in _InitCL -> clGetProgramInfo-3")); } for (int i = 0; i < deviceListSize; i++) binaries[i][binary_sizes[i]] = '\0'; std::cout << "--cambine:writing ptd information..." << std::endl; FILE *ptx_file = fopen("cl.ptx", "w"); if (ptx_file == NULL) { throw(string("exceptions in allocate ptx file.")); } fprintf(ptx_file, "%s", binaries[DEVICE_ID_INUSED]); fclose(ptx_file); std::cout << "--cambine:writing ptd information done." << std::endl; for (int i = 0; i < deviceListSize; i++) free(binaries[i]); #endif for (int nKernel = 0; nKernel < total_kernels; nKernel++) { /* get a kernel object handle for a kernel with the given name */ cl_kernel kernel = clCreateKernel( oclHandles.program, (kernel_names[nKernel]).c_str(), &resultCL); if ((resultCL != CL_SUCCESS) || (kernel == NULL)) { string errorMsg = "InitCL()::Error: Creating Kernel (clCreateKernel) \"" + kernel_names[nKernel] + "\""; throw(errorMsg); } oclHandles.kernel.push_back(kernel); } // get resource alocation information #ifdef RES_MSG char *build_log; size_t ret_val_size; oclHandles.cl_status = clGetProgramBuildInfo( oclHandles.program, oclHandles.devices[DEVICE_ID_INUSED], CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size); if (oclHandles.cl_status != CL_SUCCESS) { throw(string("exceptions in _InitCL -> getting resource information")); } build_log = (char *)malloc(ret_val_size + 1); oclHandles.cl_status = clGetProgramBuildInfo( oclHandles.program, oclHandles.devices[DEVICE_ID_INUSED], CL_PROGRAM_BUILD_LOG, ret_val_size, build_log, NULL); if (oclHandles.cl_status != CL_SUCCESS) { throw(string( "exceptions in _InitCL -> getting resources allocation information-2")); } build_log[ret_val_size] = '\0'; std::cout << "--cambine:" << build_log << std::endl; free(build_log); #endif } //--------------------------------------- // release CL objects void _clRelease() { char errorFlag = false; for (int nKernel = 0; nKernel < oclHandles.kernel.size(); nKernel++) { if (oclHandles.kernel[nKernel] != NULL) { cl_int resultCL = clReleaseKernel(oclHandles.kernel[nKernel]); if (resultCL != CL_SUCCESS) { cerr << "ReleaseCL()::Error: In clReleaseKernel" << endl; errorFlag = true; } oclHandles.kernel[nKernel] = NULL; } oclHandles.kernel.clear(); } if (oclHandles.program != NULL) { cl_int resultCL = clReleaseProgram(oclHandles.program); if (resultCL != CL_SUCCESS) { cerr << "ReleaseCL()::Error: In clReleaseProgram" << endl; errorFlag = true; } oclHandles.program = NULL; } if (oclHandles.queue != NULL) { cl_int resultCL = clReleaseCommandQueue(oclHandles.queue); if (resultCL != CL_SUCCESS) { cerr << "ReleaseCL()::Error: In clReleaseCommandQueue" << endl; errorFlag = true; } oclHandles.queue = NULL; } free(oclHandles.devices); if (oclHandles.context != NULL) { cl_int resultCL = clReleaseContext(oclHandles.context); if (resultCL != CL_SUCCESS) { cerr << "ReleaseCL()::Error: In clReleaseContext" << endl; errorFlag = true; } oclHandles.context = NULL; } if (errorFlag) throw(string("ReleaseCL()::Error encountered.")); } //-------------------------------------------------------- //--cambine:create buffer and then copy data from host to device cl_mem _clCreateAndCpyMem(int size, void *h_mem_source) throw(string) { cl_mem d_mem; d_mem = clCreateBuffer(oclHandles.context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, size, h_mem_source, &oclHandles.cl_status); #ifdef ERRMSG if (oclHandles.cl_status != CL_SUCCESS) throw(string("excpetion in _clCreateAndCpyMem()")); #endif return d_mem; } //------------------------------------------------------- //--cambine: create read only buffer for devices //--date: 17/01/2011 cl_mem _clMallocRW(int size, void *h_mem_ptr) throw(string) { cl_mem d_mem; d_mem = clCreateBuffer(oclHandles.context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, size, h_mem_ptr, &oclHandles.cl_status); #ifdef ERRMSG if (oclHandles.cl_status != CL_SUCCESS) throw(string("excpetion in _clMallocRW")); #endif return d_mem; } //------------------------------------------------------- //--cambine: create read and write buffer for devices //--date: 17/01/2011 cl_mem _clMalloc(int size, void *h_mem_ptr) throw(string) { cl_mem d_mem; d_mem = clCreateBuffer(oclHandles.context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, size, h_mem_ptr, &oclHandles.cl_status); #ifdef ERRMSG if (oclHandles.cl_status != CL_SUCCESS) throw(string("excpetion in _clMalloc")); #endif return d_mem; } //------------------------------------------------------- //--cambine: transfer data from host to device //--date: 17/01/2011 void _clMemcpyH2D(cl_mem d_mem, int size, const void *h_mem_ptr) throw(string) { oclHandles.cl_status = clEnqueueWriteBuffer( oclHandles.queue, d_mem, CL_TRUE, 0, size, h_mem_ptr, 0, NULL, NULL); #ifdef ERRMSG if (oclHandles.cl_status != CL_SUCCESS) throw(string("excpetion in _clMemcpyH2D")); #endif } //-------------------------------------------------------- //--cambine:create buffer and then copy data from host to device with pinned // memory cl_mem _clCreateAndCpyPinnedMem(int size, float *h_mem_source) throw(string) { cl_mem d_mem, d_mem_pinned; float *h_mem_pinned = NULL; d_mem_pinned = clCreateBuffer(oclHandles.context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, size, NULL, &oclHandles.cl_status); #ifdef ERRMSG if (oclHandles.cl_status != CL_SUCCESS) throw(string("excpetion in _clCreateAndCpyMem()->d_mem_pinned")); #endif //------------ d_mem = clCreateBuffer(oclHandles.context, CL_MEM_READ_ONLY, size, NULL, &oclHandles.cl_status); #ifdef ERRMSG if (oclHandles.cl_status != CL_SUCCESS) throw(string("excpetion in _clCreateAndCpyMem() -> d_mem ")); #endif //---------- h_mem_pinned = (cl_float *)clEnqueueMapBuffer( oclHandles.queue, d_mem_pinned, CL_TRUE, CL_MAP_WRITE, 0, size, 0, NULL, NULL, &oclHandles.cl_status); #ifdef ERRMSG if (oclHandles.cl_status != CL_SUCCESS) throw(string("excpetion in _clCreateAndCpyMem() -> clEnqueueMapBuffer")); #endif int element_number = size / sizeof(float); #pragma omp parallel for for (int i = 0; i < element_number; i++) { h_mem_pinned[i] = h_mem_source[i]; } //---------- oclHandles.cl_status = clEnqueueWriteBuffer( oclHandles.queue, d_mem, CL_TRUE, 0, size, h_mem_pinned, 0, NULL, NULL); #ifdef ERRMSG if (oclHandles.cl_status != CL_SUCCESS) throw(string("excpetion in _clCreateAndCpyMem() -> clEnqueueWriteBuffer")); #endif return d_mem; } //-------------------------------------------------------- //--cambine:create write only buffer on device cl_mem _clMallocWO(int size) throw(string) { cl_mem d_mem; d_mem = clCreateBuffer(oclHandles.context, CL_MEM_WRITE_ONLY, size, 0, &oclHandles.cl_status); #ifdef ERRMSG if (oclHandles.cl_status != CL_SUCCESS) throw(string("excpetion in _clCreateMem()")); #endif return d_mem; } //-------------------------------------------------------- // transfer data from device to host void _clMemcpyD2H(cl_mem d_mem, int size, void *h_mem) throw(string) { oclHandles.cl_status = clEnqueueReadBuffer(oclHandles.queue, d_mem, CL_TRUE, 0, size, h_mem, 0, 0, 0); #ifdef ERRMSG oclHandles.error_str = "excpetion in _clCpyMemD2H -> "; switch (oclHandles.cl_status) { case CL_INVALID_COMMAND_QUEUE: oclHandles.error_str += "CL_INVALID_COMMAND_QUEUE"; break; case CL_INVALID_CONTEXT: oclHandles.error_str += "CL_INVALID_CONTEXT"; break; case CL_INVALID_MEM_OBJECT: oclHandles.error_str += "CL_INVALID_MEM_OBJECT"; break; case CL_INVALID_VALUE: oclHandles.error_str += "CL_INVALID_VALUE"; break; case CL_INVALID_EVENT_WAIT_LIST: oclHandles.error_str += "CL_INVALID_EVENT_WAIT_LIST"; break; case CL_MEM_OBJECT_ALLOCATION_FAILURE: oclHandles.error_str += "CL_MEM_OBJECT_ALLOCATION_FAILURE"; break; case CL_OUT_OF_HOST_MEMORY: oclHandles.error_str += "CL_OUT_OF_HOST_MEMORY"; break; default: oclHandles.error_str += "Unknown reason"; break; } if (oclHandles.cl_status != CL_SUCCESS) throw(oclHandles.error_str); #endif } //-------------------------------------------------------- // set kernel arguments void _clSetArgs(int kernel_id, int arg_idx, void *d_mem, int size = 0) throw(string) { if (!size) { oclHandles.cl_status = clSetKernelArg(oclHandles.kernel[kernel_id], arg_idx, sizeof(d_mem), &d_mem); #ifdef ERRMSG oclHandles.error_str = "excpetion in _clSetKernelArg() "; switch (oclHandles.cl_status) { case CL_INVALID_KERNEL: oclHandles.error_str += "CL_INVALID_KERNEL"; break; case CL_INVALID_ARG_INDEX: oclHandles.error_str += "CL_INVALID_ARG_INDEX"; break; case CL_INVALID_ARG_VALUE: oclHandles.error_str += "CL_INVALID_ARG_VALUE"; break; case CL_INVALID_MEM_OBJECT: oclHandles.error_str += "CL_INVALID_MEM_OBJECT"; break; case CL_INVALID_SAMPLER: oclHandles.error_str += "CL_INVALID_SAMPLER"; break; case CL_INVALID_ARG_SIZE: oclHandles.error_str += "CL_INVALID_ARG_SIZE"; break; case CL_OUT_OF_RESOURCES: oclHandles.error_str += "CL_OUT_OF_RESOURCES"; break; case CL_OUT_OF_HOST_MEMORY: oclHandles.error_str += "CL_OUT_OF_HOST_MEMORY"; break; default: oclHandles.error_str += "Unknown reason"; break; } if (oclHandles.cl_status != CL_SUCCESS) throw(oclHandles.error_str); #endif } else { oclHandles.cl_status = clSetKernelArg(oclHandles.kernel[kernel_id], arg_idx, size, d_mem); #ifdef ERRMSG oclHandles.error_str = "excpetion in _clSetKernelArg() "; switch (oclHandles.cl_status) { case CL_INVALID_KERNEL: oclHandles.error_str += "CL_INVALID_KERNEL"; break; case CL_INVALID_ARG_INDEX: oclHandles.error_str += "CL_INVALID_ARG_INDEX"; break; case CL_INVALID_ARG_VALUE: oclHandles.error_str += "CL_INVALID_ARG_VALUE"; break; case CL_INVALID_MEM_OBJECT: oclHandles.error_str += "CL_INVALID_MEM_OBJECT"; break; case CL_INVALID_SAMPLER: oclHandles.error_str += "CL_INVALID_SAMPLER"; break; case CL_INVALID_ARG_SIZE: oclHandles.error_str += "CL_INVALID_ARG_SIZE"; break; case CL_OUT_OF_RESOURCES: oclHandles.error_str += "CL_OUT_OF_RESOURCES"; break; case CL_OUT_OF_HOST_MEMORY: oclHandles.error_str += "CL_OUT_OF_HOST_MEMORY"; break; default: oclHandles.error_str += "Unknown reason"; break; } if (oclHandles.cl_status != CL_SUCCESS) throw(oclHandles.error_str); #endif } } void _clFinish() throw(string) { oclHandles.cl_status = clFinish(oclHandles.queue); #ifdef ERRMSG oclHandles.error_str = "excpetion in _clFinish"; switch (oclHandles.cl_status) { case CL_INVALID_COMMAND_QUEUE: oclHandles.error_str += "CL_INVALID_COMMAND_QUEUE"; break; case CL_OUT_OF_RESOURCES: oclHandles.error_str += "CL_OUT_OF_RESOURCES"; break; case CL_OUT_OF_HOST_MEMORY: oclHandles.error_str += "CL_OUT_OF_HOST_MEMORY"; break; default: oclHandles.error_str += "Unknown reasons"; break; } if (oclHandles.cl_status != CL_SUCCESS) { throw(oclHandles.error_str); } #endif } //-------------------------------------------------------- //--cambine:enqueue kernel void _clInvokeKernel(int kernel_id, int work_items, int work_group_size) throw(string) { cl_uint work_dim = WORK_DIM; cl_event e[1]; if (work_items % work_group_size != 0) // process situations that work_items // cannot be divided by work_group_size work_items = work_items + (work_group_size - (work_items % work_group_size)); size_t local_work_size[] = {work_group_size, 1}; size_t global_work_size[] = {work_items, 1}; oclHandles.cl_status = clEnqueueNDRangeKernel( oclHandles.queue, oclHandles.kernel[kernel_id], work_dim, 0, global_work_size, local_work_size, 0, 0, &(e[0])); #ifdef ERRMSG oclHandles.error_str = "excpetion in _clInvokeKernel() -> "; switch (oclHandles.cl_status) { case CL_INVALID_PROGRAM_EXECUTABLE: oclHandles.error_str += "CL_INVALID_PROGRAM_EXECUTABLE"; break; case CL_INVALID_COMMAND_QUEUE: oclHandles.error_str += "CL_INVALID_COMMAND_QUEUE"; break; case CL_INVALID_KERNEL: oclHandles.error_str += "CL_INVALID_KERNEL"; break; case CL_INVALID_CONTEXT: oclHandles.error_str += "CL_INVALID_CONTEXT"; break; case CL_INVALID_KERNEL_ARGS: oclHandles.error_str += "CL_INVALID_KERNEL_ARGS"; break; case CL_INVALID_WORK_DIMENSION: oclHandles.error_str += "CL_INVALID_WORK_DIMENSION"; break; case CL_INVALID_GLOBAL_WORK_SIZE: oclHandles.error_str += "CL_INVALID_GLOBAL_WORK_SIZE"; break; case CL_INVALID_WORK_GROUP_SIZE: oclHandles.error_str += "CL_INVALID_WORK_GROUP_SIZE"; break; case CL_INVALID_WORK_ITEM_SIZE: oclHandles.error_str += "CL_INVALID_WORK_ITEM_SIZE"; break; case CL_INVALID_GLOBAL_OFFSET: oclHandles.error_str += "CL_INVALID_GLOBAL_OFFSET"; break; case CL_OUT_OF_RESOURCES: oclHandles.error_str += "CL_OUT_OF_RESOURCES"; break; case CL_MEM_OBJECT_ALLOCATION_FAILURE: oclHandles.error_str += "CL_MEM_OBJECT_ALLOCATION_FAILURE"; break; case CL_INVALID_EVENT_WAIT_LIST: oclHandles.error_str += "CL_INVALID_EVENT_WAIT_LIST"; break; case CL_OUT_OF_HOST_MEMORY: oclHandles.error_str += "CL_OUT_OF_HOST_MEMORY"; break; default: oclHandles.error_str += "Unkown reseason"; break; } if (oclHandles.cl_status != CL_SUCCESS) throw(oclHandles.error_str); #endif //_clFinish(); // oclHandles.cl_status = clWaitForEvents(1, &e[0]); // #ifdef ERRMSG // if (oclHandles.cl_status!= CL_SUCCESS) // throw(string("excpetion in _clEnqueueNDRange() -> clWaitForEvents")); // #endif } void _clInvokeKernel2D(int kernel_id, int range_x, int range_y, int group_x, int group_y) throw(string) { cl_uint work_dim = WORK_DIM; size_t local_work_size[] = {group_x, group_y}; size_t global_work_size[] = {range_x, range_y}; cl_event e[1]; /*if(work_items%work_group_size != 0) //process situations that work_items cannot be divided by work_group_size work_items = work_items + (work_group_size-(work_items%work_group_size));*/ oclHandles.cl_status = clEnqueueNDRangeKernel( oclHandles.queue, oclHandles.kernel[kernel_id], work_dim, 0, global_work_size, local_work_size, 0, 0, &(e[0])); #ifdef ERRMSG oclHandles.error_str = "excpetion in _clInvokeKernel() -> "; switch (oclHandles.cl_status) { case CL_INVALID_PROGRAM_EXECUTABLE: oclHandles.error_str += "CL_INVALID_PROGRAM_EXECUTABLE"; break; case CL_INVALID_COMMAND_QUEUE: oclHandles.error_str += "CL_INVALID_COMMAND_QUEUE"; break; case CL_INVALID_KERNEL: oclHandles.error_str += "CL_INVALID_KERNEL"; break; case CL_INVALID_CONTEXT: oclHandles.error_str += "CL_INVALID_CONTEXT"; break; case CL_INVALID_KERNEL_ARGS: oclHandles.error_str += "CL_INVALID_KERNEL_ARGS"; break; case CL_INVALID_WORK_DIMENSION: oclHandles.error_str += "CL_INVALID_WORK_DIMENSION"; break; case CL_INVALID_GLOBAL_WORK_SIZE: oclHandles.error_str += "CL_INVALID_GLOBAL_WORK_SIZE"; break; case CL_INVALID_WORK_GROUP_SIZE: oclHandles.error_str += "CL_INVALID_WORK_GROUP_SIZE"; break; case CL_INVALID_WORK_ITEM_SIZE: oclHandles.error_str += "CL_INVALID_WORK_ITEM_SIZE"; break; case CL_INVALID_GLOBAL_OFFSET: oclHandles.error_str += "CL_INVALID_GLOBAL_OFFSET"; break; case CL_OUT_OF_RESOURCES: oclHandles.error_str += "CL_OUT_OF_RESOURCES"; break; case CL_MEM_OBJECT_ALLOCATION_FAILURE: oclHandles.error_str += "CL_MEM_OBJECT_ALLOCATION_FAILURE"; break; case CL_INVALID_EVENT_WAIT_LIST: oclHandles.error_str += "CL_INVALID_EVENT_WAIT_LIST"; break; case CL_OUT_OF_HOST_MEMORY: oclHandles.error_str += "CL_OUT_OF_HOST_MEMORY"; break; default: oclHandles.error_str += "Unkown reseason"; break; } if (oclHandles.cl_status != CL_SUCCESS) throw(oclHandles.error_str); #endif //_clFinish(); /*oclHandles.cl_status = clWaitForEvents(1, &e[0]); #ifdef ERRMSG if (oclHandles.cl_status!= CL_SUCCESS) throw(string("excpetion in _clEnqueueNDRange() -> clWaitForEvents")); #endif*/ } //-------------------------------------------------------- // release OpenCL objects void _clFree(cl_mem ob) throw(string) { if (ob != NULL) oclHandles.cl_status = clReleaseMemObject(ob); #ifdef ERRMSG oclHandles.error_str = "excpetion in _clFree() ->"; switch (oclHandles.cl_status) { case CL_INVALID_MEM_OBJECT: oclHandles.error_str += "CL_INVALID_MEM_OBJECT"; break; case CL_OUT_OF_RESOURCES: oclHandles.error_str += "CL_OUT_OF_RESOURCES"; break; case CL_OUT_OF_HOST_MEMORY: oclHandles.error_str += "CL_OUT_OF_HOST_MEMORY"; break; default: oclHandles.error_str += "Unkown reseason"; break; } if (oclHandles.cl_status != CL_SUCCESS) throw(oclHandles.error_str); #endif } #endif //_CL_HELPER_
sumstats.h
/* Copyright (c) 2015-2016 Drew Schmidt All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __COOP_LIB_SUMSTATS_H__ #define __COOP_LIB_SUMSTATS_H__ #include "safeomp.h" // x[*, j] -= colmean(x[*, j]) static inline void remove_colmeans(const int m, const int n, double *restrict x) { if (m == 0 || n == 0) return; const double div = 1. / ((double) m); #pragma omp parallel for shared(x) if(m*n > OMP_MIN_SIZE) for (int j=0; j<n; j++) { double colmean = 0; // Get column mean SAFE_SIMD for (int i=0; i<m; i++) colmean += x[i + m*j]; colmean *= div; // Remove mean from column SAFE_SIMD for (int i=0; i<m; i++) x[i + m*j] -= colmean; } } // same as above but return the means vector static inline void remove_colmeans_retmean(const int m, const int n, double *restrict x, double *restrict colmeans) { if (m == 0 || n == 0) return; const double div = 1. / ((double) m); #pragma omp parallel for shared(x, colmeans) if(m*n > OMP_MIN_SIZE) for (int j=0; j<n; j++) { colmeans[j] = 0; // Get column mean SAFE_SIMD for (int i=0; i<m; i++) colmeans[j] += x[i + m*j]; colmeans[j] *= div; // Remove mean from column SAFE_SIMD for (int i=0; i<m; i++) x[i + m*j] -= colmeans[j]; } } // compute the mean of a vector static inline double mean(const int n, const double * const restrict x) { const double divbyn = 1. / ((double) n); double mean = 0.; PLEASE_VECTORIZE for (int i=0; i<n; i++) mean += x[i]; return mean*divbyn; } #endif
GB_unop__identity_int16_uint32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int16_uint32) // op(A') function: GB (_unop_tran__identity_int16_uint32) // C type: int16_t // A type: uint32_t // cast: int16_t cij = (int16_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int16_t z = (int16_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int16_t z = (int16_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int16_uint32) ( int16_t *Cx, // Cx and Ax may be aliased const uint32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t aij = Ax [p] ; int16_t z = (int16_t) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint32_t aij = Ax [p] ; int16_t z = (int16_t) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int16_uint32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
3d7pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 32; tile_size[1] = 32; tile_size[2] = 16; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,16);t1++) { lbp=max(ceild(t1,2),ceild(32*t1-Nt+3,32)); ubp=min(floord(Nt+Nz-4,32),floord(16*t1+Nz+13,32)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(32*t2-Nz-12,16)),t1);t3<=min(min(min(floord(Nt+Ny-4,16),floord(16*t1+Ny+29,16)),floord(32*t2+Ny+28,16)),floord(32*t1-32*t2+Nz+Ny+27,16));t3++) { for (t4=max(max(max(0,ceild(t1-15,16)),ceild(32*t2-Nz-252,256)),ceild(16*t3-Ny-252,256));t4<=min(min(min(min(floord(Nt+Nx-4,256),floord(16*t1+Nx+29,256)),floord(32*t2+Nx+28,256)),floord(16*t3+Nx+12,256)),floord(32*t1-32*t2+Nz+Nx+27,256));t4++) { for (t5=max(max(max(max(max(0,16*t1),32*t1-32*t2+1),32*t2-Nz+2),16*t3-Ny+2),256*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,16*t1+31),32*t2+30),16*t3+14),256*t4+254),32*t1-32*t2+Nz+29);t5++) { for (t6=max(max(32*t2,t5+1),-32*t1+32*t2+2*t5-31);t6<=min(min(32*t2+31,-32*t1+32*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(16*t3,t5+1);t7<=min(16*t3+15,t5+Ny-2);t7++) { lbv=max(256*t4,t5+1); ubv=min(256*t4+255,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/ASTConcept.h" #include "clang/AST/ASTFwd.h" #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprConcepts.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/TypeLoc.h" #include "clang/APINotes/APINotesManager.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/DarwinSDKInfo.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenCLOptions.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaConcept.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <functional> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Tracks expected type during expression parsing, for use in code completion. /// The type is tied to a particular token, all functions that update or consume /// the type take a start location of the token they are looking at as a /// parameter. This avoids updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Handles e.g. BaseType{ .D = Tok... void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, const Designation &D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. /// /// The callback should also emit signature help as a side-effect, but only /// if the completion point has been reached. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); /// Get the expected type associated with this location, if any. /// /// If the location is a function argument, determining the expected type /// involves considering all function overloads and the arguments so far. /// In this case, signature help for these function overloads will be reported /// as a side-effect (only if the completion point has been reached). QualType get(SourceLocation Tok) const { if (!Enabled || Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: bool Enabled; /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema final { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: /// The maximum alignment, same as in llvm::Value. We duplicate them here /// because that allows us not to duplicate the constants in clang code, /// which we must to since we can't directly use the llvm constants. /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp /// /// This is the greatest alignment value supported by load, store, and alloca /// instructions, and global values. static const unsigned MaxAlignmentExponent = 29; static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent; typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions CurFPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; api_notes::APINotesManager APINotes; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; // #pragma pack and align. class AlignPackInfo { public: // `Native` represents default align mode, which may vary based on the // platform. enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; // #pragma pack info constructor AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { assert(Num == PackNumber && "The pack number has been truncated."); } // #pragma align info constructor AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) : PackAttr(false), AlignMode(M), PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} AlignPackInfo() : AlignPackInfo(Native, false) {} // When a AlignPackInfo itself cannot be used, this returns an 32-bit // integer encoding for it. This should only be passed to // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. static uint32_t getRawEncoding(const AlignPackInfo &Info) { std::uint32_t Encoding{}; if (Info.IsXLStack()) Encoding |= IsXLMask; Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; if (Info.IsPackAttr()) Encoding |= PackAttrMask; Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; return Encoding; } static AlignPackInfo getFromRawEncoding(unsigned Encoding) { bool IsXL = static_cast<bool>(Encoding & IsXLMask); AlignPackInfo::Mode M = static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); int PackNumber = (Encoding & PackNumMask) >> 4; if (Encoding & PackAttrMask) return AlignPackInfo(M, PackNumber, IsXL); return AlignPackInfo(M, IsXL); } bool IsPackAttr() const { return PackAttr; } bool IsAlignAttr() const { return !PackAttr; } Mode getAlignMode() const { return AlignMode; } unsigned getPackNumber() const { return PackNumber; } bool IsPackSet() const { // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack // attriute on a decl. return PackNumber != UninitPackVal && PackNumber != 0; } bool IsXLStack() const { return XLStack; } bool operator==(const AlignPackInfo &Info) const { return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, Info.XLStack); } bool operator!=(const AlignPackInfo &Info) const { return !(*this == Info); } private: /// \brief True if this is a pragma pack attribute, /// not a pragma align attribute. bool PackAttr; /// \brief The alignment mode that is in effect. Mode AlignMode; /// \brief The pack number of the stack. unsigned char PackNumber; /// \brief True if it is a XL #pragma align/pack stack. bool XLStack; /// \brief Uninitialized pack value. static constexpr unsigned char UninitPackVal = -1; // Masks to encode and decode an AlignPackInfo. static constexpr uint32_t IsXLMask{0x0000'0001}; static constexpr uint32_t AlignModeMask{0x0000'0006}; static constexpr uint32_t PackAttrMask{0x00000'0008}; static constexpr uint32_t PackNumMask{0x0000'01F0}; }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value) { if (Action == PSK_Reset) { CurrentValue = DefaultValue; CurrentPragmaLocation = PragmaLocation; return; } if (Action & PSK_Push) Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, PragmaLocation); else if (Action & PSK_Pop) { if (!StackSlotLabel.empty()) { // If we've got a label, try to find it and jump there. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; }); // If we found the label so pop from there. if (I != Stack.rend()) { CurrentValue = I->Value; CurrentPragmaLocation = I->PragmaLocation; Stack.erase(std::prev(I.base()), Stack.end()); } } else if (!Stack.empty()) { // We do not have a label, just pop the last entry. CurrentValue = Stack.back().Value; CurrentPragmaLocation = Stack.back().PragmaLocation; Stack.pop_back(); } } if (Action & PSK_Set) { CurrentValue = Value; CurrentPragmaLocation = PragmaLocation; } } // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispMode> VtorDispStack; PragmaStack<AlignPackInfo> AlignPackStack; // The current #pragma align/pack values and locations at each #include. struct AlignPackIncludeState { AlignPackInfo CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // This stack tracks the current state of Sema.CurFPFeatures. PragmaStack<FPOptionsOverride> FpPragmaStack; FPOptionsOverride CurFPFeatureOverrides() { FPOptionsOverride result; if (!FpPragmaStack.hasValue()) { result = FPOptionsOverride(); } else { result = FpPragmaStack.CurrentValue; } return result; } // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, llvm::SmallPtrSet<Expr *, 4>>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; /// The index of the first FunctionScope that corresponds to the current /// context. unsigned FunctionScopesStart = 0; ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, FunctionScopes.end()); } /// Stack containing information needed when in C++2a an 'auto' is encountered /// in a function declaration parameter type specifier in order to invent a /// corresponding template parameter in the enclosing abbreviated function /// template. This information is also present in LambdaScopeInfo, stored in /// the FunctionScopes stack. SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; /// The index of the first InventedParameterInfo that refers to the current /// context. unsigned InventedParameterInfosStart = 0; ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { return llvm::makeArrayRef(InventedParameterInfos.begin() + InventedParameterInfosStart, InventedParameterInfos.end()); } typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; /// All the external declarations encoutered and used in the TU. SmallVector<VarDecl *, 4> ExternalDeclarations; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } /// \brief Callback to the parser to parse a type expressed as a string. std::function<TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback; // Does the work necessary to deal with a SYCL kernel lambda. At the moment, // this just marks the list of lambdas required to name the kernel. void AddSYCLKernelLambda(const FunctionDecl *FD); class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; unsigned SavedFunctionScopesStart; unsigned SavedInventedParameterInfosStart; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride), SavedFunctionScopesStart(S.FunctionScopesStart), SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); // Any saved FunctionScopes do not refer to this context. S.FunctionScopesStart = S.FunctionScopes.size(); S.InventedParameterInfosStart = S.InventedParameterInfos.size(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; S.FunctionScopesStart = SavedFunctionScopesStart; S.InventedParameterInfosStart = SavedInventedParameterInfosStart; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Whether the AST is currently being rebuilt to correct immediate /// invocations. Immediate invocation candidates and references to consteval /// functions aren't tracked when this is set. bool RebuildingImmediateInvocation = false; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// Set of candidates for starting an immediate invocation. llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; /// Set of DeclRefExprs referencing a consteval function when used in a /// context not already known to be immediately invoked. llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. const TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the CurFPFeatures state on entry/exit of compound /// statements. class FPFeaturesStateRAII { public: FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { OldOverrides = S.FpPragmaStack.CurrentValue; } ~FPFeaturesStateRAII() { S.CurFPFeatures = OldFPFeaturesState; S.FpPragmaStack.CurrentValue = OldOverrides; } FPOptionsOverride getOverrides() { return OldOverrides; } private: Sema& S; FPOptions OldFPFeaturesState; FPOptionsOverride OldOverrides; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; /// Increment when we find a reference; decrement when we find an ignored /// assignment. Ultimately the value is 0 if every reference is an ignored /// assignment. llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments; Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); /// This virtual key function only exists to limit the emission of debug info /// describing the Sema class. GCC and Clang only emit debug info for a class /// with a vtable when the vtable is emitted. Sema is final and not /// polymorphic, but the debug info size savings are so significant that it is /// worth adding a vtable just to take advantage of this optimization. virtual void anchor(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getCurFPFeatures() { return CurFPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, StringRef Platform); ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. ImmediateDiagBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class ImmediateDiagBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op // in that case anwyay. ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; ~ImmediateDiagBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First clear the diagnostic // builder itself so it won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template <typename T> friend const ImmediateDiagBuilder & operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const ImmediateDiagBuilder &operator<<(T &&V) const { const DiagnosticBuilder &BaseDiag = *this; BaseDiag << std::move(V); return *this; } }; /// A generic diagnostic builder for errors which may or may not be deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class SemaDiagnosticBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; ~SemaDiagnosticBuilder(); bool isImmediate() const { return ImmediateDiag.hasValue(); } /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (SemaDiagnosticBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a SemaDiagnosticBuilder yourself. operator bool() const { return isImmediate(); } template <typename T> friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const SemaDiagnosticBuilder &operator<<(T &&V) const { if (ImmediateDiag.hasValue()) *ImmediateDiag << std::move(V); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); return *this; } friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { if (Diag.ImmediateDiag.hasValue()) PD.Emit(*Diag.ImmediateDiag); else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; return Diag; } void AddFixItHint(const FixItHint &Hint) const { if (ImmediateDiag.hasValue()) ImmediateDiag->AddFixItHint(Hint); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); } friend ExprResult ExprError(const SemaDiagnosticBuilder &) { return ExprError(); } friend StmtResult StmtError(const SemaDiagnosticBuilder &) { return StmtError(); } operator ExprResult() const { return ExprError(); } operator StmtResult() const { return StmtError(); } operator TypeResult() const { return TypeError(); } operator DeclResult() const { return DeclResult(true); } operator MemInitResult() const { return MemInitResult(true); } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Is the last error level diagnostic immediate. This is used to determined /// whether the next info diagnostic should be immediate. bool IsLastErrorImmediate = true; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint = false); /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint = false); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h /// Whether deferrable diagnostics should be deferred. bool DeferDiags = false; /// RAII class to control scope of DeferDiags. class DeferDiagsRAII { Sema &S; bool SavedDeferDiags = false; public: DeferDiagsRAII(Sema &S, bool DeferDiags) : S(S), SavedDeferDiags(S.DeferDiags) { S.DeferDiags = DeferDiags; } ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; } }; /// Whether uncompilable error has occurred. This includes error happens /// in deferred diagnostics. bool hasUncompilableErrorOccurred() const; bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; /// Invent a new identifier for parameters of abbreviated templates. IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, unsigned Index); void emitAndClearUnusedLocalTypedefWarnings(); private: /// Function or variable declarations to be checked for whether the deferred /// diagnostics should be emitted. llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags; public: // Emit all deferred diagnostics. void emitDeferredDiags(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void setFunctionHasMustTail(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// Retrieve the current function, if any, that should be analyzed for /// potential availability violations. sema::FunctionScopeInfo *getCurFunctionAvailabilityContext(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } /// Called before parsing a function declarator belonging to a function /// declaration. void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth); /// Called after parsing a function declarator belonging to a function /// declaration. void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Stmt *E); /// Determine whether the callee of a particular function call can throw. /// E, D and Loc are all optional. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc = SourceLocation()); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { protected: unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; /// Do a check to make sure \p Name looks like a legal argument for the /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name /// is invalid for the given declaration. /// /// \p AL is used to provide caret diagnostics in case of a malformed name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, const ParsedAttr &AL, bool IsAsync); /// A derivative of BoundTypeDiagnoser for which the diagnostic's type /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. /// For example, a diagnostic with no other parameters would generally have /// the form "...%select{incomplete|sizeless}0 type %1...". template <typename... Ts> class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { public: SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); this->emit(DB, std::index_sequence_for<Ts...>()); DB << T->isSizelessType() << T; } }; enum class CompleteTypeKind { /// Apply the normal rules for complete types. In particular, /// treat all sizeless types as incomplete. Normal, /// Relax the normal rules for complete types so that they include /// sizeless built-in types. AcceptSizeless, // FIXME: Eventually we should flip the default to Normal and opt in // to AcceptSizeless rather than opt out of it. Default = AcceptSizeless }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(const Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); // When loading a non-modular PCH files, this is used to restore module // visibility. void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { VisibleModules.setVisible(Mod, ImportLoc); } /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return D->isUnconditionallyVisible() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind = CompleteTypeKind::Default) { return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, unsigned DiagID); bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); } bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); } template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); } /// Get the type of expression E, triggering instantiation to complete the /// type if necessary -- that is, if the expression refers to a templated /// static data member of incomplete array type. /// /// May still return an incomplete type if instantiation was not possible or /// if the type is incomplete for a different reason. Use /// RequireCompleteExprType instead if a diagnostic is expected for an /// incomplete expression type. QualType getCompletedType(Expr *E); void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType getDecltypeForParenthesizedExpr(Expr *E); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as an overload set, and an expression /// representing that overload set has been formed. /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable /// expression referencing the overload set. NC_OverloadSet, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, /// The name was classified as a concept name. NC_Concept, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification OverloadSet(ExprResult E) { NameClassification Result(NC_OverloadSet); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification Concept(TemplateName Name) { NameClassification Result(NC_Concept); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_OverloadSet); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_Concept: return TNK_Concept_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Act on the result of classifying a name as an overload set. ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); void warnOnReservedIdentifier(const NamedDecl *D); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); void diagnosePointerAuthDisabled(SourceLocation loc, SourceRange range); bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const BindingDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); QualType adjustParameterTypeForObjCAutoRefCount(QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Enter a template parameter scope, after it's been associated with a particular /// DeclContext. Causes lookup within the scope to chain through enclosing contexts /// in the correct order. void EnterTemplatedContext(Scope *S, DeclContext *DC); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, /// Merge availability attributes for an implementation of /// an optional protocol requirement. AMK_OptionalProtocolImplementation }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); WebAssemblyImportNameAttr *mergeImportNameAttr( Decl *D, const WebAssemblyImportNameAttr &AL); WebAssemblyImportModuleAttr *mergeImportModuleAttr( Decl *D, const WebAssemblyImportModuleAttr &AL); EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true, bool ConsiderRequiresClauses = true); enum class AllowedExplicit { /// Allow no explicit functions to be used. None, /// Allow explicit conversion functions but not explicit constructors. Conversions, /// Allow both explicit conversion functions and explicit constructors. All }; ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool IsStringInit(Expr *Init, const ArrayType *AT); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE, NamedDecl *Dest = nullptr); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfSingleOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); void AddOverloadedCallCandidates( LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL = true); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true, FunctionDecl *DefaultedFn = nullptr); ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, bool AllowRecovery = false); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up a name following ~ in a destructor name. This is an ordinary /// lookup, but prefers tags to typedefs. LookupDestructorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplatePack, }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, SourceLocation TypoLoc); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, bool IsUDSuffix); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit = nullptr); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final = false); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param RecoverUncorrectedTypos If true, when typo correction fails, it /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr( Expr *E, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr( ExprResult ER, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), InitDecl, RecoverUncorrectedTypos, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} /// Attempts to produce a RecoveryExpr after some AST node cannot be created. ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef<Expr *> SubExprs, QualType T = QualType()); ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( FunctionDecl *FD); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Handles semantic checking for features that are common to all attributes, /// such as checking whether a parameter was properly specified, or the /// correct number of arguments were passed, etc. Returns true if the /// attribute has been diagnosed. bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A); bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A); /// Map any API notes provided for this declaration to attributes on the /// declaration. /// /// Triggered by declaration-attribute processing. void ProcessAPINotes(Decl *D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); llvm::Error isValidSectionSpecifier(StringRef Str); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Check whether a nullability type specifier can be added to the given /// type through some means not written in source (e.g. API notes). /// /// \param type The type to which the nullability specifier will be /// added. On success, this type will be updated appropriately. /// /// \param nullability The nullability specifier to add. /// /// \param diagLoc The location to use for diagnostics. /// /// \param allowArrayTypes Whether to accept nullability specifiers on an /// array type (e.g., because it will decay to a pointer). /// /// \param overrideExisting Whether to override an existing, locally-specified /// nullability specifier rather than complaining about the conflict. /// /// \returns true if nullability cannot be applied, false otherwise. bool checkImplicitNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability, SourceLocation diagLoc, bool allowArrayTypes, bool overrideExisting); /// Process the attributes before creating an attributed statement. Returns /// the semantic attributes that have been processed. void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesWithRange &InAttrs, SmallVectorImpl<const Attr *> &OutAttrs); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnAfterCompoundStatementLeadingPragmas(); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult BuildAttributedStmt(SourceLocation AttrsLoc, ArrayRef<const Attr *> Attrs, Stmt *SubStmt); StmtResult ActOnAttributedStmt(const ParsedAttributesWithRange &AttrList, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); struct NamedReturnInfo { const VarDecl *Candidate; enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable }; Status S; bool isMoveEligible() const { return S != None; }; bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; } }; enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn }; NamedReturnInfo getNamedReturnInfo( Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal); NamedReturnInfo getNamedReturnInfo(const VarDecl *VD); const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves = false); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, NamedReturnInfo &NRInfo, bool SupressSimplerImplicitMoves); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// If VD is set but not otherwise used, diagnose, for a parameter or a /// variable. void DiagnoseUnusedButSetDecl(const VarDecl *VD); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { ParsingClassDepth++; return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { ParsingClassDepth--; DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Try to convert an expression \p E to type \p Ty. Returns the result of the /// conversion. ExprResult tryConvertExprToType(Expr *E, QualType Ty); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseDependentMemberLookup(LookupResult &R); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr( const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE = nullptr); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, TypeSourceInfo *TSI); ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType ParsedTy); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc); ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef<Expr *> Dims, ArrayRef<SourceRange> Brackets); /// Data structure for iterator expression. struct OMPIteratorData { IdentifierInfo *DeclIdent = nullptr; SourceLocation DeclIdentLoc; ParsedType Type; OMPIteratorExpr::IteratorRange Range; SourceLocation AssignLoc; SourceLocation ColonLoc; SourceLocation SecColonLoc; }; ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc, ArrayRef<OMPIteratorData> Data); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false, bool AllowRecovery = false); Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth); // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void FilterUsingLookup(Scope *S, LookupResult &lookup); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R = nullptr, const UsingDecl *UD = nullptr); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists); NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, EnumDecl *ED); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, const DeclSpec &); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); /// Wrap the expression in a ConstantExpr if it is a potential immediate /// invocation. ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr *> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); // Checks that the vector type should be initialized from a scalar // by splatting the value rather than populating a single element. // This is the case for AltiVecVector types as well as with // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified. bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy); /// ActOnCXXNamedCast - Parse /// {dynamic,static,reinterpret,const,addrspace}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); // Complete an enum decl, maybe without a scope spec. bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS = nullptr); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc, ExprResult RequiresClause); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, false is returned, and /// PossibleNonPrimary will be set to true if the failure might be due to a /// non-primary expression being used as an atomic constraint. bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), bool *PossibleNonPrimary = nullptr, bool IsTrailingRequiresClause = false); private: /// Caches pairs of template-like decls whose associated constraints were /// checked for subsumption and whether or not the first's constraints did in /// fact subsume the second's. llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; /// Caches the normalized associated constraints of declarations (concepts or /// constrained declarations). If an error occurred while normalizing the /// associated constraints of the template or concept, nullptr will be cached /// here. llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> SatisfactionCache; public: const NormalizedConstraint * getNormalizedAssociatedConstraints( NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); /// \brief Check whether the given declaration's associated constraints are /// at least as constrained than another declaration's according to the /// partial ordering of constraints. /// /// \param Result If no error occurred, receives the result of true if D1 is /// at least constrained than D2, and false otherwise. /// /// \returns true if an error occurred, false otherwise. bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2, bool &Result); /// If D1 was not at least as constrained as D2, but would've been if a pair /// of atomic constraints involved had been declared in a concept and not /// repeated in two separate places in code. /// \returns true if such a diagnostic was emitted, false otherwise. bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \param Template the template-like entity that triggered the constraints /// check (either a concept or a constrained entity). /// \param ConstraintExprs a list of constraint expressions, treated as if /// they were 'AND'ed together. /// \param TemplateArgs the list of template arguments to substitute into the /// constraint expression. /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// \param Satisfaction if true is returned, will contain details of the /// satisfaction, with enough information to diagnose an unsatisfied /// expression. /// \returns true if an error occurred and satisfaction could not be checked, /// false otherwise. bool CheckConstraintSatisfaction( const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); /// \brief Check whether the given non-dependent constraint expression is /// satisfied. Returns false and updates Satisfaction with the satisfaction /// verdict if successful, emits a diagnostic and returns true if an error /// occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction); /// Check whether the given function decl's trailing requires clause is /// satisfied, if any. Returns false and updates Satisfaction with the /// satisfaction verdict if successful, emits a diagnostic and returns true if /// an error occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc = SourceLocation()); /// \brief Ensure that the given template arguments satisfy the constraints /// associated with the given template, emitting a diagnostic if they do not. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateArgs The converted, canonicalized template arguments. /// /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// /// \returns true if the constrains are not satisfied or could not be checked /// for satisfaction, false if the constraints are satisfied. bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. /// \param First whether this is the first time an unsatisfied constraint is /// diagnosed for this error. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First = true); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, bool First = true); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's /// destructor is referenced. void MarkVirtualBaseDestructorsReferenced( SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); /// Do semantic checks to allow the complete destructor variant to be emitted /// when the destructor is defined in another translation unit. In the Itanium /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they /// can be emitted in separate TUs. To emit the complete variant, run a subset /// of the checks performed when emitting a regular destructor. void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref<Scope *()> EnterScope); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK); void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship); void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbiguousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType) { return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, SourceLocation(), PDiag()); } void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; /// Whether and why a template name is required in this lookup. class RequiredTemplateKind { public: /// Template name is required if TemplateKWLoc is valid. RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) : TemplateKW(TemplateKWLoc) {} /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} SourceLocation getTemplateKeywordLoc() const { return TemplateKW.getValueOr(SourceLocation()); } bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } bool isRequired() const { return TemplateKW != SourceLocation(); } explicit operator bool() const { return isRequired(); } private: llvm::Optional<SourceLocation> TemplateKW; }; enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName( LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate = SourceLocation(), AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation = false); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint); bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack); bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool RequireStructuralType(QualType T, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic = false); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template<int X>, this would return an expression template /// argument referencing X. TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); /// Get the specialization of the given variable template corresponding to /// the specified argument list, or a null-but-valid result if the arguments /// are dependent. DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); /// Form a reference to the specialization of the given variable template /// corresponding to the specified argument list, or a null-but-valid result /// if the arguments are dependent. ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true, bool *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, bool DeducedTSTContext = true); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); //===--------------------------------------------------------------------===// // C++ Concepts //===--------------------------------------------------------------------===// Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef<ParmVarDecl *> LocalParameters, Scope *BodyScope); void ActOnFinishRequiresExpr(); concepts::Requirement *ActOnSimpleRequirement(Expr *E); concepts::Requirement *ActOnTypeRequirement( SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); concepts::Requirement *ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc); concepts::Requirement * ActOnCompoundRequirement( Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, unsigned Depth); concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); concepts::ExprRequirement * BuildExprRequirement( Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::ExprRequirement * BuildExprRequirement( concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); concepts::TypeRequirement * BuildTypeRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); concepts::NestedRequirement *BuildNestedRequirement(Expr *E); concepts::NestedRequirement * BuildNestedRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> LocalParameters, ArrayRef<concepts::Requirement *> Requirements, SourceLocation ClosingBraceLoc); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression. UPPC_Block, /// A type constraint. UPPC_TypeConstraint, // A requirement in a requires-expression. UPPC_Requirement, // A requires-clause. UPPC_RequiresClause, }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given requirees-expression contains an unexpanded reference to one /// of its own parameter packs, diagnose the error. /// /// \param RE The requiress-expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate( FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2, bool Reversed = false); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are instantiating a requirement of a requires expression. RequirementInstantiation, /// We are checking the satisfaction of a nested requirement of a requires /// expression. NestedRequirementConstraintsCheck, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are declaring an implicit 'operator==' for a defaulted /// 'operator<=>'. DeclaringImplicitEqualityComparison, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, // We are normalizing a constraint expression. ConstraintNormalization, // We are substituting into the parameter mapping of an atomic constraint // during normalization. ParameterMappingSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// We are initializing a structured binding. InitializingStructuredBinding, /// We are marking a class as __dllexport. MarkingClassDllexported, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, NamedDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); struct ConstraintNormalization {}; /// \brief Note that we are normalizing a constraint expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintNormalization, NamedDecl *Template, SourceRange InstantiationRange); struct ParameterMappingSubstitution {}; /// \brief Note that we are subtituting into the parameter mapping of an /// atomic constraint during constraint normalization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParameterMappingSubstitution, NamedDecl *Template, SourceRange InstantiationRange); /// \brief Note that we are substituting template arguments into a part of /// a requirement of a requires expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are checking the satisfaction of the constraint /// expression inside of a nested requirement. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::NestedRequirement *Req, ConstraintsCheck, SourceRange InstantiationRange = SourceRange()); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } else { // Template instantiations in the PCH may be delayed until the TU. S.PendingInstantiations.swap(SavedPendingInstantiations); S.PendingInstantiations.insert(S.PendingInstantiations.end(), SavedPendingInstantiations.begin(), SavedPendingInstantiations.end()); } } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the name and return type of a defaulted 'operator<=>' to form /// an implicit 'operator=='. FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); bool CheckInstantiatedFunctionTemplateConstraints( SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef<TemplateArgument> TemplateArgs, ConstraintSatisfaction &Satisfaction); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); void deduceOpenCLAddressSpace(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; /// Check whether the declared result type of the given Objective-C /// method declaration is compatible with the method's class. ResultTypeCompatibilityKind checkRelatedResultTypeCompatibility(const ObjCMethodDecl *Method, const ObjCInterfaceDecl *CurrentClass); void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden); void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaAlignPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaAlignPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// Are precise floating point semantics currently enabled? bool isPreciseFPEnabled() { return !CurFPFeatures.getAllowFPReassociate() && !CurFPFeatures.getNoSignedZero() && !CurFPFeatures.getAllowReciprocal() && !CurFPFeatures.getAllowApproxFunc(); } /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); /// Called on well formed /// \#pragma clang fp reassociate void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// Called to set constant rounding mode for floating point operations. void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); /// Called to set exception behavior for floating point operations. void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef<Expr *> Args); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); /// Check that the expression co_await promise.final_suspend() shall not be /// potentially-throwing. bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; struct DeclareTargetContextInfo { struct MapInfo { OMPDeclareTargetDeclAttr::MapTypeTy MT; SourceLocation Loc; }; /// Explicitly listed variables and functions in a 'to' or 'link' clause. llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped; /// The 'device_type' as parsed from the clause. OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any; /// The directive kind, `begin declare target` or `declare target`. OpenMPDirectiveKind Kind; /// The directive location. SourceLocation Loc; DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc) : Kind(Kind), Loc(Loc) {} }; /// Number of nested '#pragma omp declare target' directives. SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true, bool SuppressExprDiags = false); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Analyzes and checks a loop nest for use by a loop transformation. /// /// \param Kind The loop transformation directive kind. /// \param NumLoops How many nested loops the directive is expecting. /// \param AStmt Associated statement of the transformation directive. /// \param LoopHelpers [out] The loop analysis result. /// \param Body [out] The body code nested in \p NumLoops loop. /// \param OriginalInits [out] Collection of statements and declarations that /// must have been executed/declared before entering the /// loop. /// /// \return Whether there was any error. bool checkTransformableLoopNest( OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, Stmt *&Body, SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> &OriginalInits); /// Helper to keep information about the current `omp begin/end declare /// variant` nesting. struct OMPDeclareVariantScope { /// The associated OpenMP context selector. OMPTraitInfo *TI; /// The associated OpenMP context selector mangling. std::string NameSuffix; OMPDeclareVariantScope(OMPTraitInfo &TI); }; /// Return the OMPTraitInfo for the surrounding scope, if any. OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { return OMPDeclareVariantScopes.empty() ? nullptr : OMPDeclareVariantScopes.back().TI; } /// The current `omp begin/end declare variant` scopes. SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; /// The current `omp begin/end assumes` scopes. SmallVector<AssumptionAttr *, 4> OMPAssumeScoped; /// All `omp assumes` we encountered so far. SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal; public: /// The declarator \p D defines a function in the scope \p S which is nested /// in an `omp begin/end declare variant` scope. In this method we create a /// declaration for \p D and rename \p D according to the OpenMP context /// selector of the surrounding scope. Return all base functions in \p Bases. void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl<FunctionDecl *> &Bases); /// Register \p D as specialization of all base functions in \p Bases in the /// current `omp begin/end declare variant` scope. void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`. void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D); /// Can we exit an OpenMP declare variant scope at the moment. bool isInOpenMPDeclareVariantScope() const { return !OMPDeclareVariantScopes.empty(); } /// Given the potential call expression \p Call, determine if there is a /// specialization via the OpenMP declare variant mechanism available. If /// there is, return the specialized call expression, otherwise return the /// original \p Call. ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig); /// Handle a `omp begin declare variant`. void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); /// Handle a `omp end declare variant`. void ActOnOpenMPEndDeclareVariant(); /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; /// Check if the specified global variable must be captured by outer capture /// regions. /// \param Level Relative level of nested OpenMP construct for that /// the check is performed. bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp [begin] assume[s]'. void ActOnOpenMPAssumesDirective(SourceLocation Loc, OpenMPDirectiveKind DKind, ArrayRef<StringRef> Assumptions, bool SkippedClauses); /// Check if there is an active global `omp begin assumes` directive. bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); } /// Check if there is an active global `omp assumes` directive. bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); } /// Called on well-formed '#pragma omp end assumes'. void ActOnOpenMPEndAssumesDirective(); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; const ValueDecl *getOpenMPDeclareMapperVarName() const; /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Called at the end of target region i.e. '#pragma omp end declare target'. const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective(); /// Called once a target context is completed, that can be when a /// '#pragma omp end declare target' was encountered or when a /// '#pragma omp declare target' without declaration-definition-seq was /// encountered. void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return !DeclareTargetNesting.empty(); } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to /// an OpenMP loop directive. StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '#pragma omp tile' after parsing of its clauses and /// the associated statement. StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '#pragma omp unroll' after parsing of its clauses /// and the associated statement. StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp depobj'. StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp scan'. StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp interop'. StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp dispatch' after parsing of the // /associated statement. StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp masked' after parsing of the // /associated statement. StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type, bool IsDeclareSimd = false); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The trait info object representing the match clause. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The context traits associated with the function variant. void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-form 'sizes' clause. OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-form 'full' clauses. OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-form 'partial' clauses. OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'detach' clause. OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'order' clause. OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acq_rel' clause. OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acquire' clause. OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'release' clause. OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'relaxed' clause. OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'init' clause. OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, bool IsTarget, bool IsTargetSync, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'use' clause. OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'destroy' clause. OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'novariants' clause. OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'nocontext' clause. OMPClause *ActOnOpenMPNocontextClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'filter' clause. OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation ExtraModifierLoc, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc); /// Called on well-formed 'inclusive' clause. OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'exclusive' clause. OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause( ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depobj' pseudo clause. OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause * ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'use_device_addr' clause. OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'nontemporal' clause. OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Data for list of allocators. struct UsesAllocatorsData { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; /// Called on well-formed 'uses_allocators' clause. OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<UsesAllocatorsData> Data); /// Called on well-formed 'affinity' clause. OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This function is a no-op if the operand has a function type // or an array type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. In the success case, /// the statement is rewritten to remove implicit nodes from the return /// value. bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA); private: /// Check whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. bool checkMustTailAttr(const Stmt *St, const Attr &MTA); public: /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); /// Context in which we're performing a usual arithmetic conversion. enum ArithConvKind { /// An arithmetic operation. ACK_Arithmetic, /// A bitwise operation. ACK_BitwiseOp, /// A comparison. ACK_Comparison, /// A conditional (?:) operator. ACK_Conditional, /// A compound assignment expression. ACK_CompAssign, }; // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatibleFunctionPointer - The assignment is between two function /// pointers types that are not compatible, but we accept them as an /// extension. IncompatibleFunctionPointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); /// Type checking for matrix binary operators. QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); bool isValidSveBitcast(QualType srcType, QualType destType); bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy); bool areVectorTypesSameSize(QualType srcType, QualType destType); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; // Fake up a scoped enumeration that still contextually converts to bool. struct ReferenceConversionsScope { /// The conversions that would be performed on an lvalue of type T2 when /// binding a reference of type T1 to it, as determined when evaluating /// whether T1 is reference-compatible with T2. enum ReferenceConversions { Qualification = 0x1, NestedQualification = 0x2, Function = 0x4, DerivedToBase = 0x8, ObjC = 0x10, ObjCLifetime = 0x20, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckMatrixCast - Check type constraints for matrix casts. // We allow casting between matrixes of the same dimensions i.e. when they // have the same number of rows and column. Returns true if the cast is // invalid. bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) = 0; virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); virtual ~VerifyICEDiagnoser() {} }; enum AllowFoldKind { NoFold, AllowFold, }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, AllowFoldKind CanFold = NoFold) { return VerifyIntegerConstantExpression(E, nullptr, CanFold); } /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics /// unless \p EmitOnBothSides is true. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD = nullptr); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, FunctionDecl *FD = nullptr) { return targetDiag(Loc, PD.getDiagID(), FD) << PD; } /// Check if the expression is allowed to be used in expressions for the /// offloading devices. void checkDeviceDecl(ValueDecl *D, SourceLocation Loc); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); enum CUDAVariableTarget { CVT_Device, /// Emitted on device side with a shadow variable on host side CVT_Host, /// Emitted on host side only CVT_Both, /// Emitted on both sides with different addresses CVT_Unified, /// Emitted as a unified address, e.g. managed variables }; /// Determines whether the given variable is emitted on host or device side. CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); /// May add implicit CUDAConstantAttr attribute to VD, depending on VD /// and current compilation settings. void MaybeAddCUDAConstantAttr(VarDecl *VD); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas by default is host device function unless it has explicit /// host or device attribute. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Determines the preferred type of the current function argument, by /// examining the signatures of all possible overloads. /// Returns null if unknown or ambiguous, or if code completion is off. /// /// If the code completion point has been reached, also reports the function /// signatures that were considered. /// /// FIXME: rename to GuessCallArgumentType to reduce confusion. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); /// Trigger code completion for a record of \p BaseType. \p InitExprs are /// expressions in the initializer list seen so far and \p D is the current /// Designation being parsed. void CodeCompleteDesignator(const QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D); void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteAfterFunctionEquals(Declarator &D); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, StringRef ParamName, QualType ArgTy, QualType ParamTy); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, bool WantCDE); bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum); bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinComplex(CallExpr *TheCall); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinArithmeticFence(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc); bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); bool SemaBuiltinElementwiseMath(CallExpr *TheCall); bool SemaBuiltinElementwiseMathOneArg(CallExpr *TheCall); bool SemaBuiltinReduceMath(CallExpr *TheCall); // Matrix builtin handling. ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, ExprResult CallResult); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckFreeArguments(const CallExpr *E); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(const Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Nullable_result = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; bool isCFError(RecordDecl *D); /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// Determine the number of levels of enclosing template parameters. This is /// only usable while parsing. Note that this does not include dependent /// contexts in which no template parameters have yet been declared, such as /// in a terse function template or generic lambda before the first 'auto' is /// encountered. unsigned getTemplateDepth(Scope *S) const; /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: int ParsingClassDepth = 0; class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurLexicalContext is a kernel function or it is known that the /// function will be emitted for the device, emits the diagnostics /// immediately. /// - If CurLexicalContext is a function and we are compiling /// for the device, but we don't know that this function will be codegen'ed /// for devive yet, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// Diagnose __float128 type usage only from SYCL device code if the current /// target doesn't support it /// if (!S.Context.getTargetInfo().hasFloat128Type() && /// S.getLangOpts().SYCLIsDevice) /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed, creates a deferred diagnostic to be emitted if /// and when the caller is codegen'ed, and returns true. /// /// - Otherwise, returns true without emitting any diagnostics. /// /// Adds Callee to DeviceCallGraph if we don't know if its caller will be /// codegen'ed yet. bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; template <> void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, AlignPackInfo Value); } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getHashValue()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
mpifft.c
/* -*- mode: C; tab-width: 2; indent-tabs-mode: nil; fill-column: 79; coding: iso-latin-1-unix -*- */ /* mpifft.c */ #include <hpcc.h> #include "hpccfft.h" #include "wrapmpifftw.h" double *HPCC_fft_timings_forward, *HPCC_fft_timings_backward; static void MPIFFT0(HPCC_Params *params, int doIO, FILE *outFile, MPI_Comm comm, int locN, double *UGflops, s64Int_t *Un, double *UmaxErr, int *Ufailure) { int commRank, commSize, failure, flags; s64Int_t i, n; s64Int_t locn, loc0, alocn, aloc0, tls; double maxErr, tmp1, tmp2, tmp3, t0, t1, t2, t3, Gflops; double deps; fftw_complex *inout, *work; fftw_mpi_plan p; hpcc_fftw_mpi_plan ip; int sAbort, rAbort; #ifdef USING_FFTW int ilocn, iloc0, ialocn, ialoc0, itls; #endif failure = 1; Gflops = -1.0; deps = HPL_dlamch( HPL_MACH_EPS ); maxErr = 1.0 / deps; MPI_Comm_size( comm, &commSize ); MPI_Comm_rank( comm, &commRank ); n = locN; /* number of processes have been factored out - need to put it back in */ n *= commSize; n *= commSize; /* global vector size */ #ifdef USING_FFTW /* FFTW ver. 2 only supports vector sizes that fit in 'int' */ if (n > (1<<30)-1+(1<<30)) { #ifdef HPCC_FFTW_CHECK32 goto no_plan; #else if (doIO) { fprintf( outFile, "Warning: problem size too large: %ld*%d*%d\n", (long)(n / commSize / commSize), commSize, commSize ); } #endif } #endif #ifdef HPCC_FFTW_ESTIMATE flags = FFTW_ESTIMATE; #else flags = FFTW_MEASURE; #endif t1 = -MPI_Wtime(); p = fftw_mpi_create_plan( comm, n, FFTW_FORWARD, flags ); t1 += MPI_Wtime(); if (! p) goto no_plan; #ifdef USING_FFTW fftw_mpi_local_sizes( p, &ilocn, &iloc0, &ialocn, &ialoc0, &itls ); locn = ilocn; loc0 = iloc0; alocn = ialocn; aloc0 = ialoc0; tls = itls; #else fftw_mpi_local_sizes( p, &locn, &loc0, &alocn, &aloc0, &tls ); #endif inout = (fftw_complex *)HPCC_fftw_malloc( tls * (sizeof *inout) ); work = (fftw_complex *)HPCC_fftw_malloc( tls * (sizeof *work) ); sAbort = 0; if (! inout || ! work) sAbort = 1; MPI_Allreduce( &sAbort, &rAbort, 1, MPI_INT, MPI_SUM, comm ); if (rAbort > 0) { fftw_mpi_destroy_plan( p ); goto comp_end; } /* Make sure that `inout' and `work' are initialized in parallel if using Open MP: this will ensure better placement of pages if first-touch policy is used by a distrubuted shared memory machine. */ #ifdef _OPENMP #pragma omp parallel for for (i = 0; i < tls; ++i) { c_re( inout[i] ) = c_re( work[i] ) = 0.0; c_re( inout[i] ) = c_im( work[i] ) = 0.0; } #endif t0 = -MPI_Wtime(); HPCC_bcnrand( 2 * tls, 53 * commRank * 2 * tls, inout ); t0 += MPI_Wtime(); /* *void fftw_mpi(fftw_mpi_plan p, int n_fields, fftw_complex *local_data, fftw_complex *work); */ t2 = -MPI_Wtime(); fftw_mpi( p, 1, inout, work ); t2 += MPI_Wtime(); fftw_mpi_destroy_plan( p ); ip = HPCC_fftw_mpi_create_plan( comm, n, FFTW_BACKWARD, FFTW_ESTIMATE ); if (ip) { t3 = -MPI_Wtime(); HPCC_fftw_mpi( ip, 1, inout, work ); t3 += MPI_Wtime(); HPCC_fftw_mpi_destroy_plan( ip ); } HPCC_bcnrand( 2 * tls, 53 * commRank * 2 * tls, work ); /* regenerate data */ maxErr = 0.0; for (i = 0; i < locn; ++i) { tmp1 = c_re( inout[i] ) - c_re( work[i] ); tmp2 = c_im( inout[i] ) - c_im( work[i] ); tmp3 = sqrt( tmp1*tmp1 + tmp2*tmp2 ); maxErr = maxErr >= tmp3 ? maxErr : tmp3; } MPI_Allreduce( &maxErr, UmaxErr, 1, MPI_DOUBLE, MPI_MAX, comm ); maxErr = *UmaxErr; if (maxErr / log(n) / deps < params->test.thrsh) failure = 0; if (t2 > 0.0) Gflops = 1e-9 * (5.0 * n * log(n) / log(2.0)) / t2; if (doIO) { fprintf( outFile, "Number of nodes: %d\n", commSize ); fprintf( outFile, "Vector size: %20.0f\n", tmp1 = (double)n ); fprintf( outFile, "Generation time: %9.3f\n", t0 ); fprintf( outFile, "Tuning: %9.3f\n", t1 ); fprintf( outFile, "Computing: %9.3f\n", t2 ); fprintf( outFile, "Inverse FFT: %9.3f\n", t3 ); fprintf( outFile, "max(|x-x0|): %9.3e\n", maxErr ); fprintf( outFile, "Gflop/s: %9.3f\n", Gflops ); } comp_end: if (work) HPCC_fftw_free( work ); if (inout) HPCC_fftw_free( inout ); no_plan: *UGflops = Gflops; *Un = n; *UmaxErr = maxErr; *Ufailure = failure; } int HPCC_MPIFFT(HPCC_Params *params) { int commRank, commSize; int locN, procCnt, isComputing, doIO, failure = 0; s64Int_t n; double Gflops = -1.0, maxErr = -1.0; MPI_Comm comm; FILE *outFile; MPI_Comm_size( MPI_COMM_WORLD, &commSize ); MPI_Comm_rank( MPI_COMM_WORLD, &commRank ); doIO = commRank == 0 ? 1 : 0; if (doIO) { outFile = fopen( params->outFname, "a" ); if (! outFile) outFile = stderr; } /* There are two vectors of size 'n'/'commSize': inout, work, and internal work: 2*'n'/'commSize'; it's 4 vectors then. FFTE requires that the global vector size 'n' has to be at least as big as square of number of processes. The square is calculated in each factor independently. In other words, 'n' has to have at least twice as many 2 factors as the process count, twice as many 3 factors and twice as many 5 factors. */ #ifdef HPCC_FFT_235 locN = 0; procCnt = commSize + 1; do { int f[3]; procCnt--; for ( ; procCnt > 1 && HPCC_factor235( procCnt, f ); procCnt--) ; /* EMPTY */ /* Make sure the local vector size is greater than 0 */ locN = HPCC_LocalVectorSize( params, 4*procCnt, sizeof(fftw_complex), 0 ); for ( ; locN >= 1 && HPCC_factor235( locN, f ); locN--) ; /* EMPTY */ } while (locN < 1); #else /* Find power of two that is smaller or equal to number of processes */ for (procCnt = 1; procCnt <= (commSize >> 1); procCnt <<= 1) ; /* EMPTY */ /* Make sure the local vector size is greater than 0 */ while (1) { locN = HPCC_LocalVectorSize( params, 4*procCnt, sizeof(fftw_complex), 1 ); if (locN) break; procCnt >>= 1; } #endif isComputing = commRank < procCnt ? 1 : 0; HPCC_fft_timings_forward = params->MPIFFTtimingsForward; HPCC_fft_timings_backward = params->MPIFFTtimingsBackward; if (commSize == procCnt) comm = MPI_COMM_WORLD; else MPI_Comm_split( MPI_COMM_WORLD, isComputing ? 0 : MPI_UNDEFINED, commRank, &comm ); if (isComputing) MPIFFT0( params, doIO, outFile, comm, locN, &Gflops, &n, &maxErr, &failure ); if (commSize != procCnt && isComputing && comm != MPI_COMM_NULL) MPI_Comm_free( &comm ); params->MPIFFT_N = n; params->MPIFFT_Procs = procCnt; params->MPIFFT_maxErr = maxErr; MPI_Bcast( &Gflops, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD ); params->MPIFFTGflops = Gflops; params->FFTEnblk = FFTE_NBLK; params->FFTEnp = FFTE_NP; params->FFTEl2size = FFTE_L2SIZE; if (failure) params->Failure = 1; if (doIO) if (outFile != stderr) fclose( outFile ); return 0; }
integrateFullOrbit.c
/* Wrappers around the C integration code for Full Orbits */ #ifdef _WIN32 #include <Python.h> #endif #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <bovy_coords.h> #include <bovy_symplecticode.h> #include <leung_dop853.h> #include <bovy_rk.h> #include <integrateFullOrbit.h> //Potentials #include <galpy_potentials.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef ORBITS_CHUNKSIZE #define ORBITS_CHUNKSIZE 1 #endif //Macros to export functions in DLL on different OS #if defined(_WIN32) #define EXPORT __declspec(dllexport) #elif defined(__GNUC__) #define EXPORT __attribute__((visibility("default"))) #else // Just do nothing? #define EXPORT #endif #ifdef _WIN32 // On Windows, *need* to define this function to allow the package to be imported #if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit_libgalpy(void) { // Python 3 return NULL; } #else PyMODINIT_FUNC initlibgalpy(void) {} // Python 2 #endif #endif /* Function Declarations */ void evalRectForce(double, double *, double *, int, struct potentialArg *); void evalRectDeriv(double, double *, double *, int, struct potentialArg *); void evalRectDeriv_dxdv(double,double *, double *, int, struct potentialArg *); void initMovingObjectSplines(struct potentialArg *, double ** pot_args); void initChandrasekharDynamicalFrictionSplines(struct potentialArg *, double ** pot_args); /* Actual functions */ void parse_leapFuncArgs_Full(int npot, struct potentialArg * potentialArgs, int ** pot_type, double ** pot_args){ int ii,jj,kk; int nR, nz, nr; double * Rgrid, * zgrid, * potGrid_splinecoeffs; init_potentialArgs(npot,potentialArgs); for (ii=0; ii < npot; ii++){ switch ( *(*pot_type)++ ) { case 0: //LogarithmicHaloPotential, 4 arguments potentialArgs->potentialEval= &LogarithmicHaloPotentialEval; potentialArgs->Rforce= &LogarithmicHaloPotentialRforce; potentialArgs->zforce= &LogarithmicHaloPotentialzforce; potentialArgs->phiforce= &LogarithmicHaloPotentialphiforce; potentialArgs->dens= &LogarithmicHaloPotentialDens; //potentialArgs->R2deriv= &LogarithmicHaloPotentialR2deriv; //potentialArgs->planarphi2deriv= &ZeroForce; //potentialArgs->planarRphideriv= &ZeroForce; potentialArgs->nargs= 4; potentialArgs->requiresVelocity= false; break; case 1: //DehnenBarPotential, 6 arguments potentialArgs->Rforce= &DehnenBarPotentialRforce; potentialArgs->phiforce= &DehnenBarPotentialphiforce; potentialArgs->zforce= &DehnenBarPotentialzforce; potentialArgs->nargs= 6; potentialArgs->requiresVelocity= false; break; case 5: //MiyamotoNagaiPotential, 3 arguments potentialArgs->potentialEval= &MiyamotoNagaiPotentialEval; potentialArgs->Rforce= &MiyamotoNagaiPotentialRforce; potentialArgs->zforce= &MiyamotoNagaiPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &MiyamotoNagaiPotentialDens; //potentialArgs->R2deriv= &MiyamotoNagaiPotentialR2deriv; //potentialArgs->planarphi2deriv= &ZeroForce; //potentialArgs->planarRphideriv= &ZeroForce; potentialArgs->nargs= 3; potentialArgs->requiresVelocity= false; break; case 7: //PowerSphericalPotential, 2 arguments potentialArgs->potentialEval= &PowerSphericalPotentialEval; potentialArgs->Rforce= &PowerSphericalPotentialRforce; potentialArgs->zforce= &PowerSphericalPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &PowerSphericalPotentialDens; //potentialArgs->R2deriv= &PowerSphericalPotentialR2deriv; //potentialArgs->planarphi2deriv= &ZeroForce; //potentialArgs->planarRphideriv= &ZeroForce; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 8: //HernquistPotential, 2 arguments potentialArgs->potentialEval= &HernquistPotentialEval; potentialArgs->Rforce= &HernquistPotentialRforce; potentialArgs->zforce= &HernquistPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &HernquistPotentialDens; //potentialArgs->R2deriv= &HernquistPotentialR2deriv; //potentialArgs->planarphi2deriv= &ZeroForce; //potentialArgs->planarRphideriv= &ZeroForce; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 9: //NFWPotential, 2 arguments potentialArgs->potentialEval= &NFWPotentialEval; potentialArgs->Rforce= &NFWPotentialRforce; potentialArgs->zforce= &NFWPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &NFWPotentialDens; //potentialArgs->R2deriv= &NFWPotentialR2deriv; //potentialArgs->planarphi2deriv= &ZeroForce; //potentialArgs->planarRphideriv= &ZeroForce; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 10: //JaffePotential, 2 arguments potentialArgs->potentialEval= &JaffePotentialEval; potentialArgs->Rforce= &JaffePotentialRforce; potentialArgs->zforce= &JaffePotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &JaffePotentialDens; //potentialArgs->R2deriv= &JaffePotentialR2deriv; //potentialArgs->planarphi2deriv= &ZeroForce; //potentialArgs->planarRphideriv= &ZeroForce; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 11: //DoubleExponentialDiskPotential, XX arguments potentialArgs->potentialEval= &DoubleExponentialDiskPotentialEval; potentialArgs->Rforce= &DoubleExponentialDiskPotentialRforce; potentialArgs->zforce= &DoubleExponentialDiskPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &DoubleExponentialDiskPotentialDens; //Look at pot_args to figure out the number of arguments potentialArgs->nargs= (int) (5 + 4 * *(*pot_args+4) ); potentialArgs->requiresVelocity= false; break; case 12: //FlattenedPowerPotential, 4 arguments potentialArgs->potentialEval= &FlattenedPowerPotentialEval; potentialArgs->Rforce= &FlattenedPowerPotentialRforce; potentialArgs->zforce= &FlattenedPowerPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &FlattenedPowerPotentialDens; potentialArgs->nargs= 4; potentialArgs->requiresVelocity= false; break; case 13: //interpRZPotential, XX arguments //Grab the grids and the coefficients nR= (int) *(*pot_args)++; nz= (int) *(*pot_args)++; Rgrid= (double *) malloc ( nR * sizeof ( double ) ); zgrid= (double *) malloc ( nz * sizeof ( double ) ); potGrid_splinecoeffs= (double *) malloc ( nR * nz * sizeof ( double ) ); for (kk=0; kk < nR; kk++) *(Rgrid+kk)= *(*pot_args)++; for (kk=0; kk < nz; kk++) *(zgrid+kk)= *(*pot_args)++; for (kk=0; kk < nR; kk++) put_row(potGrid_splinecoeffs,kk,*pot_args+kk*nz,nz); *pot_args+= nR*nz; potentialArgs->i2d= interp_2d_alloc(nR,nz); interp_2d_init(potentialArgs->i2d,Rgrid,zgrid,potGrid_splinecoeffs, INTERP_2D_LINEAR); //latter bc we already calculated the coeffs potentialArgs->accx= gsl_interp_accel_alloc (); potentialArgs->accy= gsl_interp_accel_alloc (); for (kk=0; kk < nR; kk++) put_row(potGrid_splinecoeffs,kk,*pot_args+kk*nz,nz); *pot_args+= nR*nz; potentialArgs->i2drforce= interp_2d_alloc(nR,nz); interp_2d_init(potentialArgs->i2drforce,Rgrid,zgrid,potGrid_splinecoeffs, INTERP_2D_LINEAR); //latter bc we already calculated the coeffs potentialArgs->accxrforce= gsl_interp_accel_alloc (); potentialArgs->accyrforce= gsl_interp_accel_alloc (); for (kk=0; kk < nR; kk++) put_row(potGrid_splinecoeffs,kk,*pot_args+kk*nz,nz); *pot_args+= nR*nz; potentialArgs->i2dzforce= interp_2d_alloc(nR,nz); interp_2d_init(potentialArgs->i2dzforce,Rgrid,zgrid,potGrid_splinecoeffs, INTERP_2D_LINEAR); //latter bc we already calculated the coeffs potentialArgs->accxzforce= gsl_interp_accel_alloc (); potentialArgs->accyzforce= gsl_interp_accel_alloc (); potentialArgs->potentialEval= &interpRZPotentialEval; potentialArgs->Rforce= &interpRZPotentialRforce; potentialArgs->zforce= &interpRZPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->nargs= 2; //clean up free(Rgrid); free(zgrid); free(potGrid_splinecoeffs); potentialArgs->requiresVelocity= false; break; case 14: //IsochronePotential, 2 arguments potentialArgs->potentialEval= &IsochronePotentialEval; potentialArgs->Rforce= &IsochronePotentialRforce; potentialArgs->zforce= &IsochronePotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &IsochronePotentialDens; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 15: //PowerSphericalwCutoffPotential, 3 arguments potentialArgs->potentialEval= &PowerSphericalPotentialwCutoffEval; potentialArgs->Rforce= &PowerSphericalPotentialwCutoffRforce; potentialArgs->zforce= &PowerSphericalPotentialwCutoffzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &PowerSphericalPotentialwCutoffDens; //potentialArgs->R2deriv= &PowerSphericalPotentialR2deriv; //potentialArgs->planarphi2deriv= &ZeroForce; //potentialArgs->planarRphideriv= &ZeroForce; potentialArgs->nargs= 3; potentialArgs->requiresVelocity= false; break; case 16: //KuzminKutuzovStaeckelPotential, 3 arguments potentialArgs->potentialEval= &KuzminKutuzovStaeckelPotentialEval; potentialArgs->Rforce= &KuzminKutuzovStaeckelPotentialRforce; potentialArgs->zforce= &KuzminKutuzovStaeckelPotentialzforce; potentialArgs->phiforce= &ZeroForce; //potentialArgs->R2deriv= &KuzminKutuzovStaeckelPotentialR2deriv; potentialArgs->nargs= 3; potentialArgs->requiresVelocity= false; break; case 17: //PlummerPotential, 2 arguments potentialArgs->potentialEval= &PlummerPotentialEval; potentialArgs->Rforce= &PlummerPotentialRforce; potentialArgs->zforce= &PlummerPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &PlummerPotentialDens; //potentialArgs->R2deriv= &PlummerPotentialR2deriv; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 18: //PseudoIsothermalPotential, 2 arguments potentialArgs->potentialEval= &PseudoIsothermalPotentialEval; potentialArgs->Rforce= &PseudoIsothermalPotentialRforce; potentialArgs->zforce= &PseudoIsothermalPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &PseudoIsothermalPotentialDens; //potentialArgs->R2deriv= &PseudoIsothermalPotentialR2deriv; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 19: //KuzminDiskPotential, 2 arguments potentialArgs->potentialEval= &KuzminDiskPotentialEval; potentialArgs->Rforce= &KuzminDiskPotentialRforce; potentialArgs->zforce= &KuzminDiskPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 20: //BurkertPotential, 2 arguments potentialArgs->potentialEval= &BurkertPotentialEval; potentialArgs->Rforce= &BurkertPotentialRforce; potentialArgs->zforce= &BurkertPotentialzforce; potentialArgs->dens= &BurkertPotentialDens; potentialArgs->phiforce= &ZeroForce; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 21: //TriaxialHernquistPotential, lots of arguments potentialArgs->potentialEval= &EllipsoidalPotentialEval; potentialArgs->Rforce = &EllipsoidalPotentialRforce; potentialArgs->zforce = &EllipsoidalPotentialzforce; potentialArgs->phiforce = &EllipsoidalPotentialphiforce; potentialArgs->dens= &EllipsoidalPotentialDens; // Also assign functions specific to EllipsoidalPotential potentialArgs->psi= &TriaxialHernquistPotentialpsi; potentialArgs->mdens= &TriaxialHernquistPotentialmdens; potentialArgs->mdensDeriv= &TriaxialHernquistPotentialmdensDeriv; potentialArgs->nargs = (int) (21 + *(*pot_args+7) + 2 * *(*pot_args + (int) (*(*pot_args+7) + 20))); potentialArgs->requiresVelocity= false; break; case 22: //TriaxialNFWPotential, lots of arguments potentialArgs->potentialEval= &EllipsoidalPotentialEval; potentialArgs->Rforce = &EllipsoidalPotentialRforce; potentialArgs->zforce = &EllipsoidalPotentialzforce; potentialArgs->phiforce = &EllipsoidalPotentialphiforce; potentialArgs->dens= &EllipsoidalPotentialDens; // Also assign functions specific to EllipsoidalPotential potentialArgs->psi= &TriaxialNFWPotentialpsi; potentialArgs->mdens= &TriaxialNFWPotentialmdens; potentialArgs->mdensDeriv= &TriaxialNFWPotentialmdensDeriv; potentialArgs->nargs = (int) (21 + *(*pot_args+7) + 2 * *(*pot_args + (int) (*(*pot_args+7) + 20))); potentialArgs->requiresVelocity= false; break; case 23: //TriaxialJaffePotential, lots of arguments potentialArgs->potentialEval= &EllipsoidalPotentialEval; potentialArgs->Rforce = &EllipsoidalPotentialRforce; potentialArgs->zforce = &EllipsoidalPotentialzforce; potentialArgs->phiforce = &EllipsoidalPotentialphiforce; potentialArgs->dens= &EllipsoidalPotentialDens; // Also assign functions specific to EllipsoidalPotential potentialArgs->psi= &TriaxialJaffePotentialpsi; potentialArgs->mdens= &TriaxialJaffePotentialmdens; potentialArgs->mdensDeriv= &TriaxialJaffePotentialmdensDeriv; potentialArgs->nargs = (int) (21 + *(*pot_args+7) + 2 * *(*pot_args + (int) (*(*pot_args+7) + 20))); potentialArgs->requiresVelocity= false; break; case 24: //SCFPotential, many arguments potentialArgs->potentialEval= &SCFPotentialEval; potentialArgs->Rforce= &SCFPotentialRforce; potentialArgs->zforce= &SCFPotentialzforce; potentialArgs->phiforce= &SCFPotentialphiforce; potentialArgs->dens= &SCFPotentialDens; potentialArgs->nargs= (int) (5 + (1 + *(*pot_args + 1)) * *(*pot_args+2) * *(*pot_args+3)* *(*pot_args+4) + 7); potentialArgs->requiresVelocity= false; break; case 25: //SoftenedNeedleBarPotential, 13 arguments potentialArgs->potentialEval= &SoftenedNeedleBarPotentialEval; potentialArgs->Rforce= &SoftenedNeedleBarPotentialRforce; potentialArgs->zforce= &SoftenedNeedleBarPotentialzforce; potentialArgs->phiforce= &SoftenedNeedleBarPotentialphiforce; potentialArgs->nargs= (int) 13; potentialArgs->requiresVelocity= false; break; case 26: //DiskSCFPotential, nsigma+3 arguments potentialArgs->potentialEval= &DiskSCFPotentialEval; potentialArgs->Rforce= &DiskSCFPotentialRforce; potentialArgs->zforce= &DiskSCFPotentialzforce; potentialArgs->dens= &DiskSCFPotentialDens; potentialArgs->phiforce= &ZeroForce; potentialArgs->nargs= (int) **pot_args + 3; potentialArgs->requiresVelocity= false; break; case 27: // SpiralArmsPotential, 10 arguments + array of Cs potentialArgs->Rforce = &SpiralArmsPotentialRforce; potentialArgs->zforce = &SpiralArmsPotentialzforce; potentialArgs->phiforce = &SpiralArmsPotentialphiforce; //potentialArgs->R2deriv = &SpiralArmsPotentialR2deriv; //potentialArgs->z2deriv = &SpiralArmsPotentialz2deriv; potentialArgs->phi2deriv = &SpiralArmsPotentialphi2deriv; //potentialArgs->Rzderiv = &SpiralArmsPotentialRzderiv; potentialArgs->Rphideriv = &SpiralArmsPotentialRphideriv; potentialArgs->nargs = (int) 10 + **pot_args; potentialArgs->requiresVelocity= false; break; case 30: // PerfectEllipsoidPotential, lots of arguments potentialArgs->potentialEval= &EllipsoidalPotentialEval; potentialArgs->Rforce = &EllipsoidalPotentialRforce; potentialArgs->zforce = &EllipsoidalPotentialzforce; potentialArgs->phiforce = &EllipsoidalPotentialphiforce; potentialArgs->dens= &EllipsoidalPotentialDens; //potentialArgs->R2deriv = &EllipsoidalPotentialR2deriv; //potentialArgs->z2deriv = &EllipsoidalPotentialz2deriv; //potentialArgs->phi2deriv = &EllipsoidalPotentialphi2deriv; //potentialArgs->Rzderiv = &EllipsoidalPotentialRzderiv; //potentialArgs->Rphideriv = &EllipsoidalPotentialRphideriv; // Also assign functions specific to EllipsoidalPotential potentialArgs->psi= &PerfectEllipsoidPotentialpsi; potentialArgs->mdens= &PerfectEllipsoidPotentialmdens; potentialArgs->mdensDeriv= &PerfectEllipsoidPotentialmdensDeriv; potentialArgs->nargs = (int) (21 + *(*pot_args+7) + 2 * *(*pot_args + (int) (*(*pot_args+7) + 20))); potentialArgs->requiresVelocity= false; break; // 31: KGPotential // 32: IsothermalDiskPotential case 33: //DehnenCoreSphericalPotential, 2 arguments potentialArgs->potentialEval= &DehnenCoreSphericalPotentialEval; potentialArgs->Rforce= &DehnenCoreSphericalPotentialRforce; potentialArgs->zforce= &DehnenCoreSphericalPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &DehnenCoreSphericalPotentialDens; //potentialArgs->R2deriv= &DehnenCoreSphericalPotentialR2deriv; //potentialArgs->planarphi2deriv= &ZeroForce; //potentialArgs->planarRphideriv= &ZeroForce; potentialArgs->nargs= 2; potentialArgs->requiresVelocity= false; break; case 34: //DehnenSphericalPotential, 3 arguments potentialArgs->potentialEval= &DehnenSphericalPotentialEval; potentialArgs->Rforce= &DehnenSphericalPotentialRforce; potentialArgs->zforce= &DehnenSphericalPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &DehnenSphericalPotentialDens; //potentialArgs->R2deriv= &DehnenSphericalPotentialR2deriv; //potentialArgs->planarphi2deriv= &ZeroForce; //potentialArgs->planarRphideriv= &ZeroForce; potentialArgs->nargs= 3; potentialArgs->requiresVelocity= false; break; case 35: //HomogeneousSpherePotential, 3 arguments potentialArgs->potentialEval= &HomogeneousSpherePotentialEval; potentialArgs->Rforce= &HomogeneousSpherePotentialRforce; potentialArgs->zforce= &HomogeneousSpherePotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &HomogeneousSpherePotentialDens; potentialArgs->nargs= 3; potentialArgs->requiresVelocity= false; break; case 36: //interpSphericalPotential, XX arguments // Set up 1 spline in potentialArgs potentialArgs->nspline1d= 1; potentialArgs->spline1d= (gsl_spline **) \ malloc ( potentialArgs->nspline1d*sizeof ( gsl_spline *) ); potentialArgs->acc1d= (gsl_interp_accel **) \ malloc ( potentialArgs->nspline1d * sizeof ( gsl_interp_accel * ) ); // allocate accelerator *potentialArgs->acc1d= gsl_interp_accel_alloc(); // Set up interpolater nr= (int) **pot_args; *potentialArgs->spline1d= gsl_spline_alloc(gsl_interp_cspline,nr); gsl_spline_init(*potentialArgs->spline1d,*pot_args+1,*pot_args+1+nr,nr); *pot_args+= 2*nr+1; // Bind forces potentialArgs->potentialEval= &SphericalPotentialEval; potentialArgs->Rforce = &SphericalPotentialRforce; potentialArgs->zforce = &SphericalPotentialzforce; potentialArgs->phiforce= &ZeroForce; potentialArgs->dens= &SphericalPotentialDens; // Also assign functions specific to SphericalPotential potentialArgs->revaluate= &interpSphericalPotentialrevaluate; potentialArgs->rforce= &interpSphericalPotentialrforce; potentialArgs->r2deriv= &interpSphericalPotentialr2deriv; potentialArgs->rdens= &interpSphericalPotentialrdens; potentialArgs->nargs = (int) 6; potentialArgs->requiresVelocity= false; break; case 37: // TriaxialGaussianPotential, lots of arguments potentialArgs->potentialEval= &EllipsoidalPotentialEval; potentialArgs->Rforce = &EllipsoidalPotentialRforce; potentialArgs->zforce = &EllipsoidalPotentialzforce; potentialArgs->phiforce = &EllipsoidalPotentialphiforce; potentialArgs->dens= &EllipsoidalPotentialDens; //potentialArgs->R2deriv = &EllipsoidalPotentialR2deriv; //potentialArgs->z2deriv = &EllipsoidalPotentialz2deriv; //potentialArgs->phi2deriv = &EllipsoidalPotentialphi2deriv; //potentialArgs->Rzderiv = &EllipsoidalPotentialRzderiv; //potentialArgs->Rphideriv = &EllipsoidalPotentialRphideriv; // Also assign functions specific to EllipsoidalPotential potentialArgs->psi= &TriaxialGaussianPotentialpsi; potentialArgs->mdens= &TriaxialGaussianPotentialmdens; potentialArgs->mdensDeriv= &TriaxialGaussianPotentialmdensDeriv; potentialArgs->nargs = (int) (21 + *(*pot_args+7) + 2 * *(*pot_args + (int) (*(*pot_args+7) + 20))); potentialArgs->requiresVelocity= false; break; case 38: // PowerTriaxialPotential, lots of arguments potentialArgs->potentialEval= &EllipsoidalPotentialEval; potentialArgs->Rforce = &EllipsoidalPotentialRforce; potentialArgs->zforce = &EllipsoidalPotentialzforce; potentialArgs->phiforce = &EllipsoidalPotentialphiforce; potentialArgs->dens= &EllipsoidalPotentialDens; //potentialArgs->R2deriv = &EllipsoidalPotentialR2deriv; //potentialArgs->z2deriv = &EllipsoidalPotentialz2deriv; //potentialArgs->phi2deriv = &EllipsoidalPotentialphi2deriv; //potentialArgs->Rzderiv = &EllipsoidalPotentialRzderiv; //potentialArgs->Rphideriv = &EllipsoidalPotentialRphideriv; // Also assign functions specific to EllipsoidalPotential potentialArgs->psi= &PowerTriaxialPotentialpsi; potentialArgs->mdens= &PowerTriaxialPotentialmdens; potentialArgs->mdensDeriv= &PowerTriaxialPotentialmdensDeriv; potentialArgs->nargs = (int) (21 + *(*pot_args+7) + 2 * *(*pot_args + (int) (*(*pot_args+7) + 20))); potentialArgs->requiresVelocity= false; break; //////////////////////////////// WRAPPERS ///////////////////////////////////// case -1: //DehnenSmoothWrapperPotential potentialArgs->potentialEval= &DehnenSmoothWrapperPotentialEval; potentialArgs->Rforce= &DehnenSmoothWrapperPotentialRforce; potentialArgs->zforce= &DehnenSmoothWrapperPotentialzforce; potentialArgs->phiforce= &DehnenSmoothWrapperPotentialphiforce; potentialArgs->nargs= (int) 4; potentialArgs->requiresVelocity= false; break; case -2: //SolidBodyRotationWrapperPotential potentialArgs->Rforce= &SolidBodyRotationWrapperPotentialRforce; potentialArgs->zforce= &SolidBodyRotationWrapperPotentialzforce; potentialArgs->phiforce= &SolidBodyRotationWrapperPotentialphiforce; potentialArgs->nargs= (int) 3; potentialArgs->requiresVelocity= false; break; case -4: //CorotatingRotationWrapperPotential potentialArgs->Rforce= &CorotatingRotationWrapperPotentialRforce; potentialArgs->zforce= &CorotatingRotationWrapperPotentialzforce; potentialArgs->phiforce= &CorotatingRotationWrapperPotentialphiforce; potentialArgs->nargs= (int) 5; potentialArgs->requiresVelocity= false; break; case -5: //GaussianAmplitudeWrapperPotential potentialArgs->potentialEval= &GaussianAmplitudeWrapperPotentialEval; potentialArgs->Rforce= &GaussianAmplitudeWrapperPotentialRforce; potentialArgs->zforce= &GaussianAmplitudeWrapperPotentialzforce; potentialArgs->phiforce= &GaussianAmplitudeWrapperPotentialphiforce; potentialArgs->nargs= (int) 3; potentialArgs->requiresVelocity= false; break; case -6: //MovingObjectPotential potentialArgs->Rforce= &MovingObjectPotentialRforce; potentialArgs->zforce= &MovingObjectPotentialzforce; potentialArgs->phiforce= &MovingObjectPotentialphiforce; potentialArgs->nargs= (int) 3; potentialArgs->requiresVelocity= false; break; case -7: //ChandrasekharDynamicalFrictionForce potentialArgs->RforceVelocity= &ChandrasekharDynamicalFrictionForceRforce; potentialArgs->zforceVelocity= &ChandrasekharDynamicalFrictionForcezforce; potentialArgs->phiforceVelocity= &ChandrasekharDynamicalFrictionForcephiforce; potentialArgs->nargs= (int) 16; potentialArgs->requiresVelocity= true; break; case -8: //RotateAndTiltWrapperPotential potentialArgs->Rforce= &RotateAndTiltWrapperPotentialRforce; potentialArgs->zforce= &RotateAndTiltWrapperPotentialzforce; potentialArgs->phiforce= &RotateAndTiltWrapperPotentialphiforce; potentialArgs->nargs= (int) 16; potentialArgs->requiresVelocity= false; break; } int setupMovingObjectSplines = *(*pot_type-1) == -6 ? 1 : 0; int setupChandrasekharDynamicalFrictionSplines = *(*pot_type-1) == -7 ? 1 : 0; if ( *(*pot_type-1) < 0 ) { // Parse wrapped potential for wrappers potentialArgs->nwrapped= (int) *(*pot_args)++; potentialArgs->wrappedPotentialArg= \ (struct potentialArg *) malloc ( potentialArgs->nwrapped \ * sizeof (struct potentialArg) ); parse_leapFuncArgs_Full(potentialArgs->nwrapped, potentialArgs->wrappedPotentialArg, pot_type,pot_args); } if (setupMovingObjectSplines) initMovingObjectSplines(potentialArgs, pot_args); if (setupChandrasekharDynamicalFrictionSplines) initChandrasekharDynamicalFrictionSplines(potentialArgs,pot_args); potentialArgs->args= (double *) malloc( potentialArgs->nargs * sizeof(double)); for (jj=0; jj < potentialArgs->nargs; jj++){ *(potentialArgs->args)= *(*pot_args)++; potentialArgs->args++; } potentialArgs->args-= potentialArgs->nargs; potentialArgs++; } potentialArgs-= npot; } EXPORT void integrateFullOrbit(int nobj, double *yo, int nt, double *t, int npot, int * pot_type, double * pot_args, double dt, double rtol, double atol, double *result, int * err, int odeint_type){ //Set up the forces, first count int ii,jj; int dim; int max_threads; int * thread_pot_type; double * thread_pot_args; max_threads= ( nobj < omp_get_max_threads() ) ? nobj : omp_get_max_threads(); // Because potentialArgs may cache, safest to have one / thread struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( max_threads * npot * sizeof (struct potentialArg) ); #pragma omp parallel for schedule(static,1) private(ii,thread_pot_type,thread_pot_args) num_threads(max_threads) for (ii=0; ii < max_threads; ii++) { thread_pot_type= pot_type; // need to make thread-private pointers, bc thread_pot_args= pot_args; // these pointers are changed in parse_... parse_leapFuncArgs_Full(npot,potentialArgs+ii*npot, &thread_pot_type,&thread_pot_args); } //Integrate void (*odeint_func)(void (*func)(double, double *, double *, int, struct potentialArg *), int, double *, int, double, double *, int, struct potentialArg *, double, double, double *,int *); void (*odeint_deriv_func)(double, double *, double *, int,struct potentialArg *); switch ( odeint_type ) { case 0: //leapfrog odeint_func= &leapfrog; odeint_deriv_func= &evalRectForce; dim= 3; break; case 1: //RK4 odeint_func= &bovy_rk4; odeint_deriv_func= &evalRectDeriv; dim= 6; break; case 2: //RK6 odeint_func= &bovy_rk6; odeint_deriv_func= &evalRectDeriv; dim= 6; break; case 3: //symplec4 odeint_func= &symplec4; odeint_deriv_func= &evalRectForce; dim= 3; break; case 4: //symplec6 odeint_func= &symplec6; odeint_deriv_func= &evalRectForce; dim= 3; break; case 5: //DOPR54 odeint_func= &bovy_dopr54; odeint_deriv_func= &evalRectDeriv; dim= 6; break; case 6: //DOP853 odeint_func= &dop853; odeint_deriv_func= &evalRectDeriv; dim= 6; break; } #pragma omp parallel for schedule(dynamic,ORBITS_CHUNKSIZE) private(ii,jj) num_threads(max_threads) for (ii=0; ii < nobj; ii++) { cyl_to_rect_galpy(yo+6*ii); odeint_func(odeint_deriv_func,dim,yo+6*ii,nt,dt,t, npot,potentialArgs+omp_get_thread_num()*npot,rtol,atol, result+6*nt*ii,err+ii); for (jj=0; jj < nt; jj++) rect_to_cyl_galpy(result+6*jj+6*nt*ii); } //Free allocated memory #pragma omp parallel for schedule(static,1) private(ii) num_threads(max_threads) for (ii=0; ii < max_threads; ii++) free_potentialArgs(npot,potentialArgs+ii*npot); free(potentialArgs); //Done! } // LCOV_EXCL_START void integrateOrbit_dxdv(double *yo, int nt, double *t, int npot, int * pot_type, double * pot_args, double rtol, double atol, double *result, int * err, int odeint_type){ //Set up the forces, first count int dim; struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) ); parse_leapFuncArgs_Full(npot,potentialArgs,&pot_type,&pot_args); //Integrate void (*odeint_func)(void (*func)(double, double *, double *, int, struct potentialArg *), int, double *, int, double, double *, int, struct potentialArg *, double, double, double *,int *); void (*odeint_deriv_func)(double, double *, double *, int,struct potentialArg *); switch ( odeint_type ) { case 0: //leapfrog odeint_func= &leapfrog; odeint_deriv_func= &evalRectForce; dim= 6; break; case 1: //RK4 odeint_func= &bovy_rk4; odeint_deriv_func= &evalRectDeriv_dxdv; dim= 12; break; case 2: //RK6 odeint_func= &bovy_rk6; odeint_deriv_func= &evalRectDeriv_dxdv; dim= 12; break; case 3: //symplec4 odeint_func= &symplec4; odeint_deriv_func= &evalRectForce; dim= 6; break; case 4: //symplec6 odeint_func= &symplec6; odeint_deriv_func= &evalRectForce; dim= 6; break; case 5: //DOPR54 odeint_func= &bovy_dopr54; odeint_deriv_func= &evalRectDeriv_dxdv; dim= 12; break; case 6: //DOP853 odeint_func= &dop853; odeint_deriv_func= &evalRectDeriv_dxdv; dim= 12; break; } odeint_func(odeint_deriv_func,dim,yo,nt,-9999.99,t,npot,potentialArgs, rtol,atol,result,err); //Free allocated memory free_potentialArgs(npot,potentialArgs); free(potentialArgs); //Done! } // LCOV_EXCL_STOP void evalRectForce(double t, double *q, double *a, int nargs, struct potentialArg * potentialArgs){ double sinphi, cosphi, x, y, phi,R,Rforce,phiforce, z, zforce; //q is rectangular so calculate R and phi x= *q; y= *(q+1); z= *(q+2); R= sqrt(x*x+y*y); phi= acos(x/R); sinphi= y/R; cosphi= x/R; if ( y < 0. ) phi= 2.*M_PI-phi; //Calculate the forces Rforce= calcRforce(R,z,phi,t,nargs,potentialArgs); zforce= calczforce(R,z,phi,t,nargs,potentialArgs); phiforce= calcPhiforce(R,z,phi,t,nargs,potentialArgs); *a++= cosphi*Rforce-1./R*sinphi*phiforce; *a++= sinphi*Rforce+1./R*cosphi*phiforce; *a= zforce; } void evalRectDeriv(double t, double *q, double *a, int nargs, struct potentialArg * potentialArgs){ double sinphi, cosphi, x, y, phi,R,Rforce,phiforce,z,zforce,vR,vT; //first three derivatives are just the velocities *a++= *(q+3); *a++= *(q+4); *a++= *(q+5); //Rest is force //q is rectangular so calculate R and phi, vR and vT (for dissipative) x= *q; y= *(q+1); z= *(q+2); R= sqrt(x*x+y*y); phi= acos(x/R); sinphi= y/R; cosphi= x/R; if ( y < 0. ) phi= 2.*M_PI-phi; vR= *(q+3) * cosphi + *(q+4) * sinphi; vT= -*(q+3) * sinphi + *(q+4) * cosphi; //Calculate the forces Rforce= calcRforce(R,z,phi,t,nargs,potentialArgs,vR,vT,*(q+5)); zforce= calczforce(R,z,phi,t,nargs,potentialArgs,vR,vT,*(q+5)); phiforce= calcPhiforce(R,z,phi,t,nargs,potentialArgs,vR,vT,*(q+5)); *a++= cosphi*Rforce-1./R*sinphi*phiforce; *a++= sinphi*Rforce+1./R*cosphi*phiforce; *a= zforce; } void initMovingObjectSplines(struct potentialArg * potentialArgs, double ** pot_args){ gsl_interp_accel *x_accel_ptr = gsl_interp_accel_alloc(); gsl_interp_accel *y_accel_ptr = gsl_interp_accel_alloc(); gsl_interp_accel *z_accel_ptr = gsl_interp_accel_alloc(); int nPts = (int) **pot_args; gsl_spline *x_spline = gsl_spline_alloc(gsl_interp_cspline, nPts); gsl_spline *y_spline = gsl_spline_alloc(gsl_interp_cspline, nPts); gsl_spline *z_spline = gsl_spline_alloc(gsl_interp_cspline, nPts); double * t_arr = *pot_args+1; double * x_arr = t_arr+1*nPts; double * y_arr = t_arr+2*nPts; double * z_arr = t_arr+3*nPts; double * t= (double *) malloc ( nPts * sizeof (double) ); double tf = *(t_arr+4*nPts+2); double to = *(t_arr+4*nPts+1); int ii; for (ii=0; ii < nPts; ii++) *(t+ii) = (t_arr[ii]-to)/(tf-to); gsl_spline_init(x_spline, t, x_arr, nPts); gsl_spline_init(y_spline, t, y_arr, nPts); gsl_spline_init(z_spline, t, z_arr, nPts); potentialArgs->nspline1d= 3; potentialArgs->spline1d= (gsl_spline **) malloc ( 3*sizeof ( gsl_spline *) ); potentialArgs->acc1d= (gsl_interp_accel **) \ malloc ( 3 * sizeof ( gsl_interp_accel * ) ); *potentialArgs->spline1d = x_spline; *potentialArgs->acc1d = x_accel_ptr; *(potentialArgs->spline1d+1)= y_spline; *(potentialArgs->acc1d+1)= y_accel_ptr; *(potentialArgs->spline1d+2)= z_spline; *(potentialArgs->acc1d+2)= z_accel_ptr; *pot_args = *pot_args + (int) (1+4*nPts); free(t); } void initChandrasekharDynamicalFrictionSplines(struct potentialArg * potentialArgs, double ** pot_args){ gsl_interp_accel *sr_accel_ptr = gsl_interp_accel_alloc(); int nPts = (int) **pot_args; gsl_spline *sr_spline = gsl_spline_alloc(gsl_interp_cspline,nPts); double * r_arr = *pot_args+1; double * sr_arr = r_arr+1*nPts; double * r= (double *) malloc ( nPts * sizeof (double) ); double ro = *(r_arr+2*nPts+14); double rf = *(r_arr+2*nPts+15); int ii; for (ii=0; ii < nPts; ii++) *(r+ii) = (r_arr[ii]-ro)/(rf-ro); gsl_spline_init(sr_spline,r,sr_arr,nPts); potentialArgs->nspline1d= 1; potentialArgs->spline1d= (gsl_spline **) \ malloc ( potentialArgs->nspline1d*sizeof ( gsl_spline *) ); potentialArgs->acc1d= (gsl_interp_accel **) \ malloc ( potentialArgs->nspline1d * sizeof ( gsl_interp_accel * ) ); *potentialArgs->spline1d = sr_spline; *potentialArgs->acc1d = sr_accel_ptr; *pot_args = *pot_args + (int) (1+(1+potentialArgs->nspline1d)*nPts); free(r); } // LCOV_EXCL_START void evalRectDeriv_dxdv(double t, double *q, double *a, int nargs, struct potentialArg * potentialArgs){ double sinphi, cosphi, x, y, phi,R,Rforce,phiforce,z,zforce; double R2deriv, phi2deriv, Rphideriv, dFxdx, dFxdy, dFydx, dFydy; //first three derivatives are just the velocities *a++= *(q+3); *a++= *(q+4); *a++= *(q+5); //Rest is force //q is rectangular so calculate R and phi x= *q; y= *(q+1); z= *(q+2); R= sqrt(x*x+y*y); phi= acos(x/R); sinphi= y/R; cosphi= x/R; if ( y < 0. ) phi= 2.*M_PI-phi; //Calculate the forces Rforce= calcRforce(R,z,phi,t,nargs,potentialArgs); zforce= calczforce(R,z,phi,t,nargs,potentialArgs); phiforce= calcPhiforce(R,z,phi,t,nargs,potentialArgs); *a++= cosphi*Rforce-1./R*sinphi*phiforce; *a++= sinphi*Rforce+1./R*cosphi*phiforce; *a++= zforce; //dx derivatives are just dv *a++= *(q+9); *a++= *(q+10); *a++= *(q+11); //for the dv derivatives we need also R2deriv, phi2deriv, and Rphideriv R2deriv= calcR2deriv(R,z,phi,t,nargs,potentialArgs); phi2deriv= calcphi2deriv(R,z,phi,t,nargs,potentialArgs); Rphideriv= calcRphideriv(R,z,phi,t,nargs,potentialArgs); //..and dFxdx, dFxdy, dFydx, dFydy dFxdx= -cosphi*cosphi*R2deriv +2.*cosphi*sinphi/R/R*phiforce +sinphi*sinphi/R*Rforce +2.*sinphi*cosphi/R*Rphideriv -sinphi*sinphi/R/R*phi2deriv; dFxdy= -sinphi*cosphi*R2deriv +(sinphi*sinphi-cosphi*cosphi)/R/R*phiforce -cosphi*sinphi/R*Rforce -(cosphi*cosphi-sinphi*sinphi)/R*Rphideriv +cosphi*sinphi/R/R*phi2deriv; dFydx= -cosphi*sinphi*R2deriv +(sinphi*sinphi-cosphi*cosphi)/R/R*phiforce +(sinphi*sinphi-cosphi*cosphi)/R*Rphideriv -sinphi*cosphi/R*Rforce +sinphi*cosphi/R/R*phi2deriv; dFydy= -sinphi*sinphi*R2deriv -2.*sinphi*cosphi/R/R*phiforce -2.*sinphi*cosphi/R*Rphideriv +cosphi*cosphi/R*Rforce -cosphi*cosphi/R/R*phi2deriv; *a++= dFxdx * *(q+4) + dFxdy * *(q+5); *a++= dFydx * *(q+4) + dFydy * *(q+5); *a= 0; //BOVY: PUT IN Z2DERIVS } // LCOV_EXCL_STOP
add.c
#include "main.h" mat_rv addition_coo_nothreading(coo matrix1, coo matrix2) { mat_rv rv; if(matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols){ rv.error = ERR_WRONG_DIM; return rv; } if(matrix1.elems[0].type != matrix2.elems[0].type){ rv.error = ERR_TYPE_MISSMATCH; return rv; } struct timespec start, end; get_utc_time(&start); coo result; result.rows = matrix1.rows; result.cols = matrix1.cols; result.type = matrix1.type; result.length = 0; int size = MALLOCINIT; if(!(result.elems = (coo_elem*)malloc(size*sizeof(coo_elem)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } int matrix1_i = 0; int matrix2_i = 0; while(matrix1_i < matrix1.length && matrix2_i < matrix2.length){ coo_elem next; next.type = matrix1.elems[0].type; if(matrix1.elems[matrix1_i].i == matrix2.elems[matrix2_i].i){ if(matrix1.elems[matrix1_i].j == matrix2.elems[matrix2_i].j){ if(next.type == MAT_INT) next.val.i = matrix1.elems[matrix1_i].val.i + matrix2.elems[matrix2_i].val.i; else next.val.f = matrix1.elems[matrix1_i].val.f + matrix2.elems[matrix2_i].val.f; next.i = matrix1.elems[matrix1_i].i; next.j = matrix1.elems[matrix1_i].j; ++matrix1_i; ++matrix2_i; } else if(matrix1.elems[matrix1_i].j > matrix2.elems[matrix2_i].j) next = matrix2.elems[matrix2_i++]; else next = matrix1.elems[matrix1_i++]; } else if(matrix1.elems[matrix1_i].i > matrix2.elems[matrix2_i].i) next = matrix2.elems[matrix2_i++]; else next = matrix1.elems[matrix1_i++]; if(size == result.length){ size *= 2; if(!(result.elems = realloc(result.elems, size*sizeof(coo_elem)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } result.elems[result.length++] = next; } while(matrix1_i < matrix1.length){ if(size == result.length){ size *= 2; if(!(result.elems = realloc(result.elems, size*sizeof(coo_elem)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } result.elems[result.length++] = matrix1.elems[matrix1_i++]; } while(matrix2_i < matrix2.length){ if(size == result.length){ size *= 2; if(!(result.elems = realloc(result.elems, size*sizeof(coo_elem)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } result.elems[result.length++] = matrix2.elems[matrix2_i++]; } get_utc_time(&end); rv = coo_to_mat_nothreading(result); rv.t_process = time_delta(end, start); free_coo(result); return rv; } mat_rv addition_coo(coo matrix1, coo matrix2, int thread_count) { mat_rv rv; if(matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols){ rv.error = ERR_WRONG_DIM; return rv; } if(matrix1.elems[0].type != matrix2.elems[0].type){ rv.error = ERR_TYPE_MISSMATCH; return rv; } struct timespec start, end; get_utc_time(&start); coo result; result.rows = matrix1.rows; result.cols = matrix1.cols; result.type = matrix1.type; result.length = 0; //local storage elems coo_elem **local_elems; int *local_elems_len; if(!(local_elems = (coo_elem**)malloc(matrix1.rows * sizeof(coo_elem *)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } if(!(local_elems_len = (int*)calloc(matrix1.rows, sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } //allocate for worst case such that additional calls to change allocation is not needed //by each thread for(int i = 0; i < matrix1.rows; ++i){ if(!(local_elems[i] = (coo_elem*)malloc(matrix1.cols * sizeof(coo_elem)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } //row1 corresponds to matrix1 //row2 corresponds to matrix2 int *row1_entries; int *row1_lens; int *row2_entries; int *row2_lens; if(!(row1_entries = (int*)malloc(matrix1.rows * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } if(!(row1_lens = (int*)calloc(matrix1.rows, sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } if(!(row2_entries = (int*)malloc(matrix2.rows * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } if(!(row2_lens = (int*)calloc(matrix2.rows, sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } for(int i = 0; i < matrix1.rows; ++i){ row1_entries[i] = -1; row2_entries[i] = -1; } //Time constants for building makes threading redundant for(int i = 0; i < matrix1.length; ++i){ if(row1_entries[matrix1.elems[i].i] == -1) row1_entries[matrix1.elems[i].i] = i; row1_lens[matrix1.elems[i].i]++; } for(int i = 0; i < matrix2.length; ++i){ if(row2_entries[matrix2.elems[i].i] == -1) row2_entries[matrix2.elems[i].i] = i; row2_lens[matrix2.elems[i].i]++; } int i; #pragma omp parallel for num_threads(thread_count) private(i) shared(matrix1, matrix2, local_elems) for(i = 0; i < matrix1.rows; ++i){ if(row1_lens[i] == 0 && row2_lens[i] == 0) continue; int row1_i = 0, row2_i = 0; while(row1_i < row1_lens[i] && row2_i < row2_lens[i]){ if(matrix1.elems[row1_entries[i] + row1_i].j == matrix2.elems[row2_entries[i] + row2_i].j){ if(result.type == MAT_INT) local_elems[i][local_elems_len[i]].val.i = matrix1.elems[row1_entries[i] + row1_i].val.i + matrix2.elems[row2_entries[i] + row2_i].val.i; else local_elems[i][local_elems_len[i]].val.f = matrix1.elems[row1_entries[i] + row1_i].val.f + matrix2.elems[row2_entries[i] + row2_i].val.f; local_elems[i][local_elems_len[i]].j = matrix1.elems[row1_entries[i] + row1_i].j; ++row2_i; ++row1_i; } else if(matrix1.elems[row1_entries[i] + row1_i].j > matrix2.elems[row2_entries[i] + row2_i].j){ if(result.type == MAT_INT) local_elems[i][local_elems_len[i]].val.i = matrix2.elems[row2_entries[i] + row2_i].val.i; else local_elems[i][local_elems_len[i]].val.f = matrix2.elems[row2_entries[i] + row2_i].val.f; local_elems[i][local_elems_len[i]].j = matrix2.elems[row2_entries[i] + row2_i].j; ++row2_i; } else{ if(result.type == MAT_INT) local_elems[i][local_elems_len[i]].val.i = matrix1.elems[row1_entries[i] + row1_i].val.i; else local_elems[i][local_elems_len[i]].val.f = matrix1.elems[row1_entries[i] + row1_i].val.f; local_elems[i][local_elems_len[i]].j = matrix1.elems[row1_entries[i] + row1_i].j; ++row1_i; } local_elems[i][local_elems_len[i]].i = i; local_elems[i][local_elems_len[i]].type = result.type; ++local_elems_len[i]; } while(row1_i < row1_lens[i]){ if(result.type == MAT_INT) local_elems[i][local_elems_len[i]].val.i = matrix1.elems[row1_entries[i] + row1_i].val.i; else local_elems[i][local_elems_len[i]].val.f = matrix1.elems[row1_entries[i] + row1_i].val.f; local_elems[i][local_elems_len[i]].j = matrix1.elems[row1_entries[i] + row1_i].j; local_elems[i][local_elems_len[i]].i = i; local_elems[i][local_elems_len[i]].type = result.type; ++local_elems_len[i]; ++row1_i; } while(row2_i < row2_lens[i]){ if(result.type == MAT_INT) local_elems[i][local_elems_len[i]].val.i = matrix2.elems[row2_entries[i] + row2_i].val.i; else local_elems[i][local_elems_len[i]].val.f = matrix2.elems[row2_entries[i] + row2_i].val.f; local_elems[i][local_elems_len[i]].j = matrix2.elems[row2_entries[i] + row2_i].j; local_elems[i][local_elems_len[i]].i = i; local_elems[i][local_elems_len[i]].type = result.type; ++local_elems_len[i]; ++row2_i; } } free(row1_entries); free(row1_lens); free(row2_entries); free(row2_lens); for(i = 0; i < result.rows; ++i) result.length += local_elems_len[i]; if(!(result.elems = malloc(result.length * sizeof(coo_elem)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } int index = 0; for(i = 0; i < result.rows; ++i){ memcpy(&result.elems[index], local_elems[i], local_elems_len[i] * sizeof(coo_elem)); index += local_elems_len[i]; free(local_elems[i]); } free(local_elems); free(local_elems_len); get_utc_time(&end); rv = coo_to_mat(result, thread_count); rv.t_process = time_delta(end, start); free_coo(result); return rv; } mat_rv addition_csr_nothreading(csr matrix1, csr matrix2) { mat_rv rv; if(matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols){ rv.error = ERR_WRONG_DIM; return rv; } if(matrix1.type != matrix2.type){ rv.error = ERR_TYPE_MISSMATCH; return rv; } struct timespec start, end; get_utc_time(&start); csr result; result.rows = matrix1.rows; result.cols = matrix1.cols; result.type = matrix1.type; result.num_vals = 0; //check worst case between all rows * cols or all elems int nnz_size = matrix1.cols*matrix1.rows; if(matrix1.num_vals + matrix2.num_vals < nnz_size) nnz_size = matrix1.num_vals + matrix2.num_vals; if(result.type == MAT_INT){ if(!(result.nnz.i = (int*)malloc(nnz_size * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } else{ if(!(result.nnz.f = (long double*)malloc(nnz_size * sizeof(long double)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } if(!(result.ja = (int*)malloc(nnz_size * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } if(!(result.ia = (int*)malloc((result.rows + 1) * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } result.ia[0] = 0; for(int i = 0; i < result.rows; ++i){ result.ia[i + 1] = result.ia[i]; int mat1_i = matrix1.ia[i]; int mat2_i = matrix2.ia[i]; while(mat1_i < matrix1.ia[i + 1] && mat2_i < matrix2.ia[i + 1]){ if(matrix1.ja[mat1_i] == matrix2.ja[mat2_i]){ if(result.type == MAT_INT) result.nnz.i[result.ia[i + 1]] = matrix1.nnz.i[mat1_i] + matrix2.nnz.i[mat2_i]; else result.nnz.f[result.ia[i + 1]] = matrix1.nnz.f[mat1_i] + matrix2.nnz.f[mat2_i]; result.ja[result.ia[i + 1]] = matrix1.ja[mat1_i]; ++result.ia[i + 1]; ++mat1_i; ++mat2_i; } else if(matrix1.ja[mat1_i] > matrix2.ja[mat2_i]) ++mat2_i; else ++mat1_i; } while(mat1_i < matrix1.ia[i + 1]){ if(result.type == MAT_INT) result.nnz.i[result.ia[i + 1]] = matrix1.nnz.i[mat1_i]; else result.nnz.f[result.ia[i + 1]] = matrix1.nnz.f[mat1_i]; result.ja[result.ia[i + 1]] = matrix1.ja[mat1_i]; ++result.ia[i + 1]; ++mat1_i; } while(mat2_i < matrix2.ia[i + 1]){ if(result.type == MAT_INT) result.nnz.i[result.ia[i + 1]] = matrix2.nnz.i[mat2_i]; else result.nnz.f[result.ia[i + 1]] = matrix2.nnz.f[mat2_i]; result.ja[result.ia[i + 1]] = matrix2.ja[mat2_i]; ++result.ia[i + 1]; ++mat2_i; } } result.num_vals = result.ia[result.rows]; get_utc_time(&end); rv = csr_to_mat_nothreading(result); rv.t_process = time_delta(end, start); free_csr(result); return rv; } mat_rv addition_csr(csr matrix1, csr matrix2, int thread_count) { mat_rv rv; if(matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols){ rv.error = ERR_WRONG_DIM; return rv; } if(matrix1.type != matrix2.type){ rv.error = ERR_TYPE_MISSMATCH; return rv; } struct timespec start, end; get_utc_time(&start); csr result; result.rows = matrix1.rows; result.cols = matrix1.cols; result.type = matrix1.type; result.num_vals = 0; union{ int **i; long double **f; } local_nnzs; int **local_jas; //allocate for worst case if(result.type == MAT_INT){ if(!(local_nnzs.i = (int**)malloc(result.rows*sizeof(int *)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } for(int i = 0; i < result.rows; ++i){ if(!(local_nnzs.i[i] = (int*)malloc(result.cols*sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } } else{ if(!(local_nnzs.f = (long double**)malloc(result.rows*sizeof(long double *)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } for(int i = 0; i < result.rows; ++i){ if(!(local_nnzs.f[i] = (long double*)malloc(result.cols*sizeof(long double)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } } if(!(local_jas = (int**)malloc(result.rows*sizeof(int *)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } for(int i = 0; i < result.rows; ++i){ if(!(local_jas[i] = (int*)malloc(result.cols*sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } //using result.ia to store length of each row then iterate through at the end if(!(result.ia = (int*)calloc(result.rows + 1, sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } int i; #pragma omp parallel num_threads(thread_count) shared(matrix1, matrix2, result, local_nnzs, local_jas) { //store type on the local stack MAT_TYPE local_type = result.type; #pragma omp for private(i) for(i = 0; i < result.rows; ++i){ int mat1_i = matrix1.ia[i]; int mat2_i = matrix2.ia[i]; while(mat1_i < matrix1.ia[i + 1] && mat2_i < matrix2.ia[i + 1]){ if(matrix1.ja[mat1_i] == matrix2.ja[mat2_i]){ if(local_type == MAT_INT) local_nnzs.i[i][result.ia[i + 1]] = matrix1.nnz.i[mat1_i] + matrix2.nnz.i[mat2_i]; else local_nnzs.f[i][result.ia[i + 1]] = matrix1.nnz.f[mat1_i] + matrix2.nnz.f[mat2_i]; local_jas[i][result.ia[i + 1]] = matrix1.ja[mat1_i]; result.ia[i + 1]++; mat1_i++; mat2_i++; } else if(matrix1.ja[mat1_i] > matrix2.ja[mat2_i]) mat2_i++; else mat1_i++; } while(mat1_i < matrix1.ia[i + 1]){ if(local_type == MAT_INT) local_nnzs.i[i][result.ia[i + 1]] = matrix1.nnz.i[mat1_i]; else local_nnzs.f[i][result.ia[i + 1]] = matrix1.nnz.f[mat1_i]; local_jas[i][result.ia[i + 1]] = matrix1.ja[mat1_i]; ++result.ia[i + 1]; ++mat1_i; } while(mat2_i < matrix2.ia[i + 1]){ if(local_type == MAT_INT) local_nnzs.i[i][result.ia[i + 1]] = matrix2.nnz.i[mat2_i]; else local_nnzs.f[i][result.ia[i + 1]] = matrix2.nnz.f[mat2_i]; local_jas[i][result.ia[i + 1]] = matrix2.ja[mat2_i]; ++result.ia[i + 1]; ++mat2_i; } } } for(int i = 1; i < result.rows + 1; ++i) result.num_vals += result.ia[i]; if(result.type == MAT_INT){ if(!(result.nnz.i = (int*)malloc(result.num_vals * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } else{ if(!(result.nnz.f = (long double*)malloc(result.num_vals * sizeof(long double)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } if(!(result.ja = (int*)malloc(result.num_vals * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } for(int i = 0; i < result.rows; ++i){ if(result.ia[i + 1] > 0){ if(result.type == MAT_INT){ memcpy(&result.nnz.i[result.ia[i]],local_nnzs.i[i], result.ia[i + 1] * sizeof(int)); free(local_nnzs.i[i]); } else{ memcpy(&result.nnz.f[result.ia[i]],local_nnzs.f[i], result.ia[i + 1] * sizeof(long double)); free(local_nnzs.f[i]); } memcpy(&result.ja[result.ia[i]], local_jas[i], result.ia[i + 1] * sizeof(int)); free(local_jas[i]); } result.ia[i + 1] += result.ia[i]; } free(local_jas); if(result.type == MAT_INT) free(local_nnzs.i); else free(local_nnzs.f); get_utc_time(&end); rv = csr_to_mat(result, thread_count); rv.t_process = time_delta(end, start); free_csr(result); return rv; } mat_rv addition_csc_nothreading(csc matrix1, csc matrix2) { mat_rv rv; if(matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols){ rv.error = ERR_WRONG_DIM; return rv; } if(matrix1.type != matrix2.type){ rv.error = ERR_TYPE_MISSMATCH; return rv; } struct timespec start, end; get_utc_time(&start); csc result; result.cols = matrix1.cols; result.rows = matrix1.rows; result.type = matrix1.type; result.num_vals = 0; //check worst case between all cols * rows or all elems int nnz_size = matrix1.rows*matrix1.cols; if(matrix1.num_vals + matrix2.num_vals < nnz_size) nnz_size = matrix1.num_vals + matrix2.num_vals; if(result.type == MAT_INT){ if(!(result.nnz.i = (int*)malloc(nnz_size * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } else{ if(!(result.nnz.f = (long double*)malloc(nnz_size * sizeof(long double)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } if(!(result.ja = (int*)malloc(nnz_size * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } if(!(result.ia = (int*)malloc((result.cols + 1) * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } result.ia[0] = 0; for(int i = 0; i < result.cols; ++i){ result.ia[i + 1] = result.ia[i]; int mat1_i = matrix1.ia[i]; int mat2_i = matrix2.ia[i]; while(mat1_i < matrix1.ia[i + 1] && mat2_i < matrix2.ia[i + 1]){ if(matrix1.ja[mat1_i] == matrix2.ja[mat2_i]){ if(result.type == MAT_INT) result.nnz.i[result.ia[i + 1]] = matrix1.nnz.i[mat1_i] + matrix2.nnz.i[mat2_i]; else result.nnz.f[result.ia[i + 1]] = matrix1.nnz.f[mat1_i] + matrix2.nnz.f[mat2_i]; result.ja[result.ia[i + 1]] = matrix1.ja[mat1_i]; ++result.ia[i + 1]; ++mat1_i; ++mat2_i; } else if(matrix1.ja[mat1_i] > matrix2.ja[mat2_i]) ++mat2_i; else ++mat1_i; } while(mat1_i < matrix1.ia[i + 1]){ if(result.type == MAT_INT) result.nnz.i[result.ia[i + 1]] = matrix1.nnz.i[mat1_i]; else result.nnz.f[result.ia[i + 1]] = matrix1.nnz.f[mat1_i]; result.ja[result.ia[i + 1]] = matrix1.ja[mat1_i]; ++result.ia[i + 1]; ++mat1_i; } while(mat2_i < matrix2.ia[i + 1]){ if(result.type == MAT_INT) result.nnz.i[result.ia[i + 1]] = matrix2.nnz.i[mat2_i]; else result.nnz.f[result.ia[i + 1]] = matrix2.nnz.f[mat2_i]; result.ja[result.ia[i + 1]] = matrix2.ja[mat2_i]; ++result.ia[i + 1]; ++mat2_i; } } result.num_vals = result.ia[result.cols]; get_utc_time(&end); rv = csc_to_mat_nothreading(result); rv.t_process = time_delta(end, start); free_csc(result); return rv; } mat_rv addition_csc(csc matrix1, csc matrix2, int thread_count) { mat_rv rv; if(matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols){ rv.error = ERR_WRONG_DIM; return rv; } if(matrix1.type != matrix2.type){ rv.error = ERR_TYPE_MISSMATCH; return rv; } struct timespec start, end; get_utc_time(&start); csc result; result.cols = matrix1.cols; result.rows = matrix1.rows; result.type = matrix1.type; result.num_vals = 0; union{ int **i; long double **f; } local_nnzs; int **local_jas; //allocate for worst case if(result.type == MAT_INT){ if(!(local_nnzs.i = (int**)malloc(result.cols*sizeof(int *)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } for(int i = 0; i < result.cols; ++i){ if(!(local_nnzs.i[i] = (int*)malloc(result.rows*sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } } else{ if(!(local_nnzs.f = (long double**)malloc(result.cols*sizeof(long double *)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } for(int i = 0; i < result.cols; ++i){ if(!(local_nnzs.f[i] = (long double*)malloc(result.rows*sizeof(long double)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } } if(!(local_jas = (int**)malloc(result.cols*sizeof(int *)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } for(int i = 0; i < result.cols; ++i){ if(!(local_jas[i] = (int*)malloc(result.rows*sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } //using result.ia to store length of each row then iterate through at the end if(!(result.ia = (int*)calloc(result.cols + 1, sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } int i; #pragma omp parallel num_threads(thread_count) shared(matrix1, matrix2, result, local_nnzs, local_jas) { //store type on the local stack MAT_TYPE local_type = result.type; #pragma omp for private(i) for(i = 0; i < result.cols; ++i){ int mat1_i = matrix1.ia[i]; int mat2_i = matrix2.ia[i]; while(mat1_i < matrix1.ia[i + 1] && mat2_i < matrix2.ia[i + 1]){ if(matrix1.ja[mat1_i] == matrix2.ja[mat2_i]){ if(local_type == MAT_INT) local_nnzs.i[i][result.ia[i + 1]] = matrix1.nnz.i[mat1_i] + matrix2.nnz.i[mat2_i]; else local_nnzs.f[i][result.ia[i + 1]] = matrix1.nnz.f[mat1_i] + matrix2.nnz.f[mat2_i]; local_jas[i][result.ia[i + 1]] = matrix1.ja[mat1_i]; result.ia[i + 1]++; mat1_i++; mat2_i++; } else if(matrix1.ja[mat1_i] > matrix2.ja[mat2_i]) mat2_i++; else mat1_i++; } while(mat1_i < matrix1.ia[i + 1]){ if(local_type == MAT_INT) local_nnzs.i[i][result.ia[i + 1]] = matrix1.nnz.i[mat1_i]; else local_nnzs.f[i][result.ia[i + 1]] = matrix1.nnz.f[mat1_i]; local_jas[i][result.ia[i + 1]] = matrix1.ja[mat1_i]; ++result.ia[i + 1]; ++mat1_i; } while(mat2_i < matrix2.ia[i + 1]){ if(local_type == MAT_INT) local_nnzs.i[i][result.ia[i + 1]] = matrix2.nnz.i[mat2_i]; else local_nnzs.f[i][result.ia[i + 1]] = matrix2.nnz.f[mat2_i]; local_jas[i][result.ia[i + 1]] = matrix2.ja[mat2_i]; ++result.ia[i + 1]; ++mat2_i; } } } for(int i = 1; i < result.cols + 1; ++i) result.num_vals += result.ia[i]; if(result.type == MAT_INT){ if(!(result.nnz.i = (int*)malloc(result.num_vals * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } else{ if(!(result.nnz.f = (long double*)malloc(result.num_vals * sizeof(long double)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } } if(!(result.ja = (int*)malloc(result.num_vals * sizeof(int)))){ fprintf(stderr, "Ran out of virtual memory while allocating result matrix\n"); exit(EXIT_FAILURE); } for(int i = 0; i < result.cols; ++i){ if(result.ia[i + 1] > 0){ if(result.type == MAT_INT){ memcpy(&result.nnz.i[result.ia[i]],local_nnzs.i[i], result.ia[i + 1] * sizeof(int)); free(local_nnzs.i[i]); } else{ memcpy(&result.nnz.f[result.ia[i]],local_nnzs.f[i], result.ia[i + 1] * sizeof(long double)); free(local_nnzs.f[i]); } memcpy(&result.ja[result.ia[i]], local_jas[i], result.ia[i + 1] * sizeof(int)); free(local_jas[i]); } result.ia[i + 1] += result.ia[i]; } free(local_jas); if(result.type == MAT_INT) free(local_nnzs.i); else free(local_nnzs.f); get_utc_time(&end); rv = csc_to_mat(result, thread_count); rv.t_process = time_delta(end, start); free_csc(result); return rv; } mat_rv addition(OPERATIONARGS *args) { mat_rv rv; //default = COO if (args->format == FORM_DEFAULT) args->format = COO; switch(args->format){ case COO:{ struct timespec delta1, delta2; struct timespec fileio1, fileio2; coo matrix1 = read_coo(args->file1, &delta1, &fileio1); coo matrix2 = read_coo(args->file2, &delta2, &fileio2); struct timespec construct = time_sum(delta1, delta2); if(args->nothreading) rv = addition_coo_nothreading(matrix1, matrix2); else rv = addition_coo(matrix1, matrix2, args->num_threads); rv.t_construct = time_sum(rv.t_construct, construct); rv.t_fileio = time_sum(fileio1, fileio2); free_coo(matrix1); free_coo(matrix2); return rv; break; } case CSR:{ struct timespec delta1, delta2; struct timespec fileio1, fileio2; csr matrix1 = read_csr(args->file1, &delta1, &fileio1); csr matrix2 = read_csr(args->file2, &delta2, &fileio2); struct timespec construct = time_sum(delta1, delta2); if(args->nothreading) rv = addition_csr_nothreading(matrix1, matrix2); else rv = addition_csr(matrix1, matrix2, args->num_threads); rv.t_construct = time_sum(rv.t_construct, construct); rv.t_fileio = time_sum(fileio1, fileio2); free_csr(matrix1); free_csr(matrix2); return rv; break; } case CSC:{ struct timespec delta1, delta2; struct timespec fileio1, fileio2; csc matrix1 = read_csc(args->file1, &delta1, &fileio1); csc matrix2 = read_csc(args->file2, &delta2, &fileio2); struct timespec construct = time_sum(delta1, delta2); if(args->nothreading) rv = addition_csc_nothreading(matrix1, matrix2); else rv = addition_csc(matrix1, matrix2, args->num_threads); rv.t_construct = time_sum(rv.t_construct, construct); rv.t_fileio = time_sum(fileio1, fileio2); free_csc(matrix1); free_csc(matrix2); return rv; break; } default: fprintf(stderr, "format not implemented\n"); exit(EXIT_FAILURE); break; } //execution should never reach here rv.error = ERR_NOT_SET; return rv; }
GB_unaryop__minv_bool_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_bool_uint8 // op(A') function: GB_tran__minv_bool_uint8 // C type: bool // A type: uint8_t // cast: ; // unaryop: cij = true #define GB_ATYPE \ uint8_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = true ; // casting #define GB_CASTING(z, x) \ ; ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_BOOL || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_bool_uint8 ( bool *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_bool_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__lxor_bool.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__lxor_bool) // A.*B function (eWiseMult): GB (_AemultB_08__lxor_bool) // A.*B function (eWiseMult): GB (_AemultB_02__lxor_bool) // A.*B function (eWiseMult): GB (_AemultB_04__lxor_bool) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lxor_bool) // A*D function (colscale): GB (_AxD__lxor_bool) // D*A function (rowscale): GB (_DxB__lxor_bool) // C+=B function (dense accum): GB (_Cdense_accumB__lxor_bool) // C+=b function (dense accum): GB (_Cdense_accumb__lxor_bool) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lxor_bool) // C=scalar+B GB (_bind1st__lxor_bool) // C=scalar+B' GB (_bind1st_tran__lxor_bool) // C=A+scalar GB (_bind2nd__lxor_bool) // C=A'+scalar GB (_bind2nd_tran__lxor_bool) // C type: bool // A type: bool // A pattern? 0 // B type: bool // B pattern? 0 // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ bool #define GB_BTYPE \ bool #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ bool aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ bool bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x != y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LXOR || GxB_NO_BOOL || GxB_NO_LXOR_BOOL) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__lxor_bool) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__lxor_bool) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__lxor_bool) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type bool bool bwork = (*((bool *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__lxor_bool) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__lxor_bool) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__lxor_bool) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; bool alpha_scalar ; bool beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((bool *) alpha_scalar_in)) ; beta_scalar = (*((bool *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__lxor_bool) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__lxor_bool) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__lxor_bool) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__lxor_bool) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__lxor_bool) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; bool x = (*((bool *) x_input)) ; bool *Bx = (bool *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; bool bij = GBX (Bx, p, false) ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__lxor_bool) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; bool *Ax = (bool *) Ax_input ; bool y = (*((bool *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; bool aij = GBX (Ax, p, false) ; Cx [p] = (aij != y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ bool aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__lxor_bool) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ bool #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool x = (*((const bool *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ bool } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ bool aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__lxor_bool) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool y = (*((const bool *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
papi_helper.h
#ifndef UTILS_PAPI_HELPER_H #define UTILS_PAPI_HELPER_H #include <omp.h> #include <iostream> #include <stdexcept> #include <pthread.h> #ifdef HAVE_PAPI #include <papi.h> #endif #include "colors.h" static long long l1_tcm, l2_tcm, l3_tcm, tlb_dm; void papi_helper_init_thread() { #ifdef HAVE_PAPI if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT) throw std::runtime_error("Error initializing PAPI library!"); if (PAPI_thread_init(pthread_self) != PAPI_OK) throw std::runtime_error("Error setting threading support for PAPI!"); #endif } void papi_helper_start() { #ifdef HAVE_PAPI #pragma omp single l1_tcm = l2_tcm = l3_tcm = tlb_dm = 0; int papi_events[4] = { PAPI_L1_TCM, PAPI_L2_TCM, PAPI_L3_TCM, PAPI_TLB_DM }; if (PAPI_start_counters(papi_events, 4) != PAPI_OK) throw std::runtime_error("Error running PAPI_start_counters function!"); #endif } void papi_helper_stop() { #ifdef HAVE_PAPI long long papi_values[4]; if (PAPI_stop_counters(papi_values, 4) != PAPI_OK) throw std::runtime_error("Error running PAPI_stop_counters function!"); #pragma omp atomic update l1_tcm += papi_values[0]; #pragma omp atomic update l2_tcm += papi_values[1]; #pragma omp atomic update l3_tcm += papi_values[2]; #pragma omp atomic update tlb_dm += papi_values[3]; #endif } void papi_helper_print() { #ifdef HAVE_PAPI std::cout << "L1 cache misses: " << cyan << std::right << std::setw(20) << l1_tcm << reset << std::endl; std::cout << "L2 cache misses: " << cyan << std::right << std::setw(20) << l2_tcm << reset << std::endl; std::cout << "L3 cache misses: " << cyan << std::right << std::setw(20) << l3_tcm << reset << std::endl; std::cout << "TLB misses: " << cyan << std::right << std::setw(20) << tlb_dm << reset << std::endl; #endif } #endif
build_JKmat_DF.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <omp.h> #include "linalg_lib_wrapper.h" #include "utils.h" #include "TinyDFT_typedef.h" #include "build_JKmat_DF.h" void TinyDFT_reduce_temp_J(double *temp_J, double *temp_J_thread, int len, int tid, int nthread) { while (nthread > 1) { int mid = (nthread + 1) / 2; int act_mid = nthread / 2; if (tid < act_mid) { double *dst = temp_J_thread + len * mid; #pragma omp simd for (int i = 0; i < len; i++) temp_J_thread[i] += dst[i]; } #pragma omp barrier nthread = mid; } } // Build temporary array for J matrix and form J matrix // Low flop-per-byte ratio: access: nbf^2 * (df_nbf+1), compute: nbf^2 * df_nbf // Note: the J_mat is not completed, the symmetrizing is done later static void TinyDFT_build_Jmat_DF(TinyDFT_p TinyDFT, const double *D_mat, double *J_mat, double *temp_J_t, double *J_mat_t) { int nbf = TinyDFT->nbf; int df_nbf = TinyDFT->df_nbf; int df_nbf_16 = TinyDFT->df_nbf_16; int nthread = TinyDFT->nthread; int *bf_pair_j = TinyDFT->bf_pair_j; int *bf_pair_diag = TinyDFT->bf_pair_diag; int *bf_mask_displs = TinyDFT->bf_mask_displs; double *temp_J = TinyDFT->temp_J; double *df_tensor = TinyDFT->df_tensor; double t0, t1, t2; #pragma omp parallel { int tid = omp_get_thread_num(); #pragma omp master t0 = get_wtime_sec(); // Use thread local buffer (aligned to 128B) to reduce false sharing double *temp_J_thread = temp_J + df_nbf_16 * tid; // Generate temporary array for J memset(temp_J_thread, 0, sizeof(double) * df_nbf); #pragma omp for schedule(dynamic) for (int k = 0; k < nbf; k++) { int diag_k_idx = bf_pair_diag[k]; int idx_kk = k * nbf + k; // Basis function pair (i, i) always survives screening size_t offset = (size_t) diag_k_idx * (size_t) df_nbf; double *df_tensor_row = df_tensor + offset; double D_kl = D_mat[idx_kk]; #pragma omp simd for (size_t p = 0; p < df_nbf; p++) temp_J_thread[p] += D_kl * df_tensor_row[p]; int row_k_epos = bf_mask_displs[k + 1]; for (int l_idx = diag_k_idx + 1; l_idx < row_k_epos; l_idx++) { int l = bf_pair_j[l_idx]; int idx_kl = k * nbf + l; double D_kl = D_mat[idx_kl] * 2.0; size_t offset = (size_t) l_idx * (size_t) df_nbf; double *df_tensor_row = df_tensor + offset; #pragma omp simd for (size_t p = 0; p < df_nbf; p++) temp_J_thread[p] += D_kl * df_tensor_row[p]; } } #pragma omp barrier TinyDFT_reduce_temp_J(temp_J, temp_J_thread, df_nbf_16, tid, nthread); #pragma omp master t1 = get_wtime_sec(); // Build J matrix #pragma omp for schedule(dynamic) for (int i = 0; i < nbf; i++) { int diag_i_idx = bf_pair_diag[i]; int row_i_epos = bf_mask_displs[i + 1]; for (int j_idx = diag_i_idx; j_idx < row_i_epos; j_idx++) { int j = bf_pair_j[j_idx]; size_t offset = (size_t) j_idx * (size_t) df_nbf; double *df_tensor_row = df_tensor + offset; double t = 0; #pragma omp simd for (size_t p = 0; p < df_nbf; p++) t += temp_J[p] * df_tensor_row[p]; J_mat[i * nbf + j] = t; } } #pragma omp master t2 = get_wtime_sec(); } *temp_J_t = t1 - t0; *J_mat_t = t2 - t1; } static void TinyDFT_set_batch_dgemm_temp_K(TinyDFT_p TinyDFT) { int nbf = TinyDFT->nbf; int df_nbf = TinyDFT->df_nbf; int n_occ = TinyDFT->n_occ; int *bf_mask_displs = TinyDFT->bf_mask_displs; double *Cocc_tmp = TinyDFT->pqA; double *df_tensor = TinyDFT->df_tensor; double *temp_K = TinyDFT->temp_K; for (int i = 0; i < nbf; i++) { int row_spos = bf_mask_displs[i]; int row_epos = bf_mask_displs[i + 1]; int row_len = row_epos - row_spos; size_t offset_a = (size_t) row_spos * (size_t) df_nbf; size_t offset_b = (size_t) row_spos * (size_t) df_nbf; size_t offset_c = (size_t) i * (size_t) n_occ * (size_t) df_nbf; double *A_ptr = Cocc_tmp + offset_a; double *B_ptr = df_tensor + offset_b; double *C_ptr = temp_K + offset_c; TinyDFT->mat_K_transa[i] = CblasTrans; TinyDFT->mat_K_transb[i] = CblasNoTrans; TinyDFT->mat_K_m[i] = n_occ; TinyDFT->mat_K_n[i] = df_nbf; TinyDFT->mat_K_k[i] = row_len; TinyDFT->mat_K_alpha[i] = 1.0; TinyDFT->mat_K_beta[i] = 0.0; TinyDFT->mat_K_a[i] = A_ptr; TinyDFT->mat_K_b[i] = B_ptr; TinyDFT->mat_K_c[i] = C_ptr; TinyDFT->mat_K_lda[i] = df_nbf; TinyDFT->mat_K_ldb[i] = df_nbf; TinyDFT->mat_K_ldc[i] = df_nbf; TinyDFT->mat_K_group_size[i] = 1; } } static void TinyDFT_set_batch_dgemm_K(TinyDFT_p TinyDFT, double *K_mat) { int nbf = TinyDFT->nbf; int df_nbf = TinyDFT->df_nbf; int n_occ = TinyDFT->n_occ; int mat_K_BS = TinyDFT->mat_K_BS; int nblock0 = nbf / mat_K_BS; int bs_rem = nbf % mat_K_BS; int *group_size = TinyDFT->mat_K_group_size; group_size[0] = (nblock0 * (nblock0 + 1)) / 2; if (bs_rem > 0) { group_size[1] = nblock0; group_size[2] = 1; } else { group_size[1] = 0; group_size[2] = 0; } double *temp_K = TinyDFT->temp_K; int cnt0 = 0, cnt1 = group_size[0]; int cnt2 = group_size[0] + group_size[1]; for (int i = 0; i < nbf; i += mat_K_BS) { int i_len = mat_K_BS < (nbf - i) ? mat_K_BS : (nbf - i); for (int j = i; j < nbf; j += mat_K_BS) { int j_len = mat_K_BS < (nbf - j) ? mat_K_BS : (nbf - j); size_t offset_i0 = (size_t) i * (size_t) n_occ * (size_t) df_nbf; size_t offset_j0 = (size_t) j * (size_t) n_occ * (size_t) df_nbf; double *K_ij = K_mat + i * nbf + j; double *temp_K_i = temp_K + offset_i0; double *temp_K_j = temp_K + offset_j0; int cnt, gid; if ((i_len == mat_K_BS) && (j_len == mat_K_BS)) { cnt = cnt0; gid = 0; cnt0++; } else { if ((i_len == mat_K_BS) && (j_len < mat_K_BS)) { cnt = cnt1; gid = 1; cnt1++; } else { cnt = cnt2; gid = 2; } } TinyDFT->mat_K_transa[gid] = CblasNoTrans; TinyDFT->mat_K_transb[gid] = CblasTrans; TinyDFT->mat_K_m[gid] = i_len; TinyDFT->mat_K_n[gid] = j_len; TinyDFT->mat_K_k[gid] = n_occ * df_nbf; TinyDFT->mat_K_alpha[gid] = 1.0; TinyDFT->mat_K_beta[gid] = 0.0; TinyDFT->mat_K_a[cnt] = temp_K_i; TinyDFT->mat_K_b[cnt] = temp_K_j; TinyDFT->mat_K_c[cnt] = K_ij; TinyDFT->mat_K_lda[gid] = n_occ * df_nbf; TinyDFT->mat_K_ldb[gid] = n_occ * df_nbf; TinyDFT->mat_K_ldc[gid] = nbf; } } } #ifndef USE_MKL #warning cblas_dgemm_batch() is not available in your BLAS library, will use cblas_dgemm to simulate it. void cblas_dgemm_batch( const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE *transa_array, const CBLAS_TRANSPOSE *transb_array, const int *m_array, const int *n_array, const int *k_array, const double *alpha_array, const double **a_array, const int *lda_array, const double **b_array, const int *ldb_array, const double *beta_array, double **c_array, const int *ldc_array, const int group_count, const int *group_size ) { int idx = 0; for (int i = 0; i < group_count; i++) { const CBLAS_TRANSPOSE transa_i = transa_array[i]; const CBLAS_TRANSPOSE transb_i = transb_array[i]; const int m_i = m_array[i]; const int n_i = n_array[i]; const int k_i = k_array[i]; const int lda_i = lda_array[i]; const int ldb_i = ldb_array[i]; const int ldc_i = ldc_array[i]; const double alpha_i = alpha_array[i]; const double beta_i = beta_array[i]; for (int j = 0; j < group_size[i]; j++) { const double *a_idx = a_array[idx + j]; const double *b_idx = b_array[idx + j]; double *c_idx = c_array[idx + j]; cblas_dgemm( Layout, transa_i, transb_i, m_i, n_i, k_i, alpha_i, a_idx, lda_i, b_idx, ldb_i, beta_i, c_idx, ldc_i ); } idx += group_size[i]; } } #endif // Build temporary tensor for K matrix and form K matrix using Cocc matrix // High flop-per-byte ratio: access: nbf * df_nbf * (nbf + n_occ) , compute: nbf^2 * df_nbf * n_occ // Note: the K_mat is not completed, the symmetrizing is done later static void TinyDFT_build_Kmat_DF(TinyDFT_p TinyDFT, const double *Cocc_mat, double *K_mat, double *temp_K_t, double *K_mat_t) { int nbf = TinyDFT->nbf; int df_nbf = TinyDFT->df_nbf; int df_save_mem = TinyDFT->df_save_mem; int n_occ = TinyDFT->n_occ; int ngroups_temp_K = nbf; int bf_pair_cnt = TinyDFT->bf_mask_displs[nbf]; int *bf_pair_j = TinyDFT->bf_pair_j; int *bf_mask_displs = TinyDFT->bf_mask_displs; double *df_tensor = TinyDFT->df_tensor; double *temp_K = TinyDFT->temp_K; double *Cocc_tmp = TinyDFT->pqA; double t0, t1, t2; // Construct temporary tensor for K matrix // Formula: temp_K(i, s, p) = dot(Cocc_mat(1:nbf, s), df_tensor(i, 1:nbf, p)) t0 = get_wtime_sec(); if (df_save_mem == 0) { TinyDFT_set_batch_dgemm_temp_K(TinyDFT); #pragma omp parallel for schedule(dynamic) for (int i = 0; i < bf_pair_cnt; i++) { int j = bf_pair_j[i]; size_t Cocc_tmp_offset = (size_t) i * (size_t) df_nbf; size_t Cocc_mat_offset = (size_t) j * (size_t) n_occ; double *Cocc_tmp_ptr = Cocc_tmp + Cocc_tmp_offset; const double *Cocc_mat_ptr = Cocc_mat + Cocc_mat_offset; memcpy(Cocc_tmp_ptr, Cocc_mat_ptr, DBL_MSIZE * n_occ); } cblas_dgemm_batch( CblasRowMajor, TinyDFT->mat_K_transa, TinyDFT->mat_K_transb, TinyDFT->mat_K_m, TinyDFT->mat_K_n, TinyDFT->mat_K_k, TinyDFT->mat_K_alpha, (const double **) TinyDFT->mat_K_a, TinyDFT->mat_K_lda, (const double **) TinyDFT->mat_K_b, TinyDFT->mat_K_ldb, TinyDFT->mat_K_beta, TinyDFT->mat_K_c, TinyDFT->mat_K_ldc, ngroups_temp_K, TinyDFT->mat_K_group_size ); } else { double *A_ptr = TinyDFT->Cocc_mat; double *temp_A = TinyDFT->tmp_mat; for (int i = 0; i < nbf; i++) { size_t offset_c = (size_t) i * (size_t) n_occ * (size_t) df_nbf; double *C_ptr = temp_K + offset_c; int j_idx_spos = bf_mask_displs[i]; int j_idx_epos = bf_mask_displs[i + 1]; for (int j_idx = j_idx_spos; j_idx < j_idx_epos; j_idx++) { int j = bf_pair_j[j_idx]; int cnt = j_idx - j_idx_spos; memcpy(temp_A + cnt * n_occ, A_ptr + j * n_occ, DBL_MSIZE * n_occ); } int ncols = j_idx_epos - j_idx_spos; size_t df_tensor_offset = (size_t) j_idx_spos * (size_t) df_nbf; double *df_tensor_ptr = df_tensor + df_tensor_offset; cblas_dgemm( CblasRowMajor, CblasTrans, CblasNoTrans, n_occ, df_nbf, ncols, 1.0, temp_A, n_occ, df_tensor_ptr, df_nbf, 0.0, C_ptr, df_nbf ); } } // End of "if (df_save_mem == 0)" t1 = get_wtime_sec(); // Build K matrix // Formula: K(i, j) = sum_{s=1}^{n_occ} [ dot(temp_K(i, s, 1:df_nbf), temp_K(j, s, 1:df_nbf)) ] if (nbf <= 1024) { cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasTrans, nbf, nbf, n_occ * df_nbf, 1.0, temp_K, n_occ * df_nbf, temp_K, n_occ * df_nbf, 0.0, K_mat, nbf ); } else { int ngroups = 3; TinyDFT_set_batch_dgemm_K(TinyDFT, K_mat); if (TinyDFT->mat_K_group_size[1] == 0) ngroups = 1; cblas_dgemm_batch( CblasRowMajor, TinyDFT->mat_K_transa, TinyDFT->mat_K_transb, TinyDFT->mat_K_m, TinyDFT->mat_K_n, TinyDFT->mat_K_k, TinyDFT->mat_K_alpha, (const double **) TinyDFT->mat_K_a, TinyDFT->mat_K_lda, (const double **) TinyDFT->mat_K_b, TinyDFT->mat_K_ldb, TinyDFT->mat_K_beta, TinyDFT->mat_K_c, TinyDFT->mat_K_ldc, ngroups, TinyDFT->mat_K_group_size ); } t2 = get_wtime_sec(); *temp_K_t = t1 - t0; *K_mat_t = t2 - t1; } void TinyDFT_build_JKmat_DF(TinyDFT_p TinyDFT, const double *D_mat, const double *Cocc_mat, double *J_mat, double *K_mat) { if (J_mat == NULL && K_mat == NULL) return; int nbf = TinyDFT->nbf; double st, et, total_t, symm_t; double temp_J_t = 0.0, J_mat_t = 0.0; double temp_K_t = 0.0, K_mat_t = 0.0; if (J_mat != NULL) { TinyDFT_build_Jmat_DF(TinyDFT, D_mat, J_mat, &temp_J_t, &J_mat_t); st = get_wtime_sec(); #pragma omp for schedule(dynamic) for (int i = 1; i < nbf; i++) { #pragma omp simd for (int j = 0; j < i; j++) J_mat[i * nbf + j] = J_mat[j * nbf + i]; } et = get_wtime_sec(); symm_t = et - st; total_t = temp_J_t + J_mat_t + symm_t; printf( "* Build J mat using DF : %.3lf (s), " "aux / Jmat / symm = %.3lf, %.3lf, %.3lf\n", total_t, temp_J_t, J_mat_t, symm_t ); } if (K_mat != NULL) { if (TinyDFT->temp_K == NULL) { size_t temp_K_msize = (size_t) TinyDFT->df_nbf * (size_t) TinyDFT->n_occ * (size_t) TinyDFT->nbf; temp_K_msize *= DBL_MSIZE; st = get_wtime_sec(); TinyDFT->temp_K = (double*) malloc_aligned(temp_K_msize, 64); assert(TinyDFT->temp_K != NULL); et = get_wtime_sec(); TinyDFT->mem_size += (double) temp_K_msize; printf("Allocate auxiliary tensor for density fitting K matrix build : %.3lf (s)\n", et - st); } TinyDFT_build_Kmat_DF(TinyDFT, Cocc_mat, K_mat, &temp_K_t, &K_mat_t); st = get_wtime_sec(); #pragma omp for schedule(dynamic) for (int i = 1; i < nbf; i++) { #pragma omp simd for (int j = 0; j < i; j++) K_mat[i * nbf + j] = K_mat[j * nbf + i]; } et = get_wtime_sec(); symm_t = et - st; total_t = temp_K_t + K_mat_t + symm_t; printf( "* Build K mat using DF : %.3lf (s), " "aux / Kmat / symm = %.3lf, %.3lf, %.3lf\n", total_t, temp_K_t, K_mat_t, symm_t ); } }
Stmt.h
//===--- Stmt.h - Classes for representing statements -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Stmt interface and subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_STMT_H #define LLVM_CLANG_AST_STMT_H #include "clang/AST/DeclGroup.h" #include "clang/AST/StmtIterator.h" #include "clang/Basic/CapturedStmt.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include <string> namespace llvm { class FoldingSetNodeID; } namespace clang { class ASTContext; class Attr; class CapturedDecl; class Decl; class Expr; class IdentifierInfo; class LabelDecl; class ParmVarDecl; class PrinterHelper; struct PrintingPolicy; class QualType; class RecordDecl; class SourceManager; class StringLiteral; class SwitchStmt; class Token; class VarDecl; //===--------------------------------------------------------------------===// // ExprIterator - Iterators for iterating over Stmt* arrays that contain // only Expr*. This is needed because AST nodes use Stmt* arrays to store // references to children (to be compatible with StmtIterator). //===--------------------------------------------------------------------===// class Stmt; class Expr; class ExprIterator { Stmt** I; public: ExprIterator(Stmt** i) : I(i) {} ExprIterator() : I(nullptr) {} ExprIterator& operator++() { ++I; return *this; } ExprIterator operator-(size_t i) { return I-i; } ExprIterator operator+(size_t i) { return I+i; } Expr* operator[](size_t idx); // FIXME: Verify that this will correctly return a signed distance. signed operator-(const ExprIterator& R) const { return I - R.I; } Expr* operator*() const; Expr* operator->() const; bool operator==(const ExprIterator& R) const { return I == R.I; } bool operator!=(const ExprIterator& R) const { return I != R.I; } bool operator>(const ExprIterator& R) const { return I > R.I; } bool operator>=(const ExprIterator& R) const { return I >= R.I; } }; class ConstExprIterator { const Stmt * const *I; public: ConstExprIterator(const Stmt * const *i) : I(i) {} ConstExprIterator() : I(nullptr) {} ConstExprIterator& operator++() { ++I; return *this; } ConstExprIterator operator+(size_t i) const { return I+i; } ConstExprIterator operator-(size_t i) const { return I-i; } const Expr * operator[](size_t idx) const; signed operator-(const ConstExprIterator& R) const { return I - R.I; } const Expr * operator*() const; const Expr * operator->() const; bool operator==(const ConstExprIterator& R) const { return I == R.I; } bool operator!=(const ConstExprIterator& R) const { return I != R.I; } bool operator>(const ConstExprIterator& R) const { return I > R.I; } bool operator>=(const ConstExprIterator& R) const { return I >= R.I; } }; //===----------------------------------------------------------------------===// // AST classes for statements. //===----------------------------------------------------------------------===// /// Stmt - This represents one statement. /// class Stmt { public: enum StmtClass { NoStmtClass = 0, #define STMT(CLASS, PARENT) CLASS##Class, #define STMT_RANGE(BASE, FIRST, LAST) \ first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class, #define LAST_STMT_RANGE(BASE, FIRST, LAST) \ first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class #define ABSTRACT_STMT(STMT) #include "clang/AST/StmtNodes.inc" }; // Make vanilla 'new' and 'delete' illegal for Stmts. protected: void* operator new(size_t bytes) throw() { llvm_unreachable("Stmts cannot be allocated with regular 'new'."); } void operator delete(void* data) throw() { llvm_unreachable("Stmts cannot be released with regular 'delete'."); } class StmtBitfields { friend class Stmt; /// \brief The statement class. unsigned sClass : 8; }; enum { NumStmtBits = 8 }; class CompoundStmtBitfields { friend class CompoundStmt; unsigned : NumStmtBits; unsigned NumStmts : 32 - NumStmtBits; }; class ExprBitfields { friend class Expr; friend class DeclRefExpr; // computeDependence friend class InitListExpr; // ctor friend class DesignatedInitExpr; // ctor friend class BlockDeclRefExpr; // ctor friend class ASTStmtReader; // deserialization friend class CXXNewExpr; // ctor friend class DependentScopeDeclRefExpr; // ctor friend class CXXConstructExpr; // ctor friend class CallExpr; // ctor friend class OffsetOfExpr; // ctor friend class ObjCMessageExpr; // ctor friend class ObjCArrayLiteral; // ctor friend class ObjCDictionaryLiteral; // ctor friend class ShuffleVectorExpr; // ctor friend class ParenListExpr; // ctor friend class CXXUnresolvedConstructExpr; // ctor friend class CXXDependentScopeMemberExpr; // ctor friend class OverloadExpr; // ctor friend class PseudoObjectExpr; // ctor friend class AtomicExpr; // ctor unsigned : NumStmtBits; unsigned ValueKind : 2; unsigned ObjectKind : 2; unsigned TypeDependent : 1; unsigned ValueDependent : 1; unsigned InstantiationDependent : 1; unsigned ContainsUnexpandedParameterPack : 1; }; enum { NumExprBits = 16 }; class CharacterLiteralBitfields { friend class CharacterLiteral; unsigned : NumExprBits; unsigned Kind : 2; }; enum APFloatSemantics { IEEEhalf, IEEEsingle, IEEEdouble, x87DoubleExtended, IEEEquad, PPCDoubleDouble }; class FloatingLiteralBitfields { friend class FloatingLiteral; unsigned : NumExprBits; unsigned Semantics : 3; // Provides semantics for APFloat construction unsigned IsExact : 1; }; class UnaryExprOrTypeTraitExprBitfields { friend class UnaryExprOrTypeTraitExpr; unsigned : NumExprBits; unsigned Kind : 2; unsigned IsType : 1; // true if operand is a type, false if an expression. }; class DeclRefExprBitfields { friend class DeclRefExpr; friend class ASTStmtReader; // deserialization unsigned : NumExprBits; unsigned HasQualifier : 1; unsigned HasTemplateKWAndArgsInfo : 1; unsigned HasFoundDecl : 1; unsigned HadMultipleCandidates : 1; unsigned RefersToCapturedVariable : 1; }; class CastExprBitfields { friend class CastExpr; unsigned : NumExprBits; unsigned Kind : 6; unsigned BasePathSize : 32 - 6 - NumExprBits; }; class CallExprBitfields { friend class CallExpr; unsigned : NumExprBits; unsigned NumPreArgs : 1; }; class ExprWithCleanupsBitfields { friend class ExprWithCleanups; friend class ASTStmtReader; // deserialization unsigned : NumExprBits; unsigned NumObjects : 32 - NumExprBits; }; class PseudoObjectExprBitfields { friend class PseudoObjectExpr; friend class ASTStmtReader; // deserialization unsigned : NumExprBits; // These don't need to be particularly wide, because they're // strictly limited by the forms of expressions we permit. unsigned NumSubExprs : 8; unsigned ResultIndex : 32 - 8 - NumExprBits; }; class ObjCIndirectCopyRestoreExprBitfields { friend class ObjCIndirectCopyRestoreExpr; unsigned : NumExprBits; unsigned ShouldCopy : 1; }; class InitListExprBitfields { friend class InitListExpr; unsigned : NumExprBits; /// Whether this initializer list originally had a GNU array-range /// designator in it. This is a temporary marker used by CodeGen. unsigned HadArrayRangeDesignator : 1; }; class TypeTraitExprBitfields { friend class TypeTraitExpr; friend class ASTStmtReader; friend class ASTStmtWriter; unsigned : NumExprBits; /// \brief The kind of type trait, which is a value of a TypeTrait enumerator. unsigned Kind : 8; /// \brief If this expression is not value-dependent, this indicates whether /// the trait evaluated true or false. unsigned Value : 1; /// \brief The number of arguments to this type trait. unsigned NumArgs : 32 - 8 - 1 - NumExprBits; }; union { // FIXME: this is wasteful on 64-bit platforms. void *Aligner; StmtBitfields StmtBits; CompoundStmtBitfields CompoundStmtBits; ExprBitfields ExprBits; CharacterLiteralBitfields CharacterLiteralBits; FloatingLiteralBitfields FloatingLiteralBits; UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits; DeclRefExprBitfields DeclRefExprBits; CastExprBitfields CastExprBits; CallExprBitfields CallExprBits; ExprWithCleanupsBitfields ExprWithCleanupsBits; PseudoObjectExprBitfields PseudoObjectExprBits; ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits; InitListExprBitfields InitListExprBits; TypeTraitExprBitfields TypeTraitExprBits; }; friend class ASTStmtReader; friend class ASTStmtWriter; public: // Only allow allocation of Stmts using the allocator in ASTContext // or by doing a placement new. void* operator new(size_t bytes, const ASTContext& C, unsigned alignment = 8); void* operator new(size_t bytes, const ASTContext* C, unsigned alignment = 8) { return operator new(bytes, *C, alignment); } void* operator new(size_t bytes, void* mem) throw() { return mem; } void operator delete(void*, const ASTContext&, unsigned) throw() { } void operator delete(void*, const ASTContext*, unsigned) throw() { } void operator delete(void*, size_t) throw() { } void operator delete(void*, void*) throw() { } public: /// \brief A placeholder type used to construct an empty shell of a /// type, that will be filled in later (e.g., by some /// de-serialization). struct EmptyShell { }; private: /// \brief Whether statistic collection is enabled. static bool StatisticsEnabled; protected: /// \brief Construct an empty statement. explicit Stmt(StmtClass SC, EmptyShell) { StmtBits.sClass = SC; if (StatisticsEnabled) Stmt::addStmtClass(SC); } public: Stmt(StmtClass SC) { StmtBits.sClass = SC; if (StatisticsEnabled) Stmt::addStmtClass(SC); } StmtClass getStmtClass() const { return static_cast<StmtClass>(StmtBits.sClass); } const char *getStmtClassName() const; /// SourceLocation tokens are not useful in isolation - they are low level /// value objects created/interpreted by SourceManager. We assume AST /// clients will have a pointer to the respective SourceManager. SourceRange getSourceRange() const LLVM_READONLY; SourceLocation getLocStart() const LLVM_READONLY; SourceLocation getLocEnd() const LLVM_READONLY; // global temp stats (until we have a per-module visitor) static void addStmtClass(const StmtClass s); static void EnableStatistics(); static void PrintStats(); /// \brief Dumps the specified AST fragment and all subtrees to /// \c llvm::errs(). void dump() const; void dump(SourceManager &SM) const; void dump(raw_ostream &OS, SourceManager &SM) const; /// dumpColor - same as dump(), but forces color highlighting. void dumpColor() const; /// dumpPretty/printPretty - These two methods do a "pretty print" of the AST /// back to its original source language syntax. void dumpPretty(const ASTContext &Context) const; void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation = 0) const; /// viewAST - Visualize an AST rooted at this Stmt* using GraphViz. Only /// works on systems with GraphViz (Mac OS X) or dot+gv installed. void viewAST() const; /// Skip past any implicit AST nodes which might surround this /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes. Stmt *IgnoreImplicit(); /// \brief Skip no-op (attributed, compound) container stmts and skip captured /// stmt at the top, if \a IgnoreCaptured is true. Stmt *IgnoreContainers(bool IgnoreCaptured = false); const Stmt *stripLabelLikeStatements() const; Stmt *stripLabelLikeStatements() { return const_cast<Stmt*>( const_cast<const Stmt*>(this)->stripLabelLikeStatements()); } /// Child Iterators: All subclasses must implement 'children' /// to permit easy iteration over the substatements/subexpessions of an /// AST node. This permits easy iteration over all nodes in the AST. typedef StmtIterator child_iterator; typedef ConstStmtIterator const_child_iterator; typedef StmtRange child_range; typedef ConstStmtRange const_child_range; child_range children(); const_child_range children() const { return const_cast<Stmt*>(this)->children(); } child_iterator child_begin() { return children().first; } child_iterator child_end() { return children().second; } const_child_iterator child_begin() const { return children().first; } const_child_iterator child_end() const { return children().second; } /// \brief Produce a unique representation of the given statement. /// /// \param ID once the profiling operation is complete, will contain /// the unique representation of the given statement. /// /// \param Context the AST context in which the statement resides /// /// \param Canonical whether the profile should be based on the canonical /// representation of this statement (e.g., where non-type template /// parameters are identified by index/level rather than their /// declaration pointers) or the exact representation of the statement as /// written in the source. void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const; }; /// DeclStmt - Adaptor class for mixing declarations with statements and /// expressions. For example, CompoundStmt mixes statements, expressions /// and declarations (variables, types). Another example is ForStmt, where /// the first statement can be an expression or a declaration. /// class DeclStmt : public Stmt { DeclGroupRef DG; SourceLocation StartLoc, EndLoc; public: DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc) : Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {} /// \brief Build an empty declaration statement. explicit DeclStmt(EmptyShell Empty) : Stmt(DeclStmtClass, Empty) { } /// isSingleDecl - This method returns true if this DeclStmt refers /// to a single Decl. bool isSingleDecl() const { return DG.isSingleDecl(); } const Decl *getSingleDecl() const { return DG.getSingleDecl(); } Decl *getSingleDecl() { return DG.getSingleDecl(); } const DeclGroupRef getDeclGroup() const { return DG; } DeclGroupRef getDeclGroup() { return DG; } void setDeclGroup(DeclGroupRef DGR) { DG = DGR; } SourceLocation getStartLoc() const { return StartLoc; } void setStartLoc(SourceLocation L) { StartLoc = L; } SourceLocation getEndLoc() const { return EndLoc; } void setEndLoc(SourceLocation L) { EndLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return StartLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return EndLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == DeclStmtClass; } // Iterators over subexpressions. child_range children() { return child_range(child_iterator(DG.begin(), DG.end()), child_iterator(DG.end(), DG.end())); } typedef DeclGroupRef::iterator decl_iterator; typedef DeclGroupRef::const_iterator const_decl_iterator; typedef llvm::iterator_range<decl_iterator> decl_range; typedef llvm::iterator_range<const_decl_iterator> decl_const_range; decl_range decls() { return decl_range(decl_begin(), decl_end()); } decl_const_range decls() const { return decl_const_range(decl_begin(), decl_end()); } decl_iterator decl_begin() { return DG.begin(); } decl_iterator decl_end() { return DG.end(); } const_decl_iterator decl_begin() const { return DG.begin(); } const_decl_iterator decl_end() const { return DG.end(); } typedef std::reverse_iterator<decl_iterator> reverse_decl_iterator; reverse_decl_iterator decl_rbegin() { return reverse_decl_iterator(decl_end()); } reverse_decl_iterator decl_rend() { return reverse_decl_iterator(decl_begin()); } }; /// NullStmt - This is the null statement ";": C99 6.8.3p3. /// class NullStmt : public Stmt { SourceLocation SemiLoc; /// \brief True if the null statement was preceded by an empty macro, e.g: /// @code /// #define CALL(x) /// CALL(0); /// @endcode bool HasLeadingEmptyMacro; public: NullStmt(SourceLocation L, bool hasLeadingEmptyMacro = false) : Stmt(NullStmtClass), SemiLoc(L), HasLeadingEmptyMacro(hasLeadingEmptyMacro) {} /// \brief Build an empty null statement. explicit NullStmt(EmptyShell Empty) : Stmt(NullStmtClass, Empty), HasLeadingEmptyMacro(false) { } SourceLocation getSemiLoc() const { return SemiLoc; } void setSemiLoc(SourceLocation L) { SemiLoc = L; } bool hasLeadingEmptyMacro() const { return HasLeadingEmptyMacro; } SourceLocation getLocStart() const LLVM_READONLY { return SemiLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SemiLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == NullStmtClass; } child_range children() { return child_range(); } friend class ASTStmtReader; friend class ASTStmtWriter; }; /// CompoundStmt - This represents a group of statements like { stmt stmt }. /// class CompoundStmt : public Stmt { Stmt** Body; SourceLocation LBraceLoc, RBraceLoc; friend class ASTStmtReader; public: CompoundStmt(const ASTContext &C, ArrayRef<Stmt*> Stmts, SourceLocation LB, SourceLocation RB); // \brief Build an empty compound statement with a location. explicit CompoundStmt(SourceLocation Loc) : Stmt(CompoundStmtClass), Body(nullptr), LBraceLoc(Loc), RBraceLoc(Loc) { CompoundStmtBits.NumStmts = 0; } // \brief Build an empty compound statement. explicit CompoundStmt(EmptyShell Empty) : Stmt(CompoundStmtClass, Empty), Body(nullptr) { CompoundStmtBits.NumStmts = 0; } void setStmts(const ASTContext &C, Stmt **Stmts, unsigned NumStmts); bool body_empty() const { return CompoundStmtBits.NumStmts == 0; } unsigned size() const { return CompoundStmtBits.NumStmts; } typedef Stmt** body_iterator; typedef llvm::iterator_range<body_iterator> body_range; body_range body() { return body_range(body_begin(), body_end()); } body_iterator body_begin() { return Body; } body_iterator body_end() { return Body + size(); } Stmt *body_back() { return !body_empty() ? Body[size()-1] : nullptr; } void setLastStmt(Stmt *S) { assert(!body_empty() && "setLastStmt"); Body[size()-1] = S; } typedef Stmt* const * const_body_iterator; typedef llvm::iterator_range<const_body_iterator> body_const_range; body_const_range body() const { return body_const_range(body_begin(), body_end()); } const_body_iterator body_begin() const { return Body; } const_body_iterator body_end() const { return Body + size(); } const Stmt *body_back() const { return !body_empty() ? Body[size() - 1] : nullptr; } typedef std::reverse_iterator<body_iterator> reverse_body_iterator; reverse_body_iterator body_rbegin() { return reverse_body_iterator(body_end()); } reverse_body_iterator body_rend() { return reverse_body_iterator(body_begin()); } typedef std::reverse_iterator<const_body_iterator> const_reverse_body_iterator; const_reverse_body_iterator body_rbegin() const { return const_reverse_body_iterator(body_end()); } const_reverse_body_iterator body_rend() const { return const_reverse_body_iterator(body_begin()); } SourceLocation getLocStart() const LLVM_READONLY { return LBraceLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RBraceLoc; } SourceLocation getLBracLoc() const { return LBraceLoc; } SourceLocation getRBracLoc() const { return RBraceLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == CompoundStmtClass; } // Iterators child_range children() { return child_range(Body, Body + CompoundStmtBits.NumStmts); } const_child_range children() const { return child_range(Body, Body + CompoundStmtBits.NumStmts); } }; // SwitchCase is the base class for CaseStmt and DefaultStmt, class SwitchCase : public Stmt { protected: // A pointer to the following CaseStmt or DefaultStmt class, // used by SwitchStmt. SwitchCase *NextSwitchCase; SourceLocation KeywordLoc; SourceLocation ColonLoc; SwitchCase(StmtClass SC, SourceLocation KWLoc, SourceLocation ColonLoc) : Stmt(SC), NextSwitchCase(nullptr), KeywordLoc(KWLoc), ColonLoc(ColonLoc) { } SwitchCase(StmtClass SC, EmptyShell) : Stmt(SC), NextSwitchCase(nullptr) {} public: const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; } SwitchCase *getNextSwitchCase() { return NextSwitchCase; } void setNextSwitchCase(SwitchCase *SC) { NextSwitchCase = SC; } SourceLocation getKeywordLoc() const { return KeywordLoc; } void setKeywordLoc(SourceLocation L) { KeywordLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } Stmt *getSubStmt(); const Stmt *getSubStmt() const { return const_cast<SwitchCase*>(this)->getSubStmt(); } SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; } SourceLocation getLocEnd() const LLVM_READONLY; static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass || T->getStmtClass() == DefaultStmtClass; } }; class CaseStmt : public SwitchCase { enum { LHS, RHS, SUBSTMT, END_EXPR }; Stmt* SubExprs[END_EXPR]; // The expression for the RHS is Non-null for // GNU "case 1 ... 4" extension SourceLocation EllipsisLoc; public: CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc, SourceLocation ellipsisLoc, SourceLocation colonLoc) : SwitchCase(CaseStmtClass, caseLoc, colonLoc) { SubExprs[SUBSTMT] = nullptr; SubExprs[LHS] = reinterpret_cast<Stmt*>(lhs); SubExprs[RHS] = reinterpret_cast<Stmt*>(rhs); EllipsisLoc = ellipsisLoc; } /// \brief Build an empty switch case statement. explicit CaseStmt(EmptyShell Empty) : SwitchCase(CaseStmtClass, Empty) { } SourceLocation getCaseLoc() const { return KeywordLoc; } void setCaseLoc(SourceLocation L) { KeywordLoc = L; } SourceLocation getEllipsisLoc() const { return EllipsisLoc; } void setEllipsisLoc(SourceLocation L) { EllipsisLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } Expr *getLHS() { return reinterpret_cast<Expr*>(SubExprs[LHS]); } Expr *getRHS() { return reinterpret_cast<Expr*>(SubExprs[RHS]); } Stmt *getSubStmt() { return SubExprs[SUBSTMT]; } const Expr *getLHS() const { return reinterpret_cast<const Expr*>(SubExprs[LHS]); } const Expr *getRHS() const { return reinterpret_cast<const Expr*>(SubExprs[RHS]); } const Stmt *getSubStmt() const { return SubExprs[SUBSTMT]; } void setSubStmt(Stmt *S) { SubExprs[SUBSTMT] = S; } void setLHS(Expr *Val) { SubExprs[LHS] = reinterpret_cast<Stmt*>(Val); } void setRHS(Expr *Val) { SubExprs[RHS] = reinterpret_cast<Stmt*>(Val); } SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; } SourceLocation getLocEnd() const LLVM_READONLY { // Handle deeply nested case statements with iteration instead of recursion. const CaseStmt *CS = this; while (const CaseStmt *CS2 = dyn_cast<CaseStmt>(CS->getSubStmt())) CS = CS2; return CS->getSubStmt()->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[END_EXPR]); } }; class DefaultStmt : public SwitchCase { Stmt* SubStmt; public: DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt) : SwitchCase(DefaultStmtClass, DL, CL), SubStmt(substmt) {} /// \brief Build an empty default statement. explicit DefaultStmt(EmptyShell Empty) : SwitchCase(DefaultStmtClass, Empty) { } Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } void setSubStmt(Stmt *S) { SubStmt = S; } SourceLocation getDefaultLoc() const { return KeywordLoc; } void setDefaultLoc(SourceLocation L) { KeywordLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();} static bool classof(const Stmt *T) { return T->getStmtClass() == DefaultStmtClass; } // Iterators child_range children() { return child_range(&SubStmt, &SubStmt+1); } }; inline SourceLocation SwitchCase::getLocEnd() const { if (const CaseStmt *CS = dyn_cast<CaseStmt>(this)) return CS->getLocEnd(); return cast<DefaultStmt>(this)->getLocEnd(); } /// LabelStmt - Represents a label, which has a substatement. For example: /// foo: return; /// class LabelStmt : public Stmt { LabelDecl *TheDecl; Stmt *SubStmt; SourceLocation IdentLoc; public: LabelStmt(SourceLocation IL, LabelDecl *D, Stmt *substmt) : Stmt(LabelStmtClass), TheDecl(D), SubStmt(substmt), IdentLoc(IL) { } // \brief Build an empty label statement. explicit LabelStmt(EmptyShell Empty) : Stmt(LabelStmtClass, Empty) { } SourceLocation getIdentLoc() const { return IdentLoc; } LabelDecl *getDecl() const { return TheDecl; } void setDecl(LabelDecl *D) { TheDecl = D; } const char *getName() const; Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } void setIdentLoc(SourceLocation L) { IdentLoc = L; } void setSubStmt(Stmt *SS) { SubStmt = SS; } SourceLocation getLocStart() const LLVM_READONLY { return IdentLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();} child_range children() { return child_range(&SubStmt, &SubStmt+1); } static bool classof(const Stmt *T) { return T->getStmtClass() == LabelStmtClass; } }; /// \brief Represents an attribute applied to a statement. /// /// Represents an attribute applied to a statement. For example: /// [[omp::for(...)]] for (...) { ... } /// class AttributedStmt : public Stmt { Stmt *SubStmt; SourceLocation AttrLoc; unsigned NumAttrs; friend class ASTStmtReader; AttributedStmt(SourceLocation Loc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt) : Stmt(AttributedStmtClass), SubStmt(SubStmt), AttrLoc(Loc), NumAttrs(Attrs.size()) { memcpy(getAttrArrayPtr(), Attrs.data(), Attrs.size() * sizeof(Attr *)); } explicit AttributedStmt(EmptyShell Empty, unsigned NumAttrs) : Stmt(AttributedStmtClass, Empty), NumAttrs(NumAttrs) { memset(getAttrArrayPtr(), 0, NumAttrs * sizeof(Attr *)); } Attr *const *getAttrArrayPtr() const { return reinterpret_cast<Attr *const *>(this + 1); } Attr **getAttrArrayPtr() { return reinterpret_cast<Attr **>(this + 1); } public: static AttributedStmt *Create(const ASTContext &C, SourceLocation Loc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); // \brief Build an empty attributed statement. static AttributedStmt *CreateEmpty(const ASTContext &C, unsigned NumAttrs); SourceLocation getAttrLoc() const { return AttrLoc; } ArrayRef<const Attr*> getAttrs() const { return llvm::makeArrayRef(getAttrArrayPtr(), NumAttrs); } Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } SourceLocation getLocStart() const LLVM_READONLY { return AttrLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();} child_range children() { return child_range(&SubStmt, &SubStmt + 1); } static bool classof(const Stmt *T) { return T->getStmtClass() == AttributedStmtClass; } }; /// IfStmt - This represents an if/then/else. /// class IfStmt : public Stmt { enum { VAR, COND, THEN, ELSE, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation IfLoc; SourceLocation ElseLoc; public: IfStmt(const ASTContext &C, SourceLocation IL, VarDecl *var, Expr *cond, Stmt *then, SourceLocation EL = SourceLocation(), Stmt *elsev = nullptr); /// \brief Build an empty if/then/else statement explicit IfStmt(EmptyShell Empty) : Stmt(IfStmtClass, Empty) { } /// \brief Retrieve the variable declared in this "if" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// if (int x = foo()) { /// printf("x is %d", x); /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(const ASTContext &C, VarDecl *V); /// If this IfStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[VAR]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt *>(E); } const Stmt *getThen() const { return SubExprs[THEN]; } void setThen(Stmt *S) { SubExprs[THEN] = S; } const Stmt *getElse() const { return SubExprs[ELSE]; } void setElse(Stmt *S) { SubExprs[ELSE] = S; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } Stmt *getThen() { return SubExprs[THEN]; } Stmt *getElse() { return SubExprs[ELSE]; } SourceLocation getIfLoc() const { return IfLoc; } void setIfLoc(SourceLocation L) { IfLoc = L; } SourceLocation getElseLoc() const { return ElseLoc; } void setElseLoc(SourceLocation L) { ElseLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return IfLoc; } SourceLocation getLocEnd() const LLVM_READONLY { if (SubExprs[ELSE]) return SubExprs[ELSE]->getLocEnd(); else return SubExprs[THEN]->getLocEnd(); } // Iterators over subexpressions. The iterators will include iterating // over the initialization expression referenced by the condition variable. child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } static bool classof(const Stmt *T) { return T->getStmtClass() == IfStmtClass; } }; /// SwitchStmt - This represents a 'switch' stmt. /// class SwitchStmt : public Stmt { enum { VAR, COND, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // This points to a linked list of case and default statements. SwitchCase *FirstCase; SourceLocation SwitchLoc; /// If the SwitchStmt is a switch on an enum value, this records whether /// all the enum values were covered by CaseStmts. This value is meant to /// be a hint for possible clients. unsigned AllEnumCasesCovered : 1; public: SwitchStmt(const ASTContext &C, VarDecl *Var, Expr *cond); /// \brief Build a empty switch statement. explicit SwitchStmt(EmptyShell Empty) : Stmt(SwitchStmtClass, Empty) { } /// \brief Retrieve the variable declared in this "switch" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// switch (int x = foo()) { /// case 0: break; /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(const ASTContext &C, VarDecl *V); /// If this SwitchStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[VAR]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Stmt *getBody() const { return SubExprs[BODY]; } const SwitchCase *getSwitchCaseList() const { return FirstCase; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt *>(E); } Stmt *getBody() { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SwitchCase *getSwitchCaseList() { return FirstCase; } /// \brief Set the case list for this switch statement. void setSwitchCaseList(SwitchCase *SC) { FirstCase = SC; } SourceLocation getSwitchLoc() const { return SwitchLoc; } void setSwitchLoc(SourceLocation L) { SwitchLoc = L; } void setBody(Stmt *S, SourceLocation SL) { SubExprs[BODY] = S; SwitchLoc = SL; } void addSwitchCase(SwitchCase *SC) { assert(!SC->getNextSwitchCase() && "case/default already added to a switch"); SC->setNextSwitchCase(FirstCase); FirstCase = SC; } /// Set a flag in the SwitchStmt indicating that if the 'switch (X)' is a /// switch over an enum value then all cases have been explicitly covered. void setAllEnumCasesCovered() { AllEnumCasesCovered = 1; } /// Returns true if the SwitchStmt is a switch of an enum value and all cases /// have been explicitly covered. bool isAllEnumCasesCovered() const { return (bool) AllEnumCasesCovered; } SourceLocation getLocStart() const LLVM_READONLY { return SwitchLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubExprs[BODY] ? SubExprs[BODY]->getLocEnd() : SubExprs[COND]->getLocEnd(); } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } static bool classof(const Stmt *T) { return T->getStmtClass() == SwitchStmtClass; } }; /// WhileStmt - This represents a 'while' stmt. /// class WhileStmt : public Stmt { enum { VAR, COND, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation WhileLoc; public: WhileStmt(const ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body, SourceLocation WL); /// \brief Build an empty while statement. explicit WhileStmt(EmptyShell Empty) : Stmt(WhileStmtClass, Empty) { } /// \brief Retrieve the variable declared in this "while" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// while (int x = random()) { /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(const ASTContext &C, VarDecl *V); /// If this WhileStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[VAR]); } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getBody() const { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getWhileLoc() const { return WhileLoc; } void setWhileLoc(SourceLocation L) { WhileLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return WhileLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubExprs[BODY]->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == WhileStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } }; /// DoStmt - This represents a 'do/while' stmt. /// class DoStmt : public Stmt { enum { BODY, COND, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation DoLoc; SourceLocation WhileLoc; SourceLocation RParenLoc; // Location of final ')' in do stmt condition. public: DoStmt(Stmt *body, Expr *cond, SourceLocation DL, SourceLocation WL, SourceLocation RP) : Stmt(DoStmtClass), DoLoc(DL), WhileLoc(WL), RParenLoc(RP) { SubExprs[COND] = reinterpret_cast<Stmt*>(cond); SubExprs[BODY] = body; } /// \brief Build an empty do-while statement. explicit DoStmt(EmptyShell Empty) : Stmt(DoStmtClass, Empty) { } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getBody() const { return SubExprs[BODY]; } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getDoLoc() const { return DoLoc; } void setDoLoc(SourceLocation L) { DoLoc = L; } SourceLocation getWhileLoc() const { return WhileLoc; } void setWhileLoc(SourceLocation L) { WhileLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return DoLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == DoStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } }; /// ForStmt - This represents a 'for (init;cond;inc)' stmt. Note that any of /// the init/cond/inc parts of the ForStmt will be null if they were not /// specified in the source. /// class ForStmt : public Stmt { enum { INIT, CONDVAR, COND, INC, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // SubExprs[INIT] is an expression or declstmt. SourceLocation ForLoc; SourceLocation LParenLoc, RParenLoc; public: ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar, Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP, SourceLocation RP); /// \brief Build an empty for statement. explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) { } Stmt *getInit() { return SubExprs[INIT]; } /// \brief Retrieve the variable declared in this "for" statement, if any. /// /// In the following example, "y" is the condition variable. /// \code /// for (int x = random(); int y = mangle(x); ++x) { /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(const ASTContext &C, VarDecl *V); /// If this ForStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[CONDVAR]); } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } Expr *getInc() { return reinterpret_cast<Expr*>(SubExprs[INC]); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getInit() const { return SubExprs[INIT]; } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Expr *getInc() const { return reinterpret_cast<Expr*>(SubExprs[INC]); } const Stmt *getBody() const { return SubExprs[BODY]; } void setInit(Stmt *S) { SubExprs[INIT] = S; } void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } void setInc(Expr *E) { SubExprs[INC] = reinterpret_cast<Stmt*>(E); } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getForLoc() const { return ForLoc; } void setForLoc(SourceLocation L) { ForLoc = L; } SourceLocation getLParenLoc() const { return LParenLoc; } void setLParenLoc(SourceLocation L) { LParenLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return ForLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return SubExprs[BODY]->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ForStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } }; /// GotoStmt - This represents a direct goto. /// class GotoStmt : public Stmt { LabelDecl *Label; SourceLocation GotoLoc; SourceLocation LabelLoc; public: GotoStmt(LabelDecl *label, SourceLocation GL, SourceLocation LL) : Stmt(GotoStmtClass), Label(label), GotoLoc(GL), LabelLoc(LL) {} /// \brief Build an empty goto statement. explicit GotoStmt(EmptyShell Empty) : Stmt(GotoStmtClass, Empty) { } LabelDecl *getLabel() const { return Label; } void setLabel(LabelDecl *D) { Label = D; } SourceLocation getGotoLoc() const { return GotoLoc; } void setGotoLoc(SourceLocation L) { GotoLoc = L; } SourceLocation getLabelLoc() const { return LabelLoc; } void setLabelLoc(SourceLocation L) { LabelLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return GotoLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == GotoStmtClass; } // Iterators child_range children() { return child_range(); } }; /// IndirectGotoStmt - This represents an indirect goto. /// class IndirectGotoStmt : public Stmt { SourceLocation GotoLoc; SourceLocation StarLoc; Stmt *Target; public: IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, Expr *target) : Stmt(IndirectGotoStmtClass), GotoLoc(gotoLoc), StarLoc(starLoc), Target((Stmt*)target) {} /// \brief Build an empty indirect goto statement. explicit IndirectGotoStmt(EmptyShell Empty) : Stmt(IndirectGotoStmtClass, Empty) { } void setGotoLoc(SourceLocation L) { GotoLoc = L; } SourceLocation getGotoLoc() const { return GotoLoc; } void setStarLoc(SourceLocation L) { StarLoc = L; } SourceLocation getStarLoc() const { return StarLoc; } Expr *getTarget() { return reinterpret_cast<Expr*>(Target); } const Expr *getTarget() const {return reinterpret_cast<const Expr*>(Target);} void setTarget(Expr *E) { Target = reinterpret_cast<Stmt*>(E); } /// getConstantTarget - Returns the fixed target of this indirect /// goto, if one exists. LabelDecl *getConstantTarget(); const LabelDecl *getConstantTarget() const { return const_cast<IndirectGotoStmt*>(this)->getConstantTarget(); } SourceLocation getLocStart() const LLVM_READONLY { return GotoLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return Target->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == IndirectGotoStmtClass; } // Iterators child_range children() { return child_range(&Target, &Target+1); } }; /// ContinueStmt - This represents a continue. /// class ContinueStmt : public Stmt { SourceLocation ContinueLoc; public: ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass), ContinueLoc(CL) {} /// \brief Build an empty continue statement. explicit ContinueStmt(EmptyShell Empty) : Stmt(ContinueStmtClass, Empty) { } SourceLocation getContinueLoc() const { return ContinueLoc; } void setContinueLoc(SourceLocation L) { ContinueLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return ContinueLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return ContinueLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ContinueStmtClass; } // Iterators child_range children() { return child_range(); } }; /// BreakStmt - This represents a break. /// class BreakStmt : public Stmt { SourceLocation BreakLoc; public: BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass), BreakLoc(BL) {} /// \brief Build an empty break statement. explicit BreakStmt(EmptyShell Empty) : Stmt(BreakStmtClass, Empty) { } SourceLocation getBreakLoc() const { return BreakLoc; } void setBreakLoc(SourceLocation L) { BreakLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return BreakLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return BreakLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == BreakStmtClass; } // Iterators child_range children() { return child_range(); } }; /// ReturnStmt - This represents a return, optionally of an expression: /// return; /// return 4; /// /// Note that GCC allows return with no argument in a function declared to /// return a value, and it allows returning a value in functions declared to /// return void. We explicitly model this in the AST, which means you can't /// depend on the return type of the function and the presence of an argument. /// class ReturnStmt : public Stmt { Stmt *RetExpr; SourceLocation RetLoc; const VarDecl *NRVOCandidate; public: ReturnStmt(SourceLocation RL) : Stmt(ReturnStmtClass), RetExpr(nullptr), RetLoc(RL), NRVOCandidate(nullptr) {} ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate) : Stmt(ReturnStmtClass), RetExpr((Stmt*) E), RetLoc(RL), NRVOCandidate(NRVOCandidate) {} /// \brief Build an empty return expression. explicit ReturnStmt(EmptyShell Empty) : Stmt(ReturnStmtClass, Empty) { } const Expr *getRetValue() const; Expr *getRetValue(); void setRetValue(Expr *E) { RetExpr = reinterpret_cast<Stmt*>(E); } SourceLocation getReturnLoc() const { return RetLoc; } void setReturnLoc(SourceLocation L) { RetLoc = L; } /// \brief Retrieve the variable that might be used for the named return /// value optimization. /// /// The optimization itself can only be performed if the variable is /// also marked as an NRVO object. const VarDecl *getNRVOCandidate() const { return NRVOCandidate; } void setNRVOCandidate(const VarDecl *Var) { NRVOCandidate = Var; } SourceLocation getLocStart() const LLVM_READONLY { return RetLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RetExpr ? RetExpr->getLocEnd() : RetLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ReturnStmtClass; } // Iterators child_range children() { if (RetExpr) return child_range(&RetExpr, &RetExpr+1); return child_range(); } }; /// AsmStmt is the base class for GCCAsmStmt and MSAsmStmt. /// class AsmStmt : public Stmt { protected: SourceLocation AsmLoc; /// \brief True if the assembly statement does not have any input or output /// operands. bool IsSimple; /// \brief If true, treat this inline assembly as having side effects. /// This assembly statement should not be optimized, deleted or moved. bool IsVolatile; unsigned NumOutputs; unsigned NumInputs; unsigned NumClobbers; Stmt **Exprs; AsmStmt(StmtClass SC, SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, unsigned numclobbers) : Stmt (SC), AsmLoc(asmloc), IsSimple(issimple), IsVolatile(isvolatile), NumOutputs(numoutputs), NumInputs(numinputs), NumClobbers(numclobbers) { } friend class ASTStmtReader; public: /// \brief Build an empty inline-assembly statement. explicit AsmStmt(StmtClass SC, EmptyShell Empty) : Stmt(SC, Empty), Exprs(nullptr) { } SourceLocation getAsmLoc() const { return AsmLoc; } void setAsmLoc(SourceLocation L) { AsmLoc = L; } bool isSimple() const { return IsSimple; } void setSimple(bool V) { IsSimple = V; } bool isVolatile() const { return IsVolatile; } void setVolatile(bool V) { IsVolatile = V; } SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } //===--- Asm String Analysis ---===// /// Assemble final IR asm string. std::string generateAsmString(const ASTContext &C) const; //===--- Output operands ---===// unsigned getNumOutputs() const { return NumOutputs; } /// getOutputConstraint - Return the constraint string for the specified /// output operand. All output constraints are known to be non-empty (either /// '=' or '+'). StringRef getOutputConstraint(unsigned i) const; /// isOutputPlusConstraint - Return true if the specified output constraint /// is a "+" constraint (which is both an input and an output) or false if it /// is an "=" constraint (just an output). bool isOutputPlusConstraint(unsigned i) const { return getOutputConstraint(i)[0] == '+'; } const Expr *getOutputExpr(unsigned i) const; /// getNumPlusOperands - Return the number of output operands that have a "+" /// constraint. unsigned getNumPlusOperands() const; //===--- Input operands ---===// unsigned getNumInputs() const { return NumInputs; } /// getInputConstraint - Return the specified input constraint. Unlike output /// constraints, these can be empty. StringRef getInputConstraint(unsigned i) const; const Expr *getInputExpr(unsigned i) const; //===--- Other ---===// unsigned getNumClobbers() const { return NumClobbers; } StringRef getClobber(unsigned i) const; static bool classof(const Stmt *T) { return T->getStmtClass() == GCCAsmStmtClass || T->getStmtClass() == MSAsmStmtClass; } // Input expr iterators. typedef ExprIterator inputs_iterator; typedef ConstExprIterator const_inputs_iterator; typedef llvm::iterator_range<inputs_iterator> inputs_range; typedef llvm::iterator_range<const_inputs_iterator> inputs_const_range; inputs_iterator begin_inputs() { return &Exprs[0] + NumOutputs; } inputs_iterator end_inputs() { return &Exprs[0] + NumOutputs + NumInputs; } inputs_range inputs() { return inputs_range(begin_inputs(), end_inputs()); } const_inputs_iterator begin_inputs() const { return &Exprs[0] + NumOutputs; } const_inputs_iterator end_inputs() const { return &Exprs[0] + NumOutputs + NumInputs; } inputs_const_range inputs() const { return inputs_const_range(begin_inputs(), end_inputs()); } // Output expr iterators. typedef ExprIterator outputs_iterator; typedef ConstExprIterator const_outputs_iterator; typedef llvm::iterator_range<outputs_iterator> outputs_range; typedef llvm::iterator_range<const_outputs_iterator> outputs_const_range; outputs_iterator begin_outputs() { return &Exprs[0]; } outputs_iterator end_outputs() { return &Exprs[0] + NumOutputs; } outputs_range outputs() { return outputs_range(begin_outputs(), end_outputs()); } const_outputs_iterator begin_outputs() const { return &Exprs[0]; } const_outputs_iterator end_outputs() const { return &Exprs[0] + NumOutputs; } outputs_const_range outputs() const { return outputs_const_range(begin_outputs(), end_outputs()); } child_range children() { return child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs); } }; /// This represents a GCC inline-assembly statement extension. /// class GCCAsmStmt : public AsmStmt { SourceLocation RParenLoc; StringLiteral *AsmStr; // FIXME: If we wanted to, we could allocate all of these in one big array. StringLiteral **Constraints; StringLiteral **Clobbers; IdentifierInfo **Names; friend class ASTStmtReader; public: GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, IdentifierInfo **names, StringLiteral **constraints, Expr **exprs, StringLiteral *asmstr, unsigned numclobbers, StringLiteral **clobbers, SourceLocation rparenloc); /// \brief Build an empty inline-assembly statement. explicit GCCAsmStmt(EmptyShell Empty) : AsmStmt(GCCAsmStmtClass, Empty), Constraints(nullptr), Clobbers(nullptr), Names(nullptr) { } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } //===--- Asm String Analysis ---===// const StringLiteral *getAsmString() const { return AsmStr; } StringLiteral *getAsmString() { return AsmStr; } void setAsmString(StringLiteral *E) { AsmStr = E; } /// AsmStringPiece - this is part of a decomposed asm string specification /// (for use with the AnalyzeAsmString function below). An asm string is /// considered to be a concatenation of these parts. class AsmStringPiece { public: enum Kind { String, // String in .ll asm string form, "$" -> "$$" and "%%" -> "%". Operand // Operand reference, with optional modifier %c4. }; private: Kind MyKind; std::string Str; unsigned OperandNo; // Source range for operand references. CharSourceRange Range; public: AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {} AsmStringPiece(unsigned OpNo, const std::string &S, SourceLocation Begin, SourceLocation End) : MyKind(Operand), Str(S), OperandNo(OpNo), Range(CharSourceRange::getCharRange(Begin, End)) { } bool isString() const { return MyKind == String; } bool isOperand() const { return MyKind == Operand; } const std::string &getString() const { return Str; } unsigned getOperandNo() const { assert(isOperand()); return OperandNo; } CharSourceRange getRange() const { assert(isOperand() && "Range is currently used only for Operands."); return Range; } /// getModifier - Get the modifier for this operand, if present. This /// returns '\0' if there was no modifier. char getModifier() const; }; /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing /// it into pieces. If the asm string is erroneous, emit errors and return /// true, otherwise return false. This handles canonicalization and /// translation of strings from GCC syntax to LLVM IR syntax, and handles //// flattening of named references like %[foo] to Operand AsmStringPiece's. unsigned AnalyzeAsmString(SmallVectorImpl<AsmStringPiece> &Pieces, const ASTContext &C, unsigned &DiagOffs) const; /// Assemble final IR asm string. std::string generateAsmString(const ASTContext &C) const; //===--- Output operands ---===// IdentifierInfo *getOutputIdentifier(unsigned i) const { return Names[i]; } StringRef getOutputName(unsigned i) const { if (IdentifierInfo *II = getOutputIdentifier(i)) return II->getName(); return StringRef(); } StringRef getOutputConstraint(unsigned i) const; const StringLiteral *getOutputConstraintLiteral(unsigned i) const { return Constraints[i]; } StringLiteral *getOutputConstraintLiteral(unsigned i) { return Constraints[i]; } Expr *getOutputExpr(unsigned i); const Expr *getOutputExpr(unsigned i) const { return const_cast<GCCAsmStmt*>(this)->getOutputExpr(i); } //===--- Input operands ---===// IdentifierInfo *getInputIdentifier(unsigned i) const { return Names[i + NumOutputs]; } StringRef getInputName(unsigned i) const { if (IdentifierInfo *II = getInputIdentifier(i)) return II->getName(); return StringRef(); } StringRef getInputConstraint(unsigned i) const; const StringLiteral *getInputConstraintLiteral(unsigned i) const { return Constraints[i + NumOutputs]; } StringLiteral *getInputConstraintLiteral(unsigned i) { return Constraints[i + NumOutputs]; } Expr *getInputExpr(unsigned i); void setInputExpr(unsigned i, Expr *E); const Expr *getInputExpr(unsigned i) const { return const_cast<GCCAsmStmt*>(this)->getInputExpr(i); } private: void setOutputsAndInputsAndClobbers(const ASTContext &C, IdentifierInfo **Names, StringLiteral **Constraints, Stmt **Exprs, unsigned NumOutputs, unsigned NumInputs, StringLiteral **Clobbers, unsigned NumClobbers); public: //===--- Other ---===// /// getNamedOperand - Given a symbolic operand reference like %[foo], /// translate this into a numeric value needed to reference the same operand. /// This returns -1 if the operand name is invalid. int getNamedOperand(StringRef SymbolicName) const; StringRef getClobber(unsigned i) const; StringLiteral *getClobberStringLiteral(unsigned i) { return Clobbers[i]; } const StringLiteral *getClobberStringLiteral(unsigned i) const { return Clobbers[i]; } SourceLocation getLocStart() const LLVM_READONLY { return AsmLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == GCCAsmStmtClass; } }; /// This represents a Microsoft inline-assembly statement extension. /// class MSAsmStmt : public AsmStmt { SourceLocation LBraceLoc, EndLoc; StringRef AsmStr; unsigned NumAsmToks; Token *AsmToks; StringRef *Constraints; StringRef *Clobbers; friend class ASTStmtReader; public: MSAsmStmt(const ASTContext &C, SourceLocation asmloc, SourceLocation lbraceloc, bool issimple, bool isvolatile, ArrayRef<Token> asmtoks, unsigned numoutputs, unsigned numinputs, ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs, StringRef asmstr, ArrayRef<StringRef> clobbers, SourceLocation endloc); /// \brief Build an empty MS-style inline-assembly statement. explicit MSAsmStmt(EmptyShell Empty) : AsmStmt(MSAsmStmtClass, Empty), NumAsmToks(0), AsmToks(nullptr), Constraints(nullptr), Clobbers(nullptr) { } SourceLocation getLBraceLoc() const { return LBraceLoc; } void setLBraceLoc(SourceLocation L) { LBraceLoc = L; } SourceLocation getEndLoc() const { return EndLoc; } void setEndLoc(SourceLocation L) { EndLoc = L; } bool hasBraces() const { return LBraceLoc.isValid(); } unsigned getNumAsmToks() { return NumAsmToks; } Token *getAsmToks() { return AsmToks; } //===--- Asm String Analysis ---===// StringRef getAsmString() const { return AsmStr; } /// Assemble final IR asm string. std::string generateAsmString(const ASTContext &C) const; //===--- Output operands ---===// StringRef getOutputConstraint(unsigned i) const { assert(i < NumOutputs); return Constraints[i]; } Expr *getOutputExpr(unsigned i); const Expr *getOutputExpr(unsigned i) const { return const_cast<MSAsmStmt*>(this)->getOutputExpr(i); } //===--- Input operands ---===// StringRef getInputConstraint(unsigned i) const { assert(i < NumInputs); return Constraints[i + NumOutputs]; } Expr *getInputExpr(unsigned i); void setInputExpr(unsigned i, Expr *E); const Expr *getInputExpr(unsigned i) const { return const_cast<MSAsmStmt*>(this)->getInputExpr(i); } //===--- Other ---===// ArrayRef<StringRef> getAllConstraints() const { return llvm::makeArrayRef(Constraints, NumInputs + NumOutputs); } ArrayRef<StringRef> getClobbers() const { return llvm::makeArrayRef(Clobbers, NumClobbers); } ArrayRef<Expr*> getAllExprs() const { return llvm::makeArrayRef(reinterpret_cast<Expr**>(Exprs), NumInputs + NumOutputs); } StringRef getClobber(unsigned i) const { return getClobbers()[i]; } private: void initialize(const ASTContext &C, StringRef AsmString, ArrayRef<Token> AsmToks, ArrayRef<StringRef> Constraints, ArrayRef<Expr*> Exprs, ArrayRef<StringRef> Clobbers); public: SourceLocation getLocStart() const LLVM_READONLY { return AsmLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return EndLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == MSAsmStmtClass; } child_range children() { return child_range(&Exprs[0], &Exprs[NumInputs + NumOutputs]); } }; class SEHExceptStmt : public Stmt { SourceLocation Loc; Stmt *Children[2]; enum { FILTER_EXPR, BLOCK }; SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); friend class ASTReader; friend class ASTStmtReader; explicit SEHExceptStmt(EmptyShell E) : Stmt(SEHExceptStmtClass, E) { } public: static SEHExceptStmt* Create(const ASTContext &C, SourceLocation ExceptLoc, Expr *FilterExpr, Stmt *Block); SourceLocation getLocStart() const LLVM_READONLY { return getExceptLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); } SourceLocation getExceptLoc() const { return Loc; } SourceLocation getEndLoc() const { return getBlock()->getLocEnd(); } Expr *getFilterExpr() const { return reinterpret_cast<Expr*>(Children[FILTER_EXPR]); } CompoundStmt *getBlock() const { return cast<CompoundStmt>(Children[BLOCK]); } child_range children() { return child_range(Children,Children+2); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHExceptStmtClass; } }; class SEHFinallyStmt : public Stmt { SourceLocation Loc; Stmt *Block; SEHFinallyStmt(SourceLocation Loc, Stmt *Block); friend class ASTReader; friend class ASTStmtReader; explicit SEHFinallyStmt(EmptyShell E) : Stmt(SEHFinallyStmtClass, E) { } public: static SEHFinallyStmt* Create(const ASTContext &C, SourceLocation FinallyLoc, Stmt *Block); SourceLocation getLocStart() const LLVM_READONLY { return getFinallyLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); } SourceLocation getFinallyLoc() const { return Loc; } SourceLocation getEndLoc() const { return Block->getLocEnd(); } CompoundStmt *getBlock() const { return cast<CompoundStmt>(Block); } child_range children() { return child_range(&Block,&Block+1); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHFinallyStmtClass; } }; class SEHTryStmt : public Stmt { bool IsCXXTry; SourceLocation TryLoc; Stmt *Children[2]; enum { TRY = 0, HANDLER = 1 }; SEHTryStmt(bool isCXXTry, // true if 'try' otherwise '__try' SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); friend class ASTReader; friend class ASTStmtReader; explicit SEHTryStmt(EmptyShell E) : Stmt(SEHTryStmtClass, E) { } public: static SEHTryStmt* Create(const ASTContext &C, bool isCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); SourceLocation getLocStart() const LLVM_READONLY { return getTryLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); } SourceLocation getTryLoc() const { return TryLoc; } SourceLocation getEndLoc() const { return Children[HANDLER]->getLocEnd(); } bool getIsCXXTry() const { return IsCXXTry; } CompoundStmt* getTryBlock() const { return cast<CompoundStmt>(Children[TRY]); } Stmt *getHandler() const { return Children[HANDLER]; } /// Returns 0 if not defined SEHExceptStmt *getExceptHandler() const; SEHFinallyStmt *getFinallyHandler() const; child_range children() { return child_range(Children,Children+2); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHTryStmtClass; } }; /// Represents a __leave statement. /// class SEHLeaveStmt : public Stmt { SourceLocation LeaveLoc; public: explicit SEHLeaveStmt(SourceLocation LL) : Stmt(SEHLeaveStmtClass), LeaveLoc(LL) {} /// \brief Build an empty __leave statement. explicit SEHLeaveStmt(EmptyShell Empty) : Stmt(SEHLeaveStmtClass, Empty) { } SourceLocation getLeaveLoc() const { return LeaveLoc; } void setLeaveLoc(SourceLocation L) { LeaveLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return LeaveLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return LeaveLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHLeaveStmtClass; } // Iterators child_range children() { return child_range(); } }; /// \brief This captures a statement into a function. For example, the following /// pragma annotated compound statement can be represented as a CapturedStmt, /// and this compound statement is the body of an anonymous outlined function. /// @code /// #pragma omp parallel /// { /// compute(); /// } /// @endcode class CapturedStmt : public Stmt { public: /// \brief The different capture forms: by 'this', by reference, capture for /// variable-length array type etc. enum VariableCaptureKind { VCK_This, VCK_ByRef, VCK_VLAType, }; /// \brief Describes the capture of either a variable, or 'this', or /// variable-length array type. class Capture { llvm::PointerIntPair<VarDecl *, 2, VariableCaptureKind> VarAndKind; SourceLocation Loc; public: /// \brief Create a new capture. /// /// \param Loc The source location associated with this capture. /// /// \param Kind The kind of capture (this, ByRef, ...). /// /// \param Var The variable being captured, or null if capturing this. /// Capture(SourceLocation Loc, VariableCaptureKind Kind, VarDecl *Var = nullptr) : VarAndKind(Var, Kind), Loc(Loc) { switch (Kind) { case VCK_This: assert(!Var && "'this' capture cannot have a variable!"); break; case VCK_ByRef: assert(Var && "capturing by reference must have a variable!"); break; case VCK_VLAType: assert(!Var && "Variable-length array type capture cannot have a variable!"); break; } } /// \brief Determine the kind of capture. VariableCaptureKind getCaptureKind() const { return VarAndKind.getInt(); } /// \brief Retrieve the source location at which the variable or 'this' was /// first used. SourceLocation getLocation() const { return Loc; } /// \brief Determine whether this capture handles the C++ 'this' pointer. bool capturesThis() const { return getCaptureKind() == VCK_This; } /// \brief Determine whether this capture handles a variable. bool capturesVariable() const { return getCaptureKind() == VCK_ByRef; } /// \brief Determine whether this capture handles a variable-length array /// type. bool capturesVariableArrayType() const { return getCaptureKind() == VCK_VLAType; } /// \brief Retrieve the declaration of the variable being captured. /// /// This operation is only valid if this capture captures a variable. VarDecl *getCapturedVar() const { assert(capturesVariable() && "No variable available for 'this' or VAT capture"); return VarAndKind.getPointer(); } friend class ASTStmtReader; }; private: /// \brief The number of variable captured, including 'this'. unsigned NumCaptures; /// \brief The pointer part is the implicit the outlined function and the /// int part is the captured region kind, 'CR_Default' etc. llvm::PointerIntPair<CapturedDecl *, 1, CapturedRegionKind> CapDeclAndKind; /// \brief The record for captured variables, a RecordDecl or CXXRecordDecl. RecordDecl *TheRecordDecl; /// \brief Construct a captured statement. CapturedStmt(Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures, ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD); /// \brief Construct an empty captured statement. CapturedStmt(EmptyShell Empty, unsigned NumCaptures); Stmt **getStoredStmts() const { return reinterpret_cast<Stmt **>(const_cast<CapturedStmt *>(this) + 1); } Capture *getStoredCaptures() const; void setCapturedStmt(Stmt *S) { getStoredStmts()[NumCaptures] = S; } public: static CapturedStmt *Create(const ASTContext &Context, Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures, ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD); static CapturedStmt *CreateDeserialized(const ASTContext &Context, unsigned NumCaptures); /// \brief Retrieve the statement being captured. Stmt *getCapturedStmt() { return getStoredStmts()[NumCaptures]; } const Stmt *getCapturedStmt() const { return const_cast<CapturedStmt *>(this)->getCapturedStmt(); } /// \brief Retrieve the outlined function declaration. CapturedDecl *getCapturedDecl() { return CapDeclAndKind.getPointer(); } const CapturedDecl *getCapturedDecl() const { return const_cast<CapturedStmt *>(this)->getCapturedDecl(); } /// \brief Set the outlined function declaration. void setCapturedDecl(CapturedDecl *D) { assert(D && "null CapturedDecl"); CapDeclAndKind.setPointer(D); } /// \brief Retrieve the captured region kind. CapturedRegionKind getCapturedRegionKind() const { return CapDeclAndKind.getInt(); } /// \brief Set the captured region kind. void setCapturedRegionKind(CapturedRegionKind Kind) { CapDeclAndKind.setInt(Kind); } /// \brief Retrieve the record declaration for captured variables. const RecordDecl *getCapturedRecordDecl() const { return TheRecordDecl; } /// \brief Set the record declaration for captured variables. void setCapturedRecordDecl(RecordDecl *D) { assert(D && "null RecordDecl"); TheRecordDecl = D; } /// \brief True if this variable has been captured. bool capturesVariable(const VarDecl *Var) const; /// \brief An iterator that walks over the captures. typedef Capture *capture_iterator; typedef const Capture *const_capture_iterator; typedef llvm::iterator_range<capture_iterator> capture_range; typedef llvm::iterator_range<const_capture_iterator> capture_const_range; capture_range captures() { return capture_range(capture_begin(), capture_end()); } capture_const_range captures() const { return capture_const_range(capture_begin(), capture_end()); } /// \brief Retrieve an iterator pointing to the first capture. capture_iterator capture_begin() { return getStoredCaptures(); } const_capture_iterator capture_begin() const { return getStoredCaptures(); } /// \brief Retrieve an iterator pointing past the end of the sequence of /// captures. capture_iterator capture_end() const { return getStoredCaptures() + NumCaptures; } /// \brief Retrieve the number of captures, including 'this'. unsigned capture_size() const { return NumCaptures; } /// \brief Iterator that walks over the capture initialization arguments. typedef Expr **capture_init_iterator; typedef llvm::iterator_range<capture_init_iterator> capture_init_range; capture_init_range capture_inits() const { return capture_init_range(capture_init_begin(), capture_init_end()); } /// \brief Retrieve the first initialization argument. capture_init_iterator capture_init_begin() const { return reinterpret_cast<Expr **>(getStoredStmts()); } /// \brief Retrieve the iterator pointing one past the last initialization /// argument. capture_init_iterator capture_init_end() const { return capture_init_begin() + NumCaptures; } SourceLocation getLocStart() const LLVM_READONLY { return getCapturedStmt()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return getCapturedStmt()->getLocEnd(); } SourceRange getSourceRange() const LLVM_READONLY { return getCapturedStmt()->getSourceRange(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CapturedStmtClass; } child_range children(); friend class ASTStmtReader; }; } // end namespace clang #endif
DRB050-functionparameter-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> /* Arrays passed as function parameters */ void foo1(double o1[], double c[], int len) { int i; long long int AI1[6]; AI1[0] = len + -1; AI1[1] = 8 * AI1[0]; AI1[2] = AI1[1] + 8; AI1[3] = AI1[2] / 8; AI1[4] = (AI1[3] > 0); AI1[5] = (AI1[4] ? AI1[3] : 0); char RST_AI1 = 0; RST_AI1 |= !(((void*) (c + 0) > (void*) (o1 + AI1[5])) || ((void*) (o1 + 0) > (void*) (c + AI1[5]))); #pragma omp target data map(to: c[0:AI1[5]]) map(tofrom: o1[0:AI1[5]]) if(!RST_AI1) { #pragma omp target parallel for for (i = 0; i < len; ++i) { double volnew_o8 = 0.5 * c[i]; o1[i] = volnew_o8; } } } int main() { double o1[101]; double c[101]; int i; int len = 100; char RST_AI1 = 0; #pragma omp target data map(tofrom: c[0:101],o1[0:101]) if(!RST_AI1) { #pragma omp target parallel for for (i = 0; i < len; ++i) { c[i] = i + 1.01; o1[i] = i + 1.01; } } foo1(&o1[1], &o1[0], 100); for (i = 0; i < len; ++i) { printf("%lf\n", o1[i]); } return 0; }
GB_concat_sparse.c
//------------------------------------------------------------------------------ // GB_concat_sparse: concatenate an array of matrices into a sparse matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #define GB_FREE_WORK \ if (S != NULL) \ { \ for (int64_t k = 0 ; k < m * n ; k++) \ { \ GB_Matrix_free (&(S [k])) ; \ } \ } \ GB_FREE_WERK (&S, S_size) ; \ GB_FREE_WERK (&Work, Work_size) ; \ GB_WERK_POP (A_ek_slicing, int64_t) ; #define GB_FREE_ALL \ { \ GB_FREE_WORK ; \ GB_phbix_free (C) ; \ } #include "GB_concat.h" GrB_Info GB_concat_sparse // concatenate into a sparse matrix ( GrB_Matrix C, // input/output matrix for results const bool C_iso, // if true, construct C as iso const GB_void *cscalar, // iso value of C, if C is io const int64_t cnz, // # of entries in C const GrB_Matrix *Tiles, // 2D row-major array of size m-by-n, const GrB_Index m, const GrB_Index n, const int64_t *restrict Tile_rows, // size m+1 const int64_t *restrict Tile_cols, // size n+1 GB_Context Context ) { //-------------------------------------------------------------------------- // allocate C as a sparse matrix //-------------------------------------------------------------------------- GrB_Info info ; GrB_Matrix A = NULL ; ASSERT_MATRIX_OK (C, "C input to concat sparse", GB0) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; int64_t *Work = NULL ; size_t Work_size = 0 ; GrB_Matrix *S = NULL ; size_t S_size = 0 ; GrB_Type ctype = C->type ; int64_t cvlen = C->vlen ; int64_t cvdim = C->vdim ; bool csc = C->is_csc ; size_t csize = ctype->size ; GB_Type_code ccode = ctype->code ; float hyper_switch = C->hyper_switch ; float bitmap_switch = C->bitmap_switch ; int sparsity_control = C->sparsity_control ; bool static_header = C->static_header ; GB_phbix_free (C) ; // set C->iso = C_iso OK GB_OK (GB_new_bix (&C, static_header, // prior static or dynamic header ctype, cvlen, cvdim, GB_Ap_malloc, csc, GxB_SPARSE, false, hyper_switch, cvdim, cnz, true, C_iso, Context)) ; C->bitmap_switch = bitmap_switch ; C->sparsity_control = sparsity_control ; int64_t *restrict Cp = C->p ; int64_t *restrict Ci = C->i ; GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; if (C_iso) { memcpy (C->x, cscalar, csize) ; } //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- int64_t nouter = csc ? n : m ; int64_t ninner = csc ? m : n ; Work = GB_CALLOC_WERK (ninner * cvdim, int64_t, &Work_size) ; S = GB_CALLOC_WERK (m * n, GrB_Matrix, &S_size) ; if (S == NULL || Work == NULL) { // out of memory GB_FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } //-------------------------------------------------------------------------- // count entries in each vector of each tile //-------------------------------------------------------------------------- for (int64_t outer = 0 ; outer < nouter ; outer++) { for (int64_t inner = 0 ; inner < ninner ; inner++) { //------------------------------------------------------------------ // get the tile A; transpose and typecast, if needed //------------------------------------------------------------------ A = csc ? GB_TILE (Tiles, inner, outer) : GB_TILE (Tiles, outer, inner) ; GrB_Matrix T = NULL ; ASSERT_MATRIX_OK (A, "A tile for concat sparse", GB0) ; if (csc != A->is_csc) { // T = (ctype) A', not in-place, using a dynamic header GB_OK (GB_new (&T, false, // auto sparsity, new header A->type, A->vdim, A->vlen, GB_Ap_null, csc, GxB_AUTO_SPARSITY, -1, 1, Context)) ; // save T in array S if (csc) { GB_TILE (S, inner, outer) = T ; } else { GB_TILE (S, outer, inner) = T ; } GB_OK (GB_transpose_cast (T, ctype, csc, A, false, Context)) ; A = T ; GB_MATRIX_WAIT (A) ; ASSERT_MATRIX_OK (A, "T=A' for concat sparse", GB0) ; } ASSERT (C->is_csc == A->is_csc) ; ASSERT (!GB_ANY_PENDING_WORK (A)) ; //------------------------------------------------------------------ // ensure the tile is not bitmap //------------------------------------------------------------------ if (GB_IS_BITMAP (A)) { if (T == NULL) { // copy A into T // set T->iso = A->iso OK: no burble needed GB_OK (GB_dup_worker (&T, A->iso, A, true, NULL, Context)) ; // save T in array S if (csc) { GB_TILE (S, inner, outer) = T ; } else { GB_TILE (S, outer, inner) = T ; } ASSERT_MATRIX_OK (T, "T=dup(A) for concat sparse", GB0) ; } // convert T from bitmap to sparse GB_OK (GB_convert_bitmap_to_sparse (T, Context)) ; ASSERT_MATRIX_OK (T, "T bitmap to sparse, concat sparse", GB0) ; A = T ; } ASSERT (!GB_IS_BITMAP (A)) ; //------------------------------------------------------------------ // log the # of entries in each vector of the tile A //------------------------------------------------------------------ const int64_t anvec = A->nvec ; const int64_t avlen = A->vlen ; int64_t cvstart = csc ? Tile_cols [outer] : Tile_rows [outer] ; int64_t *restrict W = Work + inner * cvdim + cvstart ; int nth = GB_nthreads (anvec, chunk, nthreads_max) ; if (GB_IS_FULL (A)) { // A is full int64_t j ; #pragma omp parallel for num_threads(nth) schedule(static) for (j = 0 ; j < anvec ; j++) { // W [j] = # of entries in A(:,j), which is just avlen W [j] = avlen ; } } else { // A is sparse or hyper int64_t k ; int64_t *restrict Ah = A->h ; int64_t *restrict Ap = A->p ; #pragma omp parallel for num_threads(nth) schedule(static) for (k = 0 ; k < anvec ; k++) { // W [j] = # of entries in A(:,j), the kth column of A int64_t j = GBH (Ah, k) ; W [j] = Ap [k+1] - Ap [k] ; } } } } //-------------------------------------------------------------------------- // cumulative sum of entries in each tile //-------------------------------------------------------------------------- int nth = GB_nthreads (ninner*cvdim, chunk, nthreads_max) ; int64_t k ; #pragma omp parallel for num_threads(nth) schedule(static) for (k = 0 ; k < cvdim ; k++) { int64_t s = 0 ; for (int64_t inner = 0 ; inner < ninner ; inner++) { int64_t p = inner * cvdim + k ; int64_t c = Work [p] ; Work [p] = s ; s += c ; } // total number of entries in C(:,k) Cp [k] = s ; } GB_cumsum (Cp, cvdim, &(C->nvec_nonempty), nthreads_max, Context) ; #pragma omp parallel for num_threads(nth) schedule(static) for (k = 0 ; k < cvdim ; k++) { int64_t pC = Cp [k] ; for (int64_t inner = 0 ; inner < ninner ; inner++) { int64_t p = inner * cvdim + k ; Work [p] += pC ; } } //-------------------------------------------------------------------------- // concatenate all matrices into C //-------------------------------------------------------------------------- for (int64_t outer = 0 ; outer < nouter ; outer++) { for (int64_t inner = 0 ; inner < ninner ; inner++) { //------------------------------------------------------------------ // get the tile A, either the temporary matrix T or the original A //------------------------------------------------------------------ A = csc ? GB_TILE (S, inner, outer) : GB_TILE (S, outer, inner) ; if (A == NULL) { A = csc ? GB_TILE (Tiles, inner, outer) : GB_TILE (Tiles, outer, inner) ; } ASSERT_MATRIX_OK (A, "A tile again, concat sparse", GB0) ; ASSERT (!GB_IS_BITMAP (A)) ; ASSERT (C->is_csc == A->is_csc) ; ASSERT (!GB_ANY_PENDING_WORK (A)) ; GB_Type_code acode = A->type->code ; //------------------------------------------------------------------ // determine where to place the tile in C //------------------------------------------------------------------ // The tile A appears in vectors cvstart:cvend-1 of C, and indices // cistart:ciend-1. int64_t cvstart, cvend, cistart, ciend ; if (csc) { // C and A are held by column // Tiles is row-major and accessed in column order cvstart = Tile_cols [outer] ; cvend = Tile_cols [outer+1] ; cistart = Tile_rows [inner] ; ciend = Tile_rows [inner+1] ; } else { // C and A are held by row // Tiles is row-major and accessed in row order cvstart = Tile_rows [outer] ; cvend = Tile_rows [outer+1] ; cistart = Tile_cols [inner] ; ciend = Tile_cols [inner+1] ; } // get the workspace pointer array W for this tile int64_t *restrict W = Work + inner * cvdim + cvstart ; //------------------------------------------------------------------ // slice the tile //------------------------------------------------------------------ int64_t avdim = cvend - cvstart ; int64_t avlen = ciend - cistart ; ASSERT (avdim == A->vdim) ; ASSERT (avlen == A->vlen) ; int A_nthreads, A_ntasks ; const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ai = A->i ; const bool A_iso = A->iso ; GB_SLICE_MATRIX (A, 1, chunk) ; //------------------------------------------------------------------ // copy the tile A into C //------------------------------------------------------------------ bool done = false ; if (C_iso) { //-------------------------------------------------------------- // C and A are iso //-------------------------------------------------------------- #define GB_ISO_CONCAT #define GB_COPY(pC,pA,A_iso) ; #include "GB_concat_sparse_template.c" } else { #ifndef GBCOMPACT if (ccode == acode) { // no typecasting needed switch (csize) { #undef GB_COPY #define GB_COPY(pC,pA,A_iso) \ Cx [pC] = GBX (Ax, pA, A_iso) ; case GB_1BYTE : // uint8, int8, bool, or 1-byte user #define GB_CTYPE uint8_t #include "GB_concat_sparse_template.c" break ; case GB_2BYTE : // uint16, int16, or 2-byte user #define GB_CTYPE uint16_t #include "GB_concat_sparse_template.c" break ; case GB_4BYTE : // uint32, int32, float, or 4-byte user #define GB_CTYPE uint32_t #include "GB_concat_sparse_template.c" break ; case GB_8BYTE : // uint64, int64, double, float complex, // or 8-byte user defined #define GB_CTYPE uint64_t #include "GB_concat_sparse_template.c" break ; case GB_16BYTE : // double complex or 16-byte user #define GB_CTYPE GB_blob16 // #define GB_CTYPE uint64_t // #undef GB_COPY // #define GB_COPY(pC,pA,A_iso) \ // Cx [2*pC ] = Ax [A_iso ? 0 : (2*pA)] ; \ // Cx [2*pC+1] = Ax [A_iso ? 1 : (2*pA+1)] ; #include "GB_concat_sparse_template.c" break ; default:; } } #endif } if (!done) { // with typecasting or user-defined types GB_cast_function cast_A_to_C = GB_cast_factory (ccode, acode) ; size_t asize = A->type->size ; #define GB_CTYPE GB_void #undef GB_COPY #define GB_COPY(pC,pA,A_iso) \ cast_A_to_C (Cx + (pC)*csize, \ Ax + (A_iso ? 0:(pA)*asize), asize) ; #include "GB_concat_sparse_template.c" } GB_WERK_POP (A_ek_slicing, int64_t) ; } } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- GB_FREE_WORK ; C->magic = GB_MAGIC ; ASSERT_MATRIX_OK (C, "C from concat sparse", GB0) ; return (GrB_SUCCESS) ; }
enhance.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE N N H H AAA N N CCCC EEEEE % % E NN N H H A A NN N C E % % EEE N N N HHHHH AAAAA N N N C EEE % % E N NN H H A A N NN C E % % EEEEE N N H H A A N N CCCC EEEEE % % % % % % MagickCore Image Enhancement Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoGammaImage() extract the 'mean' from the image and adjust the image % to try make set its gamma appropriately. % % The format of the AutoGammaImage method is: % % MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoGammaImage(Image *image, ExceptionInfo *exception) { double gamma, log_mean, mean, sans; MagickStatusType status; register ssize_t i; log_mean=log(0.5); if (image->channel_mask == DefaultChannels) { /* Apply gamma correction equally across all given channels. */ (void) GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception)); } /* Auto-gamma each channel separately. */ status=MagickTrue; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ChannelType channel_mask; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; channel_mask=SetImageChannelMask(image,(ChannelType) (1UL << i)); status=GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception); (void) SetImageChannelMask(image,channel_mask); if (status == MagickFalse) break; } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoLevelImage() adjusts the levels of a particular image channel by % scaling the minimum and maximum values to the full quantum range. % % The format of the LevelImage method is: % % MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoLevelImage(Image *image, ExceptionInfo *exception) { return(MinMaxStretchImage(image,0.0,0.0,1.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B r i g h t n e s s C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BrightnessContrastImage() changes the brightness and/or contrast of an % image. It converts the brightness and contrast parameters into slope and % intercept and calls a polynomical function to apply to the image. % % The format of the BrightnessContrastImage method is: % % MagickBooleanType BrightnessContrastImage(Image *image, % const double brightness,const double contrast,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o brightness: the brightness percent (-100 .. 100). % % o contrast: the contrast percent (-100 .. 100). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BrightnessContrastImage(Image *image, const double brightness,const double contrast,ExceptionInfo *exception) { #define BrightnessContastImageTag "BrightnessContast/Image" double alpha, coefficients[2], intercept, slope; MagickBooleanType status; /* Compute slope and intercept. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); alpha=contrast; slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0)); if (slope < 0.0) slope=0.0; intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope); coefficients[0]=slope; coefficients[1]=intercept; status=FunctionImage(image,PolynomialFunction,2,coefficients,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C L A H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CLAHEImage() is a variant of adaptive histogram equalization in which the % contrast amplification is limited, so as to reduce this problem of noise % amplification. % % Adapted from implementation by Karel Zuiderveld, karel@cv.ruu.nl in % "Graphics Gems IV", Academic Press, 1994. % % The format of the CLAHEImage method is: % % MagickBooleanType CLAHEImage(Image *image,const size_t width, % const size_t height,const size_t number_bins,const double clip_limit, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the tile divisions to use in horizontal direction. % % o height: the height of the tile divisions to use in vertical direction. % % o number_bins: number of bins for histogram ("dynamic range"). % % o clip_limit: contrast limit for localised changes in contrast. A limit % less than 1 results in standard non-contrast limited AHE. % % o exception: return any errors or warnings in this structure. % */ typedef struct _RangeInfo { unsigned short min, max; } RangeInfo; static void ClipCLAHEHistogram(const double clip_limit,const size_t number_bins, size_t *histogram) { #define NumberCLAHEGrays (65536) register ssize_t i; size_t cumulative_excess, previous_excess, step; ssize_t excess; /* Compute total number of excess pixels. */ cumulative_excess=0; for (i=0; i < (ssize_t) number_bins; i++) { excess=(ssize_t) histogram[i]-(ssize_t) clip_limit; if (excess > 0) cumulative_excess+=excess; } /* Clip histogram and redistribute excess pixels across all bins. */ step=cumulative_excess/number_bins; excess=(ssize_t) (clip_limit-step); for (i=0; i < (ssize_t) number_bins; i++) { if ((double) histogram[i] > clip_limit) histogram[i]=(size_t) clip_limit; else if ((ssize_t) histogram[i] > excess) { cumulative_excess-=histogram[i]-excess; histogram[i]=(size_t) clip_limit; } else { cumulative_excess-=step; histogram[i]+=step; } } /* Redistribute remaining excess. */ do { register size_t *p; size_t *q; previous_excess=cumulative_excess; p=histogram; q=histogram+number_bins; while ((cumulative_excess != 0) && (p < q)) { step=number_bins/cumulative_excess; if (step < 1) step=1; for (p=histogram; (p < q) && (cumulative_excess != 0); p+=step) if ((double) *p < clip_limit) { (*p)++; cumulative_excess--; } p++; } } while ((cumulative_excess != 0) && (cumulative_excess < previous_excess)); } static void GenerateCLAHEHistogram(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const size_t number_bins, const unsigned short *lut,const unsigned short *pixels,size_t *histogram) { register const unsigned short *p; register ssize_t i; /* Classify the pixels into a gray histogram. */ for (i=0; i < (ssize_t) number_bins; i++) histogram[i]=0L; p=pixels; for (i=0; i < (ssize_t) tile_info->height; i++) { const unsigned short *q; q=p+tile_info->width; while (p < q) histogram[lut[*p++]]++; q+=clahe_info->width; p=q-tile_info->width; } } static void InterpolateCLAHE(const RectangleInfo *clahe_info,const size_t *Q12, const size_t *Q22,const size_t *Q11,const size_t *Q21, const RectangleInfo *tile,const unsigned short *lut,unsigned short *pixels) { ssize_t y; unsigned short intensity; /* Bilinear interpolate four tiles to eliminate boundary artifacts. */ for (y=(ssize_t) tile->height; y > 0; y--) { register ssize_t x; for (x=(ssize_t) tile->width; x > 0; x--) { intensity=lut[*pixels]; *pixels++=(unsigned short) (PerceptibleReciprocal((double) tile->width* tile->height)*(y*((double) x*Q12[intensity]+(tile->width-x)* Q22[intensity])+(tile->height-y)*((double) x*Q11[intensity]+ (tile->width-x)*Q21[intensity]))); } pixels+=(clahe_info->width-tile->width); } } static void GenerateCLAHELut(const RangeInfo *range_info, const size_t number_bins,unsigned short *lut) { ssize_t i; unsigned short delta; /* Scale input image [intensity min,max] to [0,number_bins-1]. */ delta=(unsigned short) ((range_info->max-range_info->min)/number_bins+1); for (i=(ssize_t) range_info->min; i <= (ssize_t) range_info->max; i++) lut[i]=(unsigned short) ((i-range_info->min)/delta); } static void MapCLAHEHistogram(const RangeInfo *range_info, const size_t number_bins,const size_t number_pixels,size_t *histogram) { double scale, sum; register ssize_t i; /* Rescale histogram to range [min-intensity .. max-intensity]. */ scale=(double) (range_info->max-range_info->min)/number_pixels; sum=0.0; for (i=0; i < (ssize_t) number_bins; i++) { sum+=histogram[i]; histogram[i]=(size_t) (range_info->min+scale*sum); if (histogram[i] > range_info->max) histogram[i]=range_info->max; } } static MagickBooleanType CLAHE(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const RangeInfo *range_info, const size_t number_bins,const double clip_limit,unsigned short *pixels) { MemoryInfo *tile_cache; register unsigned short *p; size_t limit, *tiles; ssize_t y; unsigned short *lut; /* Constrast limited adapted histogram equalization. */ if (clip_limit == 1.0) return(MagickTrue); tile_cache=AcquireVirtualMemory((size_t) clahe_info->x*clahe_info->y, number_bins*sizeof(*tiles)); if (tile_cache == (MemoryInfo *) NULL) return(MagickFalse); lut=(unsigned short *) AcquireQuantumMemory(NumberCLAHEGrays,sizeof(*lut)); if (lut == (unsigned short *) NULL) { tile_cache=RelinquishVirtualMemory(tile_cache); return(MagickFalse); } tiles=(size_t *) GetVirtualMemoryBlob(tile_cache); limit=(size_t) (clip_limit*(tile_info->width*tile_info->height)/number_bins); if (limit < 1UL) limit=1UL; /* Generate greylevel mappings for each tile. */ GenerateCLAHELut(range_info,number_bins,lut); p=pixels; for (y=0; y < (ssize_t) clahe_info->y; y++) { register ssize_t x; for (x=0; x < (ssize_t) clahe_info->x; x++) { size_t *histogram; histogram=tiles+(number_bins*(y*clahe_info->x+x)); GenerateCLAHEHistogram(clahe_info,tile_info,number_bins,lut,p,histogram); ClipCLAHEHistogram((double) limit,number_bins,histogram); MapCLAHEHistogram(range_info,number_bins,tile_info->width* tile_info->height,histogram); p+=tile_info->width; } p+=clahe_info->width*(tile_info->height-1); } /* Interpolate greylevel mappings to get CLAHE image. */ p=pixels; for (y=0; y <= (ssize_t) clahe_info->y; y++) { OffsetInfo offset; RectangleInfo tile; register ssize_t x; tile.height=tile_info->height; tile.y=y-1; offset.y=tile.y+1; if (y == 0) { /* Top row. */ tile.height=tile_info->height >> 1; tile.y=0; offset.y=0; } else if (y == (ssize_t) clahe_info->y) { /* Bottom row. */ tile.height=(tile_info->height+1) >> 1; tile.y=clahe_info->y-1; offset.y=tile.y; } for (x=0; x <= (ssize_t) clahe_info->x; x++) { tile.width=tile_info->width; tile.x=x-1; offset.x=tile.x+1; if (x == 0) { /* Left column. */ tile.width=tile_info->width >> 1; tile.x=0; offset.x=0; } else if (x == (ssize_t) clahe_info->x) { /* Right column. */ tile.width=(tile_info->width+1) >> 1; tile.x=clahe_info->x-1; offset.x=tile.x; } InterpolateCLAHE(clahe_info, tiles+(number_bins*(tile.y*clahe_info->x+tile.x)), /* Q12 */ tiles+(number_bins*(tile.y*clahe_info->x+offset.x)), /* Q22 */ tiles+(number_bins*(offset.y*clahe_info->x+tile.x)), /* Q11 */ tiles+(number_bins*(offset.y*clahe_info->x+offset.x)), /* Q21 */ &tile,lut,p); p+=tile.width; } p+=clahe_info->width*(tile.height-1); } lut=(unsigned short *) RelinquishMagickMemory(lut); tile_cache=RelinquishVirtualMemory(tile_cache); return(MagickTrue); } MagickExport MagickBooleanType CLAHEImage(Image *image,const size_t width, const size_t height,const size_t number_bins,const double clip_limit, ExceptionInfo *exception) { #define CLAHEImageTag "CLAHE/Image" CacheView *image_view; ColorspaceType colorspace; MagickBooleanType status; MagickOffsetType progress; MemoryInfo *pixel_cache; RangeInfo range_info; RectangleInfo clahe_info, tile_info; size_t n; ssize_t y; unsigned short *pixels; /* Configure CLAHE parameters. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); range_info.min=0; range_info.max=NumberCLAHEGrays-1; tile_info.width=width; if (tile_info.width == 0) tile_info.width=image->columns >> 3; tile_info.height=height; if (tile_info.height == 0) tile_info.height=image->rows >> 3; tile_info.x=0; if ((image->columns % tile_info.width) != 0) tile_info.x=(ssize_t) tile_info.width-(image->columns % tile_info.width); tile_info.y=0; if ((image->rows % tile_info.height) != 0) tile_info.y=(ssize_t) tile_info.height-(image->rows % tile_info.height); clahe_info.width=image->columns+tile_info.x; clahe_info.height=image->rows+tile_info.y; clahe_info.x=(ssize_t) clahe_info.width/tile_info.width; clahe_info.y=(ssize_t) clahe_info.height/tile_info.height; pixel_cache=AcquireVirtualMemory(clahe_info.width,clahe_info.height* sizeof(*pixels)); if (pixel_cache == (MemoryInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); pixels=(unsigned short *) GetVirtualMemoryBlob(pixel_cache); colorspace=image->colorspace; if (TransformImageColorspace(image,LabColorspace,exception) == MagickFalse) { pixel_cache=RelinquishVirtualMemory(pixel_cache); return(MagickFalse); } /* Initialize CLAHE pixels. */ image_view=AcquireVirtualCacheView(image,exception); progress=0; status=MagickTrue; n=0; for (y=0; y < (ssize_t) clahe_info.height; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(tile_info.x >> 1),y- (tile_info.y >> 1),clahe_info.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) clahe_info.width; x++) { pixels[n++]=ScaleQuantumToShort(p[0]); p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); status=CLAHE(&clahe_info,&tile_info,&range_info,number_bins == 0 ? (size_t) 128 : MagickMin(number_bins,256),clip_limit,pixels); if (status == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); /* Push CLAHE pixels to CLAHE image. */ image_view=AcquireAuthenticCacheView(image,exception); n=clahe_info.width*(tile_info.y >> 1); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } n+=tile_info.x >> 1; for (x=0; x < (ssize_t) image->columns; x++) { q[0]=ScaleShortToQuantum(pixels[n++]); q+=GetPixelChannels(image); } n+=(clahe_info.width-image->columns-(tile_info.x >> 1)); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); pixel_cache=RelinquishVirtualMemory(pixel_cache); if (TransformImageColorspace(image,colorspace,exception) == MagickFalse) status=MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClutImage() replaces each color value in the given image, by using it as an % index to lookup a replacement color value in a Color Look UP Table in the % form of an image. The values are extracted along a diagonal of the CLUT % image so either a horizontal or vertial gradient image can be used. % % Typically this is used to either re-color a gray-scale image according to a % color gradient in the CLUT image, or to perform a freeform histogram % (level) adjustment according to the (typically gray-scale) gradient in the % CLUT image. % % When the 'channel' mask includes the matte/alpha transparency channel but % one image has no such channel it is assumed that that image is a simple % gray-scale image that will effect the alpha channel values, either for % gray-scale coloring (with transparent or semi-transparent colors), or % a histogram adjustment of existing alpha channel values. If both images % have matte channels, direct and normal indexing is applied, which is rarely % used. % % The format of the ClutImage method is: % % MagickBooleanType ClutImage(Image *image,Image *clut_image, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o clut_image: the color lookup table image for replacement color values. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ClutImageTag "Clut/Image" CacheView *clut_view, *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo *clut_map; register ssize_t i; ssize_t adjust, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clut_image != (Image *) NULL); assert(clut_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); if (clut_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Clut image. */ status=MagickTrue; progress=0; adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); clut_view=AcquireVirtualCacheView(clut_image,exception); for (i=0; i <= (ssize_t) MaxMap; i++) { GetPixelInfo(clut_image,clut_map+i); status=InterpolatePixelInfo(clut_image,clut_view,method, (double) i*(clut_image->columns-adjust)/MaxMap,(double) i* (clut_image->rows-adjust)/MaxMap,clut_map+i,exception); if (status == MagickFalse) break; } clut_view=DestroyCacheView(clut_view); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { PixelTrait traits; GetPixelInfoPixel(image,q,&pixel); traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.red))].red; traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.green))].green; traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.blue))].blue; traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.black))].black; traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.alpha))].alpha; SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ClutImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); if ((clut_image->alpha_trait != UndefinedPixelTrait) && ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r D e c i s i o n L i s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorDecisionListImage() accepts a lightweight Color Correction Collection % (CCC) file which solely contains one or more color corrections and applies % the correction to the image. Here is a sample CCC file: % % <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2"> % <ColorCorrection id="cc03345"> % <SOPNode> % <Slope> 0.9 1.2 0.5 </Slope> % <Offset> 0.4 -0.5 0.6 </Offset> % <Power> 1.0 0.8 1.5 </Power> % </SOPNode> % <SATNode> % <Saturation> 0.85 </Saturation> % </SATNode> % </ColorCorrection> % </ColorCorrectionCollection> % % which includes the slop, offset, and power for each of the RGB channels % as well as the saturation. % % The format of the ColorDecisionListImage method is: % % MagickBooleanType ColorDecisionListImage(Image *image, % const char *color_correction_collection,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_correction_collection: the color correction collection in XML. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ColorDecisionListImage(Image *image, const char *color_correction_collection,ExceptionInfo *exception) { #define ColorDecisionListCorrectImageTag "ColorDecisionList/Image" typedef struct _Correction { double slope, offset, power; } Correction; typedef struct _ColorCorrection { Correction red, green, blue; double saturation; } ColorCorrection; CacheView *image_view; char token[MagickPathExtent]; ColorCorrection color_correction; const char *content, *p; MagickBooleanType status; MagickOffsetType progress; PixelInfo *cdl_map; register ssize_t i; ssize_t y; XMLTreeInfo *cc, *ccc, *sat, *sop; /* Allocate and initialize cdl maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (color_correction_collection == (const char *) NULL) return(MagickFalse); ccc=NewXMLTree((const char *) color_correction_collection,exception); if (ccc == (XMLTreeInfo *) NULL) return(MagickFalse); cc=GetXMLTreeChild(ccc,"ColorCorrection"); if (cc == (XMLTreeInfo *) NULL) { ccc=DestroyXMLTree(ccc); return(MagickFalse); } color_correction.red.slope=1.0; color_correction.red.offset=0.0; color_correction.red.power=1.0; color_correction.green.slope=1.0; color_correction.green.offset=0.0; color_correction.green.power=1.0; color_correction.blue.slope=1.0; color_correction.blue.offset=0.0; color_correction.blue.power=1.0; color_correction.saturation=0.0; sop=GetXMLTreeChild(cc,"SOPNode"); if (sop != (XMLTreeInfo *) NULL) { XMLTreeInfo *offset, *power, *slope; slope=GetXMLTreeChild(sop,"Slope"); if (slope != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(slope); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.slope=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.slope=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.slope=StringToDouble(token, (char **) NULL); break; } } } } offset=GetXMLTreeChild(sop,"Offset"); if (offset != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(offset); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.offset=StringToDouble(token, (char **) NULL); break; } case 1: { color_correction.green.offset=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.offset=StringToDouble(token, (char **) NULL); break; } } } } power=GetXMLTreeChild(sop,"Power"); if (power != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(power); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.power=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.power=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.power=StringToDouble(token, (char **) NULL); break; } } } } } sat=GetXMLTreeChild(cc,"SATNode"); if (sat != (XMLTreeInfo *) NULL) { XMLTreeInfo *saturation; saturation=GetXMLTreeChild(sat,"Saturation"); if (saturation != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(saturation); p=(const char *) content; (void) GetNextToken(p,&p,MagickPathExtent,token); color_correction.saturation=StringToDouble(token,(char **) NULL); } } ccc=DestroyXMLTree(ccc); if (image->debug != MagickFalse) { (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Color Correction Collection:"); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.slope: %g",color_correction.red.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.offset: %g",color_correction.red.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.power: %g",color_correction.red.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.slope: %g",color_correction.green.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.offset: %g",color_correction.green.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.power: %g",color_correction.green.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.slope: %g",color_correction.blue.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.offset: %g",color_correction.blue.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.power: %g",color_correction.blue.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.saturation: %g",color_correction.saturation); } cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map)); if (cdl_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); for (i=0; i <= (ssize_t) MaxMap; i++) { cdl_map[i].red=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.red.slope*i/MaxMap+ color_correction.red.offset,color_correction.red.power)))); cdl_map[i].green=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.green.slope*i/MaxMap+ color_correction.green.offset,color_correction.green.power)))); cdl_map[i].blue=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.blue.slope*i/MaxMap+ color_correction.blue.offset,color_correction.blue.power)))); } if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Apply transfer function to colormap. */ double luma; luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+ 0.07217f*image->colormap[i].blue; image->colormap[i].red=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma; image->colormap[i].green=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma; image->colormap[i].blue=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma; } /* Apply transfer function to image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double luma; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+ 0.07217f*GetPixelBlue(image,q); SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q); SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q); SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag, progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastImage() enhances the intensity differences between the lighter and % darker elements of the image. Set sharpen to a MagickTrue to increase the % image contrast otherwise the contrast is reduced. % % The format of the ContrastImage method is: % % MagickBooleanType ContrastImage(Image *image, % const MagickBooleanType sharpen,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o exception: return any errors or warnings in this structure. % */ static void Contrast(const int sign,double *red,double *green,double *blue) { double brightness, hue, saturation; /* Enhance contrast: dark color become darker, light color become lighter. */ assert(red != (double *) NULL); assert(green != (double *) NULL); assert(blue != (double *) NULL); hue=0.0; saturation=0.0; brightness=0.0; ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)- brightness); if (brightness > 1.0) brightness=1.0; else if (brightness < 0.0) brightness=0.0; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } MagickExport MagickBooleanType ContrastImage(Image *image, const MagickBooleanType sharpen,ExceptionInfo *exception) { #define ContrastImageTag "Contrast/Image" CacheView *image_view; int sign; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); sign=sharpen != MagickFalse ? 1 : -1; if (image->storage_class == PseudoClass) { /* Contrast enhance colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; Contrast(sign,&red,&green,&blue); image->colormap[i].red=(MagickRealType) red; image->colormap[i].green=(MagickRealType) green; image->colormap[i].blue=(MagickRealType) blue; } } /* Contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, red; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); Contrast(sign,&red,&green,&blue); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ContrastImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastStretchImage() is a simple image enhancement technique that attempts % to improve the contrast in an image by 'stretching' the range of intensity % values it contains to span a desired range of values. It differs from the % more sophisticated histogram equalization in that it can only apply a % linear scaling function to the image pixel values. As a result the % 'enhancement' is less harsh. % % The format of the ContrastStretchImage method is: % % MagickBooleanType ContrastStretchImage(Image *image, % const char *levels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o levels: Specify the levels where the black and white points have the % range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ContrastStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag "ContrastStretch/Image" CacheView *image_view; double *black, *histogram, *stretch_map, *white; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate histogram and stretch map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); black=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*black)); white=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*white)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*stretch_map)); if ((black == (double *) NULL) || (white == (double *) NULL) || (histogram == (double *) NULL) || (stretch_map == (double *) NULL)) { if (stretch_map != (double *) NULL) stretch_map=(double *) RelinquishMagickMemory(stretch_map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (white != (double *) NULL) white=(double *) RelinquishMagickMemory(white); if (black != (double *) NULL) black=(double *) RelinquishMagickMemory(black); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; pixel=GetPixelIntensity(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { if (image->channel_mask != DefaultChannels) pixel=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(pixel))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black/white levels. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; black[i]=0.0; white[i]=MaxRange(QuantumRange); intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > black_point) break; } black[i]=(double) j; intensity=0.0; for (j=(ssize_t) MaxMap; j != 0; j--) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white[i]=(double) j; } histogram=(double *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) memset(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*stretch_map)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j <= (ssize_t) MaxMap; j++) { double gamma; gamma=PerceptibleReciprocal(white[i]-black[i]); if (j < (ssize_t) black[i]) stretch_map[GetPixelChannels(image)*j+i]=0.0; else if (j > (ssize_t) white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange; else if (black[i] != white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum( (double) (MaxMap*gamma*(j-black[i]))); } } if (image->storage_class == PseudoClass) { register ssize_t j; /* Stretch-contrast colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,RedPixelChannel); image->colormap[j].red=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,GreenPixelChannel); image->colormap[j].green=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,BluePixelChannel); image->colormap[j].blue=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,AlphaPixelChannel); image->colormap[j].alpha=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i]; } } } /* Stretch-contrast image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (black[j] == white[j]) continue; q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ContrastStretchImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(double *) RelinquishMagickMemory(stretch_map); white=(double *) RelinquishMagickMemory(white); black=(double *) RelinquishMagickMemory(black); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n h a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EnhanceImage() applies a digital filter that improves the quality of a % noisy image. % % The format of the EnhanceImage method is: % % Image *EnhanceImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception) { #define EnhanceImageTag "Enhance/Image" #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \ distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \ distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(image,r); \ aggregate.green+=(weight)*GetPixelGreen(image,r); \ aggregate.blue+=(weight)*GetPixelBlue(image,r); \ aggregate.black+=(weight)*GetPixelBlack(image,r); \ aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \ total_weight+=(weight); \ } \ r+=GetPixelChannels(image); CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize enhanced image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); enhance_image=CloneImage(image,0,0,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse) { enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); enhance_view=AcquireAuthenticCacheView(enhance_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,enhance_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception); q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2); GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; PixelInfo aggregate; register const Quantum *magick_restrict r; GetPixelInfo(image,&aggregate); total_weight=0.0; GetPixelInfoPixel(image,p+center,&pixel); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*GetPixelChannels(image)*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*GetPixelChannels(image)*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); if (total_weight > MagickEpsilon) { pixel.red=((aggregate.red+total_weight/2.0)/total_weight); pixel.green=((aggregate.green+total_weight/2.0)/total_weight); pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight); pixel.black=((aggregate.black+total_weight/2.0)/total_weight); pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); } SetPixelViaPixelInfo(enhance_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); } if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } enhance_view=DestroyCacheView(enhance_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) enhance_image=DestroyImage(enhance_image); return(enhance_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E q u a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EqualizeImage() applies a histogram equalization to the image. % % The format of the EqualizeImage method is: % % MagickBooleanType EqualizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=(double) p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(intensity))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) memset(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) memset(black,0,sizeof(*black)); (void) memset(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EqualizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GammaImage() gamma-corrects a particular image channel. The same % image viewed on different devices will have perceptual differences in the % way the image's intensities are represented on the screen. Specify % individual gamma levels for the red, green, and blue channels, or adjust % all three with the gamma parameter. Values typically range from 0.8 to 2.3. % % You can also reduce the influence of a particular channel with a gamma % value of 0. % % The format of the GammaImage method is: % % MagickBooleanType GammaImage(Image *image,const double gamma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o level: the image gamma as a string (e.g. 1.6,1.2,1.0). % % o gamma: the image gamma. % */ static inline double gamma_pow(const double value,const double gamma) { return(value < 0.0 ? value : pow(value,gamma)); } MagickExport MagickBooleanType GammaImage(Image *image,const double gamma, ExceptionInfo *exception) { #define GammaImageTag "Gamma/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; Quantum *gamma_map; register ssize_t i; ssize_t y; /* Allocate and initialize gamma maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (gamma == 1.0) return(MagickTrue); gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map)); if (gamma_map == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map)); if (gamma != 0.0) for (i=0; i <= (ssize_t) MaxMap; i++) gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/ MaxMap,PerceptibleReciprocal(gamma)))); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Gamma-correct colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].red))]; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].green))]; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].blue))]; if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].alpha))]; } /* Gamma-correct image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=gamma_map[ScaleQuantumToMap(ClampToQuantum((MagickRealType) q[j]))]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,GammaImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map); if (image->gamma != 0.0) image->gamma*=gamma; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GrayscaleImage() converts the image to grayscale. % % The format of the GrayscaleImage method is: % % MagickBooleanType GrayscaleImage(Image *image, % const PixelIntensityMethod method ,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the pixel intensity method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GrayscaleImage(Image *image, const PixelIntensityMethod method,ExceptionInfo *exception) { #define GrayscaleImageTag "Grayscale/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse) { image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } #endif /* Grayscale image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType blue, green, red, intensity; red=(MagickRealType) GetPixelRed(image,q); green=(MagickRealType) GetPixelGreen(image,q); blue=(MagickRealType) GetPixelBlue(image,q); intensity=0.0; switch (method) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+ blue*blue)/3.0); break; } case Rec601LumaPixelIntensityMethod: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+ blue*blue)/sqrt(3.0)); break; } } SetPixelGray(image,ClampToQuantum(intensity),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,GrayscaleImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H a l d C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % HaldClutImage() applies a Hald color lookup table to the image. A Hald % color lookup table is a 3-dimensional color cube mapped to 2 dimensions. % Create it with the HALD coder. You can apply any color transformation to % the Hald image and then use this method to apply the transform to the % image. % % The format of the HaldClutImage method is: % % MagickBooleanType HaldClutImage(Image *image,Image *hald_image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o hald_image: the color lookup table image for replacement color values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType HaldClutImage(Image *image, const Image *hald_image,ExceptionInfo *exception) { #define HaldClutImageTag "Clut/Image" typedef struct _HaldInfo { double x, y, z; } HaldInfo; CacheView *hald_view, *image_view; double width; MagickBooleanType status; MagickOffsetType progress; PixelInfo zero; size_t cube_size, length, level; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(hald_image != (Image *) NULL); assert(hald_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Hald clut image. */ status=MagickTrue; progress=0; length=(size_t) MagickMin((MagickRealType) hald_image->columns, (MagickRealType) hald_image->rows); for (level=2; (level*level*level) < length; level++) ; level*=level; cube_size=level*level; width=(double) hald_image->columns; GetPixelInfo(hald_image,&zero); hald_view=AcquireVirtualCacheView(hald_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double area, offset; HaldInfo point; PixelInfo pixel, pixel1, pixel2, pixel3, pixel4; point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q); point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q); point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q); offset=point.x+level*floor(point.y)+cube_size*floor(point.z); point.x-=floor(point.x); point.y-=floor(point.y); point.z-=floor(point.z); pixel1=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; pixel2=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel3=zero; area=point.y; if (hald_image->interpolate == NearestInterpolatePixel) area=(point.y < 0.5) ? 0.0 : 1.0; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, area,&pixel3); offset+=cube_size; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel4=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, area,&pixel4); pixel=zero; area=point.z; if (hald_image->interpolate == NearestInterpolatePixel) area=(point.z < 0.5)? 0.0 : 1.0; CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha, area,&pixel); if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) SetPixelRed(image,ClampToQuantum(pixel.red),q); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) SetPixelGreen(image,ClampToQuantum(pixel.green),q); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) SetPixelBlack(image,ClampToQuantum(pixel.black),q); if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,HaldClutImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } hald_view=DestroyCacheView(hald_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImage() adjusts the levels of a particular image channel by % scaling the colors falling between specified white and black points to % the full available quantum range. % % The parameters provided represent the black, and white points. The black % point specifies the darkest color in the image. Colors darker than the % black point are set to zero. White point specifies the lightest color in % the image. Colors brighter than the white point are set to the maximum % quantum value. % % If a '!' flag is given, map black and white colors to the given levels % rather than mapping those levels to black and white. See % LevelizeImage() below. % % Gamma specifies a gamma correction to apply to the image. % % The format of the LevelImage method is: % % MagickBooleanType LevelImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o exception: return any errors or warnings in this structure. % */ static inline double LevelPixel(const double black_point, const double white_point,const double gamma,const double pixel) { double level_pixel, scale; scale=PerceptibleReciprocal(white_point-black_point); level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point), PerceptibleReciprocal(gamma)); return(level_pixel); } MagickExport MagickBooleanType LevelImage(Image *image,const double black_point, const double white_point,const double gamma,ExceptionInfo *exception) { #define LevelImageTag "Level/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].red)); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].green)); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].blue)); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].alpha)); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma, (double) q[j])); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,LevelImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) ClampImage(image,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelizeImage() applies the reversed LevelImage() operation to just % the specific channels specified. It compresses the full range of color % values, so that they lie between the given black and white points. Gamma is % applied before the values are mapped. % % LevelizeImage() can be called with by using a +level command line % API option, or using a '!' on a -level or LevelImage() geometry string. % % It can be used to de-contrast a greyscale image to the exact levels % specified. Or by using specific levels for each channel of an image you % can convert a gray-scale image to any linear color gradient, according to % those levels. % % The format of the LevelizeImage method is: % % MagickBooleanType LevelizeImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o gamma: adjust gamma by this factor before mapping values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelizeImage(Image *image, const double black_point,const double white_point,const double gamma, ExceptionInfo *exception) { #define LevelizeImageTag "Levelize/Image" #define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \ (QuantumScale*(x)),gamma))*(white_point-black_point)+black_point) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) LevelizeValue( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) LevelizeValue( image->colormap[i].alpha); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=LevelizeValue(q[j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,LevelizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColors() maps the given color to "black" and "white" values, % linearly spreading out the colors, and level values on a channel by channel % bases, as per LevelImage(). The given colors allows you to specify % different level ranges for each of the color channels separately. % % If the boolean 'invert' is set true the image values will modifyed in the % reverse direction. That is any existing "black" and "white" colors in the % image will become the color values given, with all other values compressed % appropriately. This effectivally maps a greyscale gradient into the given % color gradient. % % The format of the LevelImageColors method is: % % MagickBooleanType LevelImageColors(Image *image, % const PixelInfo *black_color,const PixelInfo *white_color, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_color: The color to map black to/from % % o white_point: The color to map white to/from % % o invert: if true map the colors (levelize), rather than from (level) % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelImageColors(Image *image, const PixelInfo *black_color,const PixelInfo *white_color, const MagickBooleanType invert,ExceptionInfo *exception) { ChannelType channel_mask; MagickStatusType status; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsGrayColorspace(black_color->colorspace) == MagickFalse) || (IsGrayColorspace(white_color->colorspace) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; if (invert == MagickFalse) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } else { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelizeImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelizeImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelizeImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i n e a r S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LinearStretchImage() discards any pixels below the black point and above % the white point and levels the remaining pixels. % % The format of the LinearStretchImage method is: % % MagickBooleanType LinearStretchImage(Image *image, % const double black_point,const double white_point, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LinearStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define LinearStretchImageTag "LinearStretch/Image" CacheView *image_view; double *histogram, intensity; MagickBooleanType status; ssize_t black, white, y; /* Allocate histogram and linear map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Form histogram. */ (void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=GetPixelIntensity(image,p); histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black and white point levels. */ intensity=0.0; for (black=0; black < (ssize_t) MaxMap; black++) { intensity+=histogram[black]; if (intensity >= black_point) break; } intensity=0.0; for (white=(ssize_t) MaxMap; white != 0; white--) { intensity+=histogram[white]; if (intensity >= white_point) break; } histogram=(double *) RelinquishMagickMemory(histogram); status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black), (double) ScaleMapToQuantum((MagickRealType) white),1.0,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d u l a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModulateImage() lets you control the brightness, saturation, and hue % of an image. Modulate represents the brightness, saturation, and hue % as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the % modulation is lightness, saturation, and hue. For HWB, use blackness, % whiteness, and hue. And for HCL, use chrome, luma, and hue. % % The format of the ModulateImage method is: % % MagickBooleanType ModulateImage(Image *image,const char *modulate, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulate: Define the percent change in brightness, saturation, and hue. % % o exception: return any errors or warnings in this structure. % */ static inline void ModulateHCL(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHCLp(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLpToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHSB(const double percent_hue, const double percent_saturation,const double percent_brightness,double *red, double *green,double *blue) { double brightness, hue, saturation; /* Increase or decrease color brightness, saturation, or hue. */ ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; brightness*=0.01*percent_brightness; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } static inline void ModulateHSI(const double percent_hue, const double percent_saturation,const double percent_intensity,double *red, double *green,double *blue) { double intensity, hue, saturation; /* Increase or decrease color intensity, saturation, or hue. */ ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; intensity*=0.01*percent_intensity; ConvertHSIToRGB(hue,saturation,intensity,red,green,blue); } static inline void ModulateHSL(const double percent_hue, const double percent_saturation,const double percent_lightness,double *red, double *green,double *blue) { double hue, lightness, saturation; /* Increase or decrease color lightness, saturation, or hue. */ ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; lightness*=0.01*percent_lightness; ConvertHSLToRGB(hue,saturation,lightness,red,green,blue); } static inline void ModulateHSV(const double percent_hue, const double percent_saturation,const double percent_value,double *red, double *green,double *blue) { double hue, saturation, value; /* Increase or decrease color value, saturation, or hue. */ ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; value*=0.01*percent_value; ConvertHSVToRGB(hue,saturation,value,red,green,blue); } static inline void ModulateHWB(const double percent_hue, const double percent_whiteness,const double percent_blackness,double *red, double *green,double *blue) { double blackness, hue, whiteness; /* Increase or decrease color blackness, whiteness, or hue. */ ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness); hue+=fmod((percent_hue-100.0),200.0)/200.0; blackness*=0.01*percent_blackness; whiteness*=0.01*percent_whiteness; ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue); } static inline void ModulateLCHab(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHabToRGB(luma,chroma,hue,red,green,blue); } static inline void ModulateLCHuv(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue); } MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate, ExceptionInfo *exception) { #define ModulateImageTag "Modulate/Image" CacheView *image_view; ColorspaceType colorspace; const char *artifact; double percent_brightness, percent_hue, percent_saturation; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; register ssize_t i; ssize_t y; /* Initialize modulate table. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (modulate == (char *) NULL) return(MagickFalse); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); flags=ParseGeometry(modulate,&geometry_info); percent_brightness=geometry_info.rho; percent_saturation=geometry_info.sigma; if ((flags & SigmaValue) == 0) percent_saturation=100.0; percent_hue=geometry_info.xi; if ((flags & XiValue) == 0) percent_hue=100.0; colorspace=UndefinedColorspace; artifact=GetImageArtifact(image,"modulate:colorspace"); if (artifact != (const char *) NULL) colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions, MagickFalse,artifact); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; /* Modulate image colormap. */ red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSIColorspace: { ModulateHSI(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHColorspace: case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } image->colormap[i].red=red; image->colormap[i].green=green; image->colormap[i].blue=blue; } /* Modulate image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateModulateImage(image,percent_brightness,percent_hue, percent_saturation,colorspace,exception) != MagickFalse) return(MagickTrue); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red; red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHColorspace: case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ModulateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e g a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NegateImage() negates the colors in the reference image. The grayscale % option means that only grayscale values within the image are negated. % % The format of the NegateImage method is: % % MagickBooleanType NegateImage(Image *image, % const MagickBooleanType grayscale,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o grayscale: If MagickTrue, only negate grayscale pixels within the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NegateImage(Image *image, const MagickBooleanType grayscale,ExceptionInfo *exception) { #define NegateImageTag "Negate/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Negate colormap. */ if (grayscale != MagickFalse) if ((image->colormap[i].red != image->colormap[i].green) || (image->colormap[i].green != image->colormap[i].blue)) continue; if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } /* Negate image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); if( grayscale != MagickFalse ) { for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (IsPixelGray(image,q) == MagickFalse) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; progress++; proceed=SetImageProgress(image,NegateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(MagickTrue); } /* Negate image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,NegateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N o r m a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The NormalizeImage() method enhances the contrast of a color image by % mapping the darkest 2 percent of all pixel to black and the brightest % 1 percent to white. % % The format of the NormalizeImage method is: % % MagickBooleanType NormalizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NormalizeImage(Image *image, ExceptionInfo *exception) { double black_point, white_point; black_point=(double) image->columns*image->rows*0.0015; white_point=(double) image->columns*image->rows*0.9995; return(ContrastStretchImage(image,black_point,white_point,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i g m o i d a l C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SigmoidalContrastImage() adjusts the contrast of an image with a non-linear % sigmoidal contrast algorithm. Increase the contrast of the image using a % sigmoidal transfer function without saturating highlights or shadows. % Contrast indicates how much to increase the contrast (0 is none; 3 is % typical; 20 is pushing it); mid-point indicates where midtones fall in the % resultant image (0 is white; 50% is middle-gray; 100% is black). Set % sharpen to MagickTrue to increase the image contrast otherwise the contrast % is reduced. % % The format of the SigmoidalContrastImage method is: % % MagickBooleanType SigmoidalContrastImage(Image *image, % const MagickBooleanType sharpen,const char *levels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o contrast: strength of the contrast, the larger the number the more % 'threshold-like' it becomes. % % o midpoint: midpoint of the function as a color value 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ /* ImageMagick 6 has a version of this function which uses LUTs. */ /* Sigmoidal function Sigmoidal with inflexion point moved to b and "slope constant" set to a. The first version, based on the hyperbolic tangent tanh, when combined with the scaling step, is an exact arithmetic clone of the sigmoid function based on the logistic curve. The equivalence is based on the identity 1/(1+exp(-t)) = (1+tanh(t/2))/2 (http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the scaled sigmoidal derivation is invariant under affine transformations of the ordinate. The tanh version is almost certainly more accurate and cheaper. The 0.5 factor in the argument is to clone the legacy ImageMagick behavior. The reason for making the define depend on atanh even though it only uses tanh has to do with the construction of the inverse of the scaled sigmoidal. */ #if defined(MAGICKCORE_HAVE_ATANH) #define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) ) #else #define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) ) #endif /* Scaled sigmoidal function: ( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) / ( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) ) See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by zero. This is fixed below by exiting immediately when contrast is small, leaving the image (or colormap) unmodified. This appears to be safe because the series expansion of the logistic sigmoidal function around x=b is 1/2-a*(b-x)/4+... so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh). */ #define ScaledSigmoidal(a,b,x) ( \ (Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \ (Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) ) /* Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even when creating a LUT from in gamut values, hence the branching. In addition, HDRI may have out of gamut values. InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal: It is only a right inverse. This is unavoidable. */ static inline double InverseScaledSigmoidal(const double a,const double b, const double x) { const double sig0=Sigmoidal(a,b,0.0); const double sig1=Sigmoidal(a,b,1.0); const double argument=(sig1-sig0)*x+sig0; const double clamped= ( #if defined(MAGICKCORE_HAVE_ATANH) argument < -1+MagickEpsilon ? -1+MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b+(2.0/a)*atanh(clamped)); #else argument < MagickEpsilon ? MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b-log(1.0/clamped-1.0)/a); #endif } MagickExport MagickBooleanType SigmoidalContrastImage(Image *image, const MagickBooleanType sharpen,const double contrast,const double midpoint, ExceptionInfo *exception) { #define SigmoidalContrastImageTag "SigmoidalContrast/Image" #define ScaledSig(x) ( ClampToQuantum(QuantumRange* \ ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) #define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \ InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Convenience macros. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Side effect: may clamp values unless contrast<MagickEpsilon, in which case nothing is done. */ if (contrast < MagickEpsilon) return(MagickTrue); /* Sigmoidal-contrast enhance colormap. */ if (image->storage_class == PseudoClass) { register ssize_t i; if( sharpen != MagickFalse ) for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) ScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) ScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) ScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) ScaledSig( image->colormap[i].alpha); } else for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) InverseScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) InverseScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) InverseScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) InverseScaledSig( image->colormap[i].alpha); } } /* Sigmoidal-contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if( sharpen != MagickFalse ) q[i]=ScaledSig(q[i]); else q[i]=InverseScaledSig(q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e B a l a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteBalanceImage() applies white balancing to an image according to a % grayworld assumption in the LAB colorspace. % % The format of the WhiteBalanceImage method is: % % MagickBooleanType WhiteBalanceImage(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteBalanceImage(Image *image, ExceptionInfo *exception) { #define WhiteBalanceImageTag "WhiteBalance/Image" CacheView *image_view; const char *artifact; double a_mean, b_mean; MagickOffsetType progress; MagickStatusType status; ssize_t y; /* White balance image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=TransformImageColorspace(image,LabColorspace,exception); a_mean=0.0; b_mean=0.0; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { a_mean+=QuantumScale*GetPixela(image,p)-0.5; b_mean+=QuantumScale*GetPixelb(image,p)-0.5; p+=GetPixelChannels(image); } } a_mean/=((double) image->columns*image->rows); b_mean/=((double) image->columns*image->rows); progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; /* Scale the chroma distance shifted according to amount of luminance. */ a=(double) GetPixela(image,q)-1.1*GetPixelL(image,q)*a_mean; b=(double) GetPixelb(image,q)-1.1*GetPixelL(image,q)*b_mean; SetPixela(image,ClampToQuantum(a),q); SetPixelb(image,ClampToQuantum(b),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,WhiteBalanceImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); artifact=GetImageArtifact(image,"white-balance:vibrance"); if (artifact != (const char *) NULL) { ChannelType channel_mask; double black_point; GeometryInfo geometry_info; MagickStatusType flags; /* Level the a & b channels. */ flags=ParseGeometry(artifact,&geometry_info); black_point=geometry_info.rho; if ((flags & PercentValue) != 0) black_point*=(double) (QuantumRange/100.0); channel_mask=SetImageChannelMask(image,(ChannelType) (aChannel | bChannel)); status&=LevelImage(image,black_point,(double) QuantumRange-black_point, 1.0,exception); (void) SetImageChannelMask(image,channel_mask); } status&=TransformImageColorspace(image,sRGBColorspace,exception); return(status != 0 ? MagickTrue : MagickFalse); }
mixed_tentusscher_myo_epi_2004_S2_10.c
// Scenario 2 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S2_10.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { static bool first_call = true; if(first_call) { print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n"); first_call = false; } // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } // Initial conditions for TenTusscher myocardium if (mapping[sv_id] == 0) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } // Initial conditions for TenTusscher epicardium else { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.5511622902294,0.00129478742006594,0.779287470715019,0.779085777490476,0.000175320721320771,0.484912147435167,0.00294388722898241,0.999998342407651,1.93902525670492e-08,1.89538282650298e-05,0.999770600174468,1.00728398116038,0.999997515777305,4.07234942648284e-05,0.868650749787138,9.18269314291632,140.209404518869}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = (uint32_t )i; for (int j = 0; j < num_steps; ++j) { if (mapping[i] == 0) solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]); else solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_myo(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Myocardium cell real Gks=0.062; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Myocardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; // [!] Myocardium cell R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; } void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_epi(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={13.7461143263116,0.000459997917121747,0.000140043524254897,0.000542687336889403,0.260467022022842,0.179993407329159,0.120919029542890,3.73845958623661,0.0156010781506009,2.57804634751980,1099.99494996411,0.000486512853285864,0.210461563351288,0.0129601246111510,0.00526035691087821,1.87013769395828e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
Proj4.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "grb2.h" #include "wgrib2.h" #include "fnlist.h" /* proj4.c interface routines to the Proj.4 library 6/2012 Public Domain Dusan Jovic 8/2014 Public Domain Wesley Ebisuzaki latlon lambert conformal ncep rotated latlon B grid 10/2015 lambert azimuthal equal area */ #ifdef USE_PROJ4 #include "proj_api.h" #include "proj4_wgrib2.h" extern int latlon; extern enum output_order_type output_order; extern int use_proj4; #ifndef M_PI #define M_PI 3.14159265358979323846 /* pi */ #endif #ifndef M_PI_2 #define M_PI_2 1.57079632679489661923 /* pi/2 */ #endif #ifndef M_PI_4 #define M_PI_4 0.78539816339744830962 /* pi/4 */ #endif extern double *lat, *lon; static double dx, dy, x_0, y_0, x00, xN; static unsigned int gdt; static int nx, ny; static unsigned int nx_, ny_; static projPJ pj_grid, pj_latlon; int proj4_init(unsigned char **sec, double *grid_lon, double *grid_lat) { unsigned char *gds; double r_maj; /* major axis */ double r_min; /* minor axis */ double latsp1; /* first standard parallel */ double latsp2; /* second standard parallel */ double c_lon; /* center longitude */ double c_lat; /* center latitude */ double lon1; // double lon2; double lat1; // double lat2; int nres, nscan,has_np, center; unsigned int npnts; char proj4_def[1000]; if (grid_lat == NULL || grid_lon == NULL) return 1; gdt = code_table_3_1(sec); gds = sec[3]; center = GB2_Center(sec); get_nxny(sec, &nx, &ny, &npnts, &nres, &nscan); get_nxny_(sec, &nx_, &ny_, &npnts, &nres, &nscan); if (nx_ < 1 || ny_ < 1 || nx_*ny_ != npnts) return 1; /* only process certain grids */ pj_grid = NULL; pj_latlon = NULL; x_0 = y_0 = x00 = xN = 0.0; if (gdt == 0) { /* lat-lon grid */ dx = grid_lon[1] - grid_lon[0]; dy = grid_lat[nx] - grid_lat[0]; x_0 = grid_lon[0]; x00 = grid_lon[0] - 0.5*dx; xN = grid_lon[nx-1] + 0.5*dx; y_0 = grid_lat[0]; return 0; } else if (gdt == 10 && (GDS_Mercator_ori_angle(gds) == 0.0) ) { // mercator no rotation /* get earth axis */ axes_earth(sec, &r_maj, &r_min); dx = abs(GDS_Mercator_dx(gds)); dy = abs(GDS_Mercator_dy(gds)); /* central point */ c_lon = 0.0; c_lat = GDS_Mercator_latD(gds); sprintf(proj4_def,"+proj=merc +lat_ts=%lf +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +a=%lf +b=%lf", c_lat, r_maj, r_min); if ((pj_grid = pj_init_plus(proj4_def)) == NULL) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); sprintf(proj4_def,"+proj=latlong +a=%lf +b=%lf",r_maj, r_min); if ( (pj_latlon = pj_init_plus(proj4_def)) == NULL) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); /* longitude, latitude of first grid point */ lat1 = GDS_Mercator_lat1(gds); lon1 = GDS_Mercator_lon1(gds); x_0 = lon1 * DEG_TO_RAD; y_0 = lat1 * DEG_TO_RAD; if ( pj_transform(pj_latlon, pj_grid, 1, 1, &x_0, &y_0, NULL) != 0 ) fatal_error("proj4_init: Proj4 transform to lat-lon",""); } else if (gdt == 20) { // polar stereographic /* get earth axis */ axes_earth(sec, &r_maj, &r_min); dy = fabs(GDS_Polar_dy(gds)); dx = fabs(GDS_Polar_dx(gds)); /* central point */ c_lon = GDS_Polar_lov(gds); c_lat = GDS_Polar_lad(gds); /* strange but np/sp flag is used by proj4 but not gctpc */ has_np = ((flag_table_3_5(sec) & 128) == 0); sprintf(proj4_def,"+proj=stere +lat_ts=%lf +lat_0=%s +lon_0=%lf +k_0=1 +x_0=0 +y_0=0 +a=%lf +b=%lf", c_lat, has_np ? "90" : "-90", c_lon, r_maj,r_min); if ((pj_grid = pj_init_plus(proj4_def)) == NULL) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); sprintf(proj4_def,"+proj=latlong +a=%lf +b=%lf",r_maj, r_min); if ( (pj_latlon = pj_init_plus(proj4_def)) == NULL) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); /* longitude, latitude of first grid point */ lon1 = GDS_Polar_lon1(gds); lat1 = GDS_Polar_lat1(gds); x_0 = lon1 * DEG_TO_RAD; y_0 = lat1 * DEG_TO_RAD; if ( pj_transform(pj_latlon, pj_grid, 1, 1, &x_0, &y_0, NULL) != 0 ) fatal_error("proj4_init: Proj4 transform to lat-lon",""); } else if (gdt == 30) { // lambert conformal conic /* get earth axis */ axes_earth(sec, &r_maj, &r_min); dx = fabs(GDS_Lambert_dx(gds)); dy = fabs(GDS_Lambert_dy(gds)); /* latitudes of tangent/intersection */ latsp1 = GDS_Lambert_Latin1(gds); latsp2 = GDS_Lambert_Latin2(gds); /* central point */ c_lon = GDS_Lambert_Lov(gds); c_lat = GDS_Lambert_LatD(gds); sprintf(proj4_def,"+proj=lcc +lon_0=%lf +lat_0=%lf +lat_1=%lf +lat_2=%lf +a=%lf +b=%lf",c_lon, c_lat,latsp1,latsp2,r_maj,r_min); if ((pj_grid = pj_init_plus(proj4_def)) == NULL) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); sprintf(proj4_def,"+proj=latlong +a=%lf +b=%lf",r_maj, r_min); if ((pj_latlon = pj_init_plus(proj4_def)) == NULL) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); /* longitude, latitude of first grid point */ lon1 = GDS_Lambert_Lo1(gds); lat1 = GDS_Lambert_La1(gds); x_0 = lon1 * DEG_TO_RAD; y_0 = lat1 * DEG_TO_RAD; if ( pj_transform(pj_latlon, pj_grid, 1, 1, &x_0, &y_0, NULL) != 0 ) fatal_error("proj4_init: Proj4 transform to lat-lon",""); } else if (gdt == 140) { // lambert azimuthal equal area /* get earth axis */ axes_earth(sec, &r_maj, &r_min); dx = fabs(GDS_Lambert_Az_dx(gds)); dy = fabs(GDS_Lambert_Az_dy(gds)); /* central point */ c_lon = GDS_Lambert_Az_Cen_Lon(gds); c_lat = GDS_Lambert_Az_Std_Par(gds); sprintf(proj4_def,"+proj=laea +lon_0=%lf +lat_0=%lf +a=%lf +b=%lf",c_lon,c_lat,r_maj,r_min); if ((pj_grid = pj_init_plus(proj4_def)) == NULL) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); sprintf(proj4_def,"+proj=latlong +a=%lf +b=%lf",r_maj, r_min); if ((pj_latlon = pj_init_plus(proj4_def)) == NULL) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); /* longitude, latitude of first grid point */ lon1 = GDS_Lambert_Az_Lo1(gds); lat1 = GDS_Lambert_Az_La1(gds); x_0 = lon1 * DEG_TO_RAD; y_0 = lat1 * DEG_TO_RAD; if ( pj_transform(pj_latlon, pj_grid, 1, 1, &x_0, &y_0, NULL) != 0 ) fatal_error("proj4_init: Proj4 transform to lat-lon",""); } else if (center == NCEP && gdt == 32769) { // ncep rotated latlon Non-E /* get earth axis */ axes_earth(sec, &r_maj, &r_min); /* dx, dy */ dx = fabs(GDS_NCEP_B_LatLon_dlon(gds) * 0.000001); dy = fabs(GDS_NCEP_B_LatLon_dlat(gds) * 0.000001); dx *= DEG_TO_RAD; dy *= DEG_TO_RAD; /* central point */ c_lon = GDS_NCEP_B_LatLon_tlm0d(gds) * 0.000001; c_lat = GDS_NCEP_B_LatLon_tph0d(gds) * 0.000001; lon1 = GDS_NCEP_B_LatLon_lon1(gds) * 0.000001; lat1 = GDS_NCEP_B_LatLon_lat1(gds) * 0.000001; sprintf(proj4_def,"+proj=ob_tran +o_proj=latlon +o_lon_p=%f +o_lat_p=%f",c_lon,90.0+c_lat); if ((pj_latlon = pj_init_plus(proj4_def)) == NULL) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); sprintf(proj4_def,"+proj=latlon"); if ((pj_grid = pj_init_plus(proj4_def)) == NULL ) fatal_error("Proj4: pj_init_plus %s failed", proj4_def); x_0 = lon1 * DEG_TO_RAD; y_0 = lat1 * DEG_TO_RAD; if ( pj_transform(pj_latlon, pj_grid, 1, 1, &x_0, &y_0, NULL) != 0 ) fatal_error("proj4_init: Proj4 transform to lat-lon",""); } else { return 1; } return 0; } int Proj4_ll2xy(int n, double *lon, double *lat, double *x, double *y) { int i; double rlon, rlat, inv_dx, inv_dy; inv_dx = 1.0 / dx; inv_dy = 1.0 / dy; if (gdt == 0) { // lat-lon #pragma omp parallel for schedule(static) private(i,rlon,rlat) for (i = 0; i < n; i++) { rlon = lon[i]; if (rlon > xN) rlon -= 360.0; if (rlon < x00) rlon += 360.0; rlat = lat[i]; x[i] = (rlon - x_0) * inv_dx; y[i] = (rlat - y_0) * inv_dy; } return 0; } #pragma omp parallel for schedule(static) private(i,rlon,rlat) for (i = 0; i < n; i++) { rlon = lon[i] * DEG_TO_RAD; rlat = lat[i] * DEG_TO_RAD; if ( pj_transform(pj_latlon, pj_grid, 1, 1, &rlon, &rlat, NULL) != 0 ) { x[i] = y[i] = UNDEFINED; } else { x[i] = (rlon - x_0)*inv_dx; y[i] = (rlat - y_0)*inv_dy; } } return 0; } int Proj4_ll2i(int n, double *lon, double *lat, unsigned int *ipnt) { int error; unsigned int i; double rlon, rlat, inv_dx, inv_dy, x, y; inv_dx = 1.0 / dx; inv_dy = 1.0 / dy; if (gdt == 0) { // lat-lon #pragma omp parallel for schedule(static) private(i,rlon,rlat,x,y) for (i = 0; i < n; i++) { rlon = lon[i]; if (rlon > xN) rlon -= 360.0; if (rlon < x00) rlon += 360.0; rlat = lat[i]; x = floor((rlon - x_0) * inv_dx + 0.5); y = floor((rlat - y_0) * inv_dy + 0.5); if (x < 0 || x >= nx || y < 0 || y >= ny) { ipnt[i] = 0; } else { ipnt[i] = (unsigned int) x + nx* ((unsigned int) y) + 1; } } return 0; } error = 0; for (i = 0; i < n; i++) { rlon = lon[i] * DEG_TO_RAD; rlat = lat[i] * DEG_TO_RAD; if ( pj_transform(pj_latlon, pj_grid, 1, 1, &rlon, &rlat, NULL) != 0 ) error = 1; x = floor((rlon - x_0)*inv_dx + 0.5); y = floor((rlat - y_0)*inv_dy + 0.5); if (x < 0 || x >= nx || y < 0 || y >= ny) { ipnt[i] = 0; } else { ipnt[i] = (unsigned int) x + nx*(unsigned int) y + 1; } } return error; } /* * HEADER:100:proj4_ll2ij:inv:2:x=lon y=lat, converts lon-lat (i,j) using proj.4 (experimental) */ int f_proj4_ll2ij(ARG2) { double x[1], y[1], to_lat[1], to_lon[1]; int i; if (mode == -1) { latlon = 1; } if (mode >= 0) { if (output_order != wesn) return 1; to_lon[0] = atof(arg1); to_lat[0] = atof(arg2); i = proj4_init(sec, lon, lat); if (i == 0) { i = Proj4_ll2xy(1, to_lon, to_lat, x , y); if (i) x[0] = y[0] = -1.0; sprintf(inv_out,"%lf %lf -> (%lf,%lf)",to_lon[0], to_lat[0], x[0]+1.0, y[0]+1.0); } } return 0; } int Proj4_ij2ll(unsigned char **sec, int n, double *x, double *y, double *lon, double *lat) { int i, error; double xx, yy; if (gdt == 0) { #pragma omp parallel for schedule(static) for (i = 0; i < n; i++) { lon[i] = dx * x[i] + x_0; lat[i] = dy * y[i] + y_0; if (lon[i] < 0.0) lon[i] += 360.0; } return 0; } error = 0; #pragma omp parallel for schedule(static) private(i,xx,yy) for (i = 0; i < n; i++) { xx = x[i] + x_0; yy = y[i] + y_0; /* test */ xx = dx*(x[i] -1.0) + x_0; yy = dy*(y[i] -1.0) + y_0; if ( pj_transform(pj_grid, pj_latlon, 1, 1, &xx, &yy, NULL) != 0 ) { error = 1; lon[i] = 999.0; lat[i] = 999.0; } else { lon[i] = xx * RAD_TO_DEG; lat[i] = yy * RAD_TO_DEG; if (lon[i] < 0.0) lon[i] += 360.0; } } return error; } int Proj4_xy2ll(int n, double *x, double *y, double *lon, double *lat) { int i, error; double xx, yy; if (gdt == 0) { #pragma omp parallel for schedule(static) for (i = 0; i < n; i++) { lon[i] = dx * x[i] + x_0; lat[i] = dy * y[i] + y_0; if (lon[i] < 0.0) lon[i] += 360.0; } return 0; } error = 0; for (i = 0; i < n; i++) { xx = x[i] + x_0; yy = y[i] + y_0; if ( pj_transform(pj_grid, pj_latlon, 1, 1, &xx, &yy, NULL) != 0 ) error = 1; lon[i] = xx * RAD_TO_DEG; lat[i] = yy * RAD_TO_DEG; if (lon[i] < 0.0) lon[i] += 360.0; } return error; } /* * HEADER:100:proj4_ij2ll:inv:2:X=x Y=y, converts to (i,j) to lon-lat using proj.4 (experimental) we:sn */ int f_proj4_ij2ll(ARG2) { int i; double x, y, rlon, rlat; if (mode == -1) { latlon = 1; } else if (mode >= 0) { x = atof(arg1); y = atof(arg2); i = proj4_init(sec, lon, lat); if (i == 0) { i = Proj4_ij2ll(sec, 1, &x, &y, &rlon, &rlat); if (i == 0) { sprintf(inv_out,"x=%lf y=%lf lon=%lf lat=%lf", x, y, rlon, rlat); } } } return 0; } /* * HEADER:100:proj4_ll2i:inv:2:x=lon y=lat, converts to (i) using proj.4 (experimental) 1..ndata */ int f_proj4_ll2i(ARG2) { double to_lat[1], to_lon[1]; int i; unsigned int iptr; if (mode == -1) { latlon = 1; } if (mode >= 0) { if (output_order != wesn) return 1; to_lon[0] = atof(arg1); to_lat[0] = atof(arg2); i = proj4_init(sec, lon, lat); if (i) iptr = 0; else { i = Proj4_ll2i(1, to_lon, to_lat, &iptr); if (i) iptr = 0; } sprintf(inv_out,"%lf %lf -> (%u)",to_lon[0], to_lat[0], iptr); } return 0; } /* * HEADER:100:proj4:misc:1:X=0,1 use proj4 library for geolocation (testing) */ int f_proj4(ARG1) { use_proj4 = (strcmp(arg1,"1") == 0); return 0; } int proj4_get_latlon(unsigned char **sec, double **lon, double **lat) { int nnx, nny, nres, nscan, error; unsigned int i, nnpnts; double *llat, *llon; llat = *lat; llon = *lon; if (proj4_init(sec, llon, llat) != 0) return 1; get_nxny(sec, &nnx, &nny, &nnpnts, &nres, &nscan); /* potentially staggered */ if (llat != NULL) { free(llat); free(llon); *lat = *lon = llat = llon = NULL; } if ((*lat = llat = (double *) malloc(sizeof(double) * (size_t) nnpnts)) == NULL) { fatal_error("proj4_get_latlon memory allocation failed",""); } if ((*lon = llon = (double *) malloc(sizeof(double) * (size_t) nnpnts)) == NULL) { fatal_error("proj4_get_latlon memory allocation failed",""); } /* put x[] and y[] values in lon and lat */ if (stagger(sec, nnpnts, llon, llat)) fatal_error("proj4: stagger problem",""); /* handle lat-lon grid differently */ if (gdt == 0) { #pragma omp parallel for private(i) for (i = 0; i < nnpnts; i++) { llon[i] = dx * llon[i] + x_0; llat[i] = dy * llat[i] + y_0; if (llon[i] < 0.0) llon[i] += 360.0; if (llon[i] > 360.0) llon[i] -= 360.0; } return 0; } /* proj4 projections */ #pragma omp parallel for private(i) for (i = 0; i < nnpnts; i++) { llon[i] = llon[i] * dx + x_0; llat[i] = llat[i] * dy + y_0; } error = pj_transform(pj_grid, pj_latlon, (long) nnpnts, (long) 1, llon, llat, NULL); #pragma omp parallel for private(i) for (i = 0; i < nnpnts; i++) { llon[i] = llon[i] * RAD_TO_DEG; llat[i] = llat[i] * RAD_TO_DEG; if (llon[i] < 0.0) llon[i] += 360.0; } return error; } #else int f_proj4(ARG1) { if (mode == -1) {fprintf(stderr,"Proj4 package not installed\n"); return 1;} return 1; } int f_proj4_ll2ij(ARG2) { if (mode == -1) {fprintf(stderr,"Proj4 package not installed\n"); return 1;} return 1; } int f_proj4_ij2ll(ARG2) { if (mode == -1) {fprintf(stderr,"Proj4 package not installed\n"); return 1;} return 1; } int f_proj4_ll2i(ARG2) { if (mode == -1) {fprintf(stderr,"Proj4 package not installed\n"); return 1;} return 1; } #endif
amuxCRS.h
/** * \file * \author Thomas Fischer * \date 2011-09-20 * \brief Definition of amuxCRS functions. * * \copyright * Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #ifndef AMUXCRS_H #define AMUXCRS_H namespace MathLib { template<typename FP_TYPE, typename IDX_TYPE> void amuxCRS(FP_TYPE a, IDX_TYPE n, IDX_TYPE const * const iA, IDX_TYPE const * const jA, FP_TYPE const * const A, FP_TYPE const * const x, FP_TYPE* y) { for (IDX_TYPE i(0); i < n; i++) { const IDX_TYPE end(iA[i + 1]); y[i] = A[iA[i]] * x[jA[iA[i]]]; for (IDX_TYPE j(iA[i]+1); j < end; j++) { y[i] += A[j] * x[jA[j]]; } y[i] *= a; } } void amuxCRSParallelPThreads (double a, unsigned n, unsigned const * const iA, unsigned const * const jA, double const * const A, double const * const x, double* y, unsigned num_of_pthreads); void amuxCRSParallelPThreads (double a, unsigned n, unsigned const * const iA, unsigned const * const jA, double const * const A, double const * const x, double* y, unsigned num_of_pthreads, unsigned const*const workload_intervals); #ifdef _OPENMP template<typename FP_TYPE, typename IDX_TYPE> void amuxCRSParallelOpenMP (FP_TYPE a, unsigned n, IDX_TYPE const * const __restrict__ iA, IDX_TYPE const * const __restrict__ jA, FP_TYPE const * const A, FP_TYPE const * const __restrict__ x, FP_TYPE* __restrict__ y) { OPENMP_LOOP_TYPE i; IDX_TYPE j; FP_TYPE t; { #pragma omp parallel for private(i, j, t) #ifdef WIN32 #pragma warning ( push ) #pragma warning ( disable: 4018 ) #endif for (i = 0; i < n; i++) { const IDX_TYPE end(iA[i + 1]); t = A[iA[i]] * x[jA[iA[i]]]; for (j = iA[i]+1; j < end; j++) { t += A[j] * x[jA[j]]; } y[i] = t * a; } } #ifdef WIN32 #pragma warning ( pop ) #endif } #endif void amuxCRSSym (double a, unsigned n, unsigned const * const iA, unsigned const * const jA, double const * const A, double const * const x, double* y); } // end namespace MathLib #endif
valid.yolo1.src.h
#pragma once #include "ukr.h" #include "omp.h" #include "transpose.h" #include "gen_ukr_A6B2gemm_1_32_544_544_3_3_3.h" #include "gen_ukr_A4B2gemm_1_32_544_544_3_3_3.h" void testrun(float* A ,float*B, float*C, float*oriB ){ int tid = omp_get_thread_num(); int Nx = 544; int Ny = 544; int Nh = 3; long long Astrides[6] = {0,1,2,3,4,5}; int b1 = 0; for (int fpck = (tid%1)*16; fpck < uNf; fpck+=1*16){ for(int cwh = (tid/1)*8; cwh < uNc*uNw*uNh/8*8; cwh+=8*1){ transpose8x8_avx(oriB+ (fpck+0)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 0, uNc*uNw*uNh, 16); transpose8x8_avx(oriB+ (fpck+8)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 8, uNc*uNw*uNh, 16); } if((tid/1)*8==0){ int cwh = uNc*uNw*uNh/8*8; transpose3x8_avx(oriB+ (fpck+0)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 0, uNc*uNw*uNh, 16); transpose3x8_avx(oriB+ (fpck+8)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 8, uNc*uNw*uNh, 16); } } #pragma omp barrier// begin push button generated block for(int c5=0;c5<3+0;c5+=3) { for(int f5=0;f5<32+0;f5+=32) { for(int xy5=0;xy5<295936+0;xy5+=295936) { for(int c4=c5;c4<min(3, 3+c5);c4+=3) { for(int xy4=xy5;xy4<min(295936, 295936+xy5);xy4+=295936) { for(int c3=c4;c3<min(3, 3+c4);c3+=Tc1) { for(int xy3=xy4;xy3<min(295936, 295936+xy4);xy3+=Txy3) { for(int f4=f5;f4<min(32, 32+f5);f4+=32) { for(int f3=f4;f3<min(32, 32+f4);f3+=Tf2) { for(int f2=f3;f2<min(32, Tf2+f3);f2+=16) { for(int xy2=xy3;xy2<min(295936, Txy3+xy3);xy2+=6) { for(int c2=c3;c2<min(3, Tc1+c3);c2+=Tc1) { for(int c1=c2;c1<min(3, Tc1+c2);c1+=Tc1) { for(int xy1=xy2;xy1<min(295936, 6+xy2);xy1+=6) { for(int f1=f2;f1<min(32, 16+f2);f1+=16) { int ctile=min(Tc1, 3-c1); int x1=xy1/544; int y1=xy1%544/1; int c1_1=c1/1; int c1_2=c1%1/1; int kf1_1=f1/16; int kf1_2=f1%16/1; int of1_1=f1/1; int of1_2=f1%1/1; int offsetA=0+b1*894348+c1_1*298116+1*x1*546+1*y1*1+c1_2*1; int offsetB=0+kf1_1*432+c1*144+0*48+0*16+kf1_2*1; int offsetC=0+b1*9469952+of1_1*295936+x1*544+y1*1+of1_2*1; if(544-y1>=6){ cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); } else if(544*544-xy1>=6){ for(int sti=544-y1;sti<6;sti+=1) { Astrides[sti]+=2; } cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); for(int sti=544-y1;sti<6;sti+=1) { Astrides[sti]-=2; } } else{ cnn_ukr_float_scatter_4x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); } } } } } } } } } } } } } } } } // end push button generated block }
threading.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision: 2.4 $ ***********************************************************************EHEADER*/ #include <stdlib.h> #include <stdio.h> #include "utilities.h" #if defined(HYPRE_USING_OPENMP) || defined (HYPRE_USING_PGCC_SMP) int hypre_NumThreads( ) { int num_threads; #ifdef HYPRE_USING_OPENMP #pragma omp parallel num_threads = omp_get_num_threads(); #endif #ifdef HYPRE_USING_PGCC_SMP num_threads = 2; #endif return num_threads; } /* This next function must be called from within a parallel region! */ int hypre_NumActiveThreads( ) { int num_threads; num_threads = omp_get_num_threads(); return num_threads; } /* This next function must be called from within a parallel region! */ int hypre_GetThreadNum( ) { int my_thread_num; my_thread_num = omp_get_thread_num(); return my_thread_num; } #endif /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ /* The pthreads stuff needs to be reworked */ #define HYPRE_THREAD_GLOBALS #ifdef HYPRE_USE_PTHREADS #ifdef HYPRE_USE_UMALLOC #include "umalloc_local.h" #endif int iteration_counter = 0; volatile int hypre_thread_counter; volatile int work_continue = 1; int HYPRE_InitPthreads( int num_threads ) { int err; int i; hypre_qptr = (hypre_workqueue_t) malloc(sizeof(struct hypre_workqueue_struct)); hypre_NumThreads = num_threads; initial_thread = pthread_self(); if (hypre_qptr != NULL) { pthread_mutex_init(&hypre_qptr->lock, NULL); pthread_cond_init(&hypre_qptr->work_wait, NULL); pthread_cond_init(&hypre_qptr->finish_wait, NULL); hypre_qptr->n_working = hypre_qptr->n_waiting = hypre_qptr->n_queue = 0; hypre_qptr->inp = hypre_qptr->outp = 0; for (i=0; i < hypre_NumThreads; i++) { #ifdef HYPRE_USE_UMALLOC /* Get initial area to start heap */ hypre_assert ((_uinitial_block[i] = malloc(INITIAL_HEAP_SIZE))!=NULL); /* Create a user heap */ hypre_assert ((_uparam[i].myheap = _ucreate(initial_block[i], INITIAL_HEAP_SIZE, _BLOCK_CLEAN, _HEAP_REGULAR, _uget_fn, _urelease_fn)) != NULL); #endif err=pthread_create(&hypre_thread[i], NULL, (void *(*)(void *))hypre_pthread_worker, (void *)i); hypre_assert(err == 0); } } pthread_mutex_init(&hypre_mutex_boxloops, NULL); pthread_mutex_init(&mpi_mtx, NULL); pthread_mutex_init(&talloc_mtx, NULL); pthread_mutex_init(&time_mtx, NULL); pthread_mutex_init(&worker_mtx, NULL); hypre_thread_counter = 0; hypre_thread_release = 0; return (err); } void hypre_StopWorker(void *i) { work_continue = 0; } void HYPRE_DestroyPthreads( void ) { int i; void *status; for (i=0; i < hypre_NumThreads; i++) { hypre_work_put(hypre_StopWorker, (void *) &i); } #ifdef HYPRE_USE_UMALLOC for (i=0; i<hypre_NumThreads; i++) { _udestroy (_uparam[i].myheap, _FORCE); } #endif for (i=0; i<hypre_NumThreads; i++) pthread_join(hypre_thread[i], &status); pthread_mutex_destroy(&hypre_qptr->lock); pthread_mutex_destroy(&hypre_mutex_boxloops); pthread_mutex_destroy(&mpi_mtx); pthread_mutex_destroy(&talloc_mtx); pthread_mutex_destroy(&time_mtx); pthread_mutex_destroy(&worker_mtx); pthread_cond_destroy(&hypre_qptr->work_wait); pthread_cond_destroy(&hypre_qptr->finish_wait); free (hypre_qptr); } void hypre_pthread_worker( int threadid ) { void *argptr; hypre_work_proc_t funcptr; pthread_mutex_lock(&hypre_qptr->lock); hypre_qptr->n_working++; while(work_continue) { while (hypre_qptr->n_queue == 0) { if (--hypre_qptr->n_working == 0) pthread_cond_signal(&hypre_qptr->finish_wait); hypre_qptr->n_waiting++; pthread_cond_wait(&hypre_qptr->work_wait, &hypre_qptr->lock); hypre_qptr->n_waiting--; hypre_qptr->n_working++; } hypre_qptr->n_queue--; funcptr = hypre_qptr->worker_proc_queue[hypre_qptr->outp]; argptr = hypre_qptr->argqueue[hypre_qptr->outp]; hypre_qptr->outp = (hypre_qptr->outp + 1) % MAX_QUEUE; pthread_mutex_unlock(&hypre_qptr->lock); (*funcptr)(argptr); hypre_barrier(&worker_mtx, 0); if (work_continue) pthread_mutex_lock(&hypre_qptr->lock); } } void hypre_work_put( hypre_work_proc_t funcptr, void *argptr ) { pthread_mutex_lock(&hypre_qptr->lock); if (hypre_qptr->n_waiting) { /* idle workers to be awakened */ pthread_cond_signal(&hypre_qptr->work_wait); } hypre_assert(hypre_qptr->n_queue != MAX_QUEUE); hypre_qptr->n_queue++; hypre_qptr->worker_proc_queue[hypre_qptr->inp] = funcptr; hypre_qptr->argqueue[hypre_qptr->inp] = argptr; hypre_qptr->inp = (hypre_qptr->inp + 1) % MAX_QUEUE; pthread_mutex_unlock(&hypre_qptr->lock); } /* Wait until all work is done and workers quiesce. */ void hypre_work_wait( void ) { pthread_mutex_lock(&hypre_qptr->lock); while(hypre_qptr->n_queue !=0 || hypre_qptr->n_working != 0) pthread_cond_wait(&hypre_qptr->finish_wait, &hypre_qptr->lock); pthread_mutex_unlock(&hypre_qptr->lock); } int hypre_fetch_and_add( int *w ) { int temp; temp = *w; *w += 1; return temp; } int ifetchadd( int *w, pthread_mutex_t *mutex_fetchadd ) { int n; pthread_mutex_lock(mutex_fetchadd); n = *w; *w += 1; pthread_mutex_unlock(mutex_fetchadd); return n; } static volatile int thb_count = 0; static volatile int thb_release = 0; void hypre_barrier(pthread_mutex_t *mtx, int unthreaded) { if (!unthreaded) { pthread_mutex_lock(mtx); thb_count++; if (thb_count < hypre_NumThreads) { pthread_mutex_unlock(mtx); while (!thb_release); pthread_mutex_lock(mtx); thb_count--; pthread_mutex_unlock(mtx); while (thb_release); } else if (thb_count == hypre_NumThreads) { thb_count--; pthread_mutex_unlock(mtx); thb_release++; while (thb_count); thb_release = 0; } } } int hypre_GetThreadID( void ) { int i; if (pthread_equal(pthread_self(), initial_thread)) return hypre_NumThreads; for (i = 0; i < hypre_NumThreads; i++) { if (pthread_equal(pthread_self(), hypre_thread[i])) return i; } return -1; } #endif /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
opencl_sxc_fmt_plug.c
/* * Modified by Dhiru Kholia <dhiru at openwall.com> for Keychain format. * * This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net> * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_sxc; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_sxc); #else #include <string.h> #include "sha.h" #include <openssl/blowfish.h> #include "aes.h" #ifdef _OPENMP #include <omp.h> #endif #include "arch.h" #include "formats.h" #include "common.h" #include "stdint.h" #include "misc.h" #include "options.h" #include "common.h" #include "formats.h" #include "common-opencl.h" #define FORMAT_LABEL "sxc-opencl" #define FORMAT_NAME "StarOffice .sxc" #define FORMAT_TAG "$sxc$*" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL Blowfish" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define BINARY_SIZE 20 #define PLAINTEXT_LENGTH 64 #define SALT_SIZE sizeof(sxc_cpu_salt) #define BINARY_ALIGN MEM_ALIGN_WORD #define SALT_ALIGN 4 typedef struct { uint32_t length; uint8_t v[20]; // hash of password } sxc_password; typedef struct { uint32_t v[16/4]; } sxc_hash; typedef struct { uint32_t iterations; uint32_t outlen; uint32_t skip_bytes; uint8_t length; uint8_t salt[64]; } sxc_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[32 / sizeof(ARCH_WORD_32)]; typedef struct { int cipher_type; int checksum_type; int iterations; int key_size; int iv_length; int salt_length; int original_length; int length; unsigned char iv[16]; unsigned char salt[32]; unsigned char content[1024]; } sxc_cpu_salt; static sxc_cpu_salt *cur_salt; static struct fmt_tests sxc_tests[] = { {"$sxc$*0*0*1024*16*4448359828281a1e6842c31453473abfeae584fb*8*dc0248bea0c7508c*16*1d53770002fe9d8016064e5ef9423174*860*864*f00399ab17b9899cd517758ecf918d4da78099ccd3557aef5e22e137fd5b81f732fc7c167c4de0cf263b4f82b50e3d6abc65da613a36b0025d89e1a09adeb4106da28040d1019bb4b36630fc8bc94fe5b515504bf8a92ea630bb95ace074868e7c10743ec970c89895f44b975a30b6ca032354f3e73ec86b2cc7a4f7a185884026d971b37b1e0e650376a2552e27ba955c700f8903a82a6df11f6cc2ecf63290f02ffdd278f890d1db75f9e8bd0f437c4ec613d3c6dcb421bbd1067be633593ba9bd58f77ef08e0cca64c732f892567d20de8d4c444fa9c1c1adc5e4657ef9740cb69ce55c8f9e6b1cfed0739ef002f1e1c1e54a5df50a759d92354f78eb90a9d9378f36df7d1edd8002ea0d637604fcd2408494c2d42b1771e2a2a20b55044836f76db4ed71e8a53f55a04f9437946603e7246c2d2d70caf6be0de82e8977fab4de84ca3783baedac041195d8b51166b502ff80c17db78f63d3632df1d5ef5b14d8d5553fc40b072030f9e3374c93e929a490c6cfb170f04433fc46f43b9c7d27f3f8c4ed759d4a20c2e53a0701b7c3d9201390a9b5597ce8ba35bd765b662e2242b9821bbb63b6be502d2150fff37e4b7f2a6b592fd0e319a7349df320e7fe7da600a2a05628dc00e04d480c085417f676bd0518bc39d9a9be34fc0cb192d5fa5e0c657cdf7c1ad265a2e81b90ac8b28d326f98b8f33c123df83edc964d2c17a904d0df8bd9ecbf629929d6e48cadc97f49a8941ada3d219e8c0f04f37cecc9a50cc5307fd2a488c34829b05cd1615ae0d1ef0ce450529aa755f9ae38332187ffe4144990de3265afaacb9f0f0fb9c67f6210369f7a0cc5bb346412db08e0f4732f91aa8d4b32fe6eece4fba118f118f6df2fb6c53fa9bc164c9ab7a9d414d33281eb0c3cd02abe0a4dd1c170e41c1c960a8f12a48a7b5e1f748c08e1b150a4e389c110ea3368bc6c6ef2bee98dc92c6825cbf6aee20e690e116c0e6cf48d49b38035f6a9b0cd6053b9f5b9f8360024c9c608cbba3fe5e7966b656fa08dec3e3ce3178a0c0007b7d177c7c44e6a68f4c7325cb98264b1e0f391c75a6a8fd3691581fb68ef459458830f2138d0fd743631efd92b742dfeb62c5ea8502515eb65af414bf805992f9272a7b1b745970fd54e128751f8f6c0a4d5bc7872bc09c04037e1e91dc7192d68f780cdb0f7ef6b282ea883be462ffeffb7b396e30303030", "openwall"}, {"$sxc$*0*0*1024*16*64983af0b26a6ee614e6c65b32c1d906f70c6397*8*259cafe530bd09f8*16*8f53ea878d0795cfe05dcc65fb272c20*1024*1024*ffb0f736b69d8433f958e8f475f609948ad7c9dd052f2b92c14cb1b395ffcac043a3def76d58442e131701b3b53d56ea570633bb20c83068542420160f5db3cee5eece05b67b54d0d4cdf3fbfd928d94852924e391aa3f70cad598b48b946399b0cd1e9e7e7d081a888933f8a1973e83166799396e8290771463c623620b51fb5310b9b0e0de3e5597b66a091301ada3ba6a5d7515d1fcf0eff65e543b50f8fe2222619600054eaf69c7aa680c96bc403f115cab32d6d8e8bc0db3904a71ce3eb1283ca73fd6f75845d9b7d0275e4727a0f56bfbf962a9079f51849de2c9dee7f1dadbbae944f442169281004773309b0f8d68f2cf83076fd8b19afbccf5ab7dc58fb9554fee82e2c491d6434a4cef6f3209775343c840bc4bdfab6705000e67412ac74d00f5b6aba1fd21bca5213234a5a1100a9d93daa141a4936723ea77d008a35c9078167a3529706432b36b9ec012c060d093535c85ca6feb75165d620d7d663c3e76b9bf3af614556ed8560b446a8a73649cb935383a30b4fd8fd75522203e4575cf4bc2b7f01a9294310fe021c71acbf68f6f1e95f48c30c14151c51d4fb878a16272ee73753bc750cbd48007c842412ca1dcb6214215b082c00d619a5318e2ebe9149410f501170093784afc2bd71dd9f5a87b349b96661747b1627e8cba8a5c98559fb146fa7e30db4c6f648ce3c2209f84551a7a1cd46d9172ae1354b6d093f89f6f5f58d29c1d7af8830df62e67753caa8166322caa0f8adf4b61d2013d35baa7c002e1d4c83b1cba8aaa57cf4946627fa63ba7a6a5a5c803e8d5a4794845ab670ef950b918a360cd9f12e8f3424ecab1f505cb494ad35f28d12ff183471d0f47bd67e6abd3b8c8e206d11149474a19b5c13d165d8f6dc39cf579fe1000295328aeeb82e0ae8020d2f61e4c3d6e68c25a655ab72aad5e9e74af4cf27c74158fdb1a29a3d76cd658976fa0a30743247408df00a23b593f68861348a6c46af05d21a4b81fedbf5715462ec8ffc5f001a85c43058ac1fab488236588ef0bf08dd8dd7c7fce630a0a996395b503647d9a2f0dd63dd2f939eca8e1849ee4ed41a6d5672d947177e8f890692de879a20dd9e366ec494d270faf0d24fc076172a25998aac218586404687e7c77b55e77e0eff9b1c65c3f8da99deaa86411ab6aca2531d84b364349591bc73e7504163afd23c5208e321883ee611ea7e4e5885086e4fa7196e16b948cb54808b64b94106c74900e3190fd5f6068b490fd0c9c64481771527a0e2d00899fd5b7a9e7f508cc6770018fadf09d965d7a12ad3624d2161d9546d4a7937b5f961d7f7c4714786380c147e1ec6b0583503bd5a139b892831d1ea925993bb86f12e75d9010ceba230a1c286fa3d1d654a1672313cbf0763c05c622cee452f76957c42ba0e853ecda163d15e8600a702ccdc9e8f88a", "Ghe+t0Blaster"}, {"$sxc$*0*0*1024*16*64983af0b26a6ee614e6c65b32c1d906f70c6397*8*9bb755c8a4fe8c34*16*112b9d41098c8677615755361da473a6*1024*1024*b95f0f2e0e1c7b4ee61168b646804d4b70b615f3c978cec65c9a7ab515417c79625d104373fd5012c3da6b356f8408a3a75edcc8b2aad0aa38bb33edd8933bdadbffde35a350ade73ccb9df29c2996082f5e94e324496835f8dfebe15ca38950e0f435d711ef964aa09915d58287967b5e321ca195a7f90253157afe82329da9a496c97292419b9a94cdb92f919e6d54700466aff61c200c5a355905b5a37c12d77b0e4ffd23f0204cfa664f4c0545f233db8d35af5fe337b459135da398fd23101becb194db305496474ba4179a7355285a9ec935044e1831f290f5f87ed3e00925e7fb4fc6bc38d9f0cfe9abf72560400490d2fd398d2d49516b618f99168602f323dd1786bcca394830341dfbeb377f9b7ef161dc1470f5e92b6152fa7a4f428e8ae40100791491a9e1c9385298522320488f00535866ac6e08354a75b8b2fd293066da7eb6b4ad7f3e13c8dc98cd815b2393f147fdac6279f76fdac9abd0a94131fa84fe4e99634a362a56d60ce588f6e0b66d6f8b6d411511272ffe32181d20e7d2c3d4b680764607afb2c29dcb94a845b920e96f6c27575534f8b7f9ddd93bdcef0d717d0a899fa937e7d2eeeb6d5b0338757f6e69dac72524d4b6f74edce1f937008eb3653bcc31a88712af940cf47ec3f3efd83e4da89d1a6cb7da6cf8d7d41430bc81a4b5d7bb46cad687f2f505e3379143ae274eed6201c3b17c1e05e516a14cbf2351ccf9fdd46e1309afb170bd01eb8f6a1d8e12441525199455fb550e3fc689b1801332b2d985e336b158f846fcbca18fbe6ea21438cf1fb5fdbce8d6350e65d6468342880845675ec721af2fb9df917a3968b4a1a477fc4c74ee38a71a230d77c2a7cf66ae6b83804488cbd25213ebc470cd845a2691b16161a640ebb385aa2381dc91f692f6c4ca2709b5a7e94dfb4548000a29b56f1da08701945d6209fabbd1621b28849fc27810775f1a0e0204d3ae9040a8cfb1386499a39d87149cfc1579de7d059662ad25a67abd42b30bb3608f09142ca030351c3a1e921e4c7bbc11aab846ef42eb5d1418c15ada77539aca096e0678439cd1b60950d2aa0cc4d2004b1ac48dc6a454c5a8e9ea7e910047c7c83895fd614fd9dfd961631eb23757646143c2aeb03c1a6476e78fc4ccf0f02cc1f88ec1b0080a170ac6871dc183939f7a4376965b0dfa7922012582eec4846ee621edc5547a2b9c4893e7f67f76541a4bd4a91827a57b3db5cdea29a2a3cc20238d89c8145c14b037360ad27f54f87317ef70472d6b1fd9f1168bcf8aba6071257b3adebab8d4e115188ed4af3fc3574fdccb4bc7eeb00a6a442f1b96a989b735f5e6059ec72c1677b77f437dcb93066f8591a11071799c3a0ec3b48f6160976aff1928c375358837e1ef02e20397b2e9d8d9c4bff23172c9b4c0b941cb1b49b5bc070f72a14cd384", "M1racl33"}, {"$sxc$*0*0*1024*16*64983af0b26a6ee614e6c65b32c1d906f70c6397*8*ceb1edb1e3cb72fd*16*f7104c9b2789540f5fd4beef009c0139*1024*1024*709130b940a9663d0a5687133c6f78535d05a72936faed8c2f3c1b4e29423baaabcee4f0d7d57e3ad8d8c090486f974c4d0ce4be5b29ef8e1b02c01b4af1959ed0b277146a45aec35a48997b584b82697803193644eefd88a7eefcae8819839e13702f887278a597dd954babd82bf71bf8ca8559af0e5537be0264e358d36b4f5067960edf608de731e04d117de953386aadee71849edbc494fac3e6b14567a9e9c545a06d402acd3158441829f25478ed0f9086dabd2d3913b123b43c27176f8f08f30312d84e82d47654097a2bce95554357db3ce3d45a7441472067f55e4ea6244a3dedc23db4bea8f549109ffac382cf5b652c5b1ee431bcab1051567c263a9d668c5d6a15a6f8da754914746c1d3c7eb6347bdd8d6a3ac82e4c742fcf8721913c111dfd5398f2698db00f7220d2a3562e02f7f7a6505af3ba1ee10b46f2ab5b5d2f52d288fd12814c6edbcb8d50b6e8716fba0d5962747b971689fe75e94fa36ec39598ea30e15ab2b9c9f22ca04b890a13b18fb3c7a962050426bb2da08c8b993608b9c1ffd0a21e0c74e993242ead8eb30f86d7d2dcdbd4774d85c2e06adbe4b40050ff0ac1a8afe8fbc2175ec4da4676a691b1fce38421175734c20f07a604fea5287e1c33b420aa9db4de9bd97382c161b4ec0818add675e52ebf036aad779f24b824be4b2b013c470ff66cbf44f5800e128a3b328e80a5fd6295b9b3a94e915f9add6710cb9444432751a7a31c3a3422f48a5eabc26d9a52571b8447bdd0a5977ff7153d95337cef7ff2ec29774332fbeed6ee5eed5e12288cc13e14ba9d5ff3dd052e28ba96715f5b95d7ea214ebcd9e60b26308eb11370b824b5cff2644dd2117985b3c25ba8076d4025cf3a3a62da62d5e11d44422a142048e8cd00c7de6a0a55fd5dc09a3ed01dfe35b88268f351b6ff289fee8e52ac29fe32d9990e0d6d87f39727b6a762bac9d509c6ea235fc8bedc3bec2143eae9fd2cb831b798ef8261d72785002638b940947de0aad64f791f9a27e5b091e55adf4aee0649f6785bdd37e0248fedd1759d771aeacacb3ff6e7cf2d045f791428ab61710b54e869213393caf1b6bc99066678351deafc290cecc1f6b40b5532adbbab9a70408c61a437d4483b6a75cb61a55b20881efc0d849e0f60c1887f0fa091672179a145c4ab1b6487a0e939e0123d5aaffa3aec66ab593f9c25d27f22f4a73a999a4ab45e8bc7d71a85e2d40afadad1a1dc0b8389f96f91614293fa205583ef1c3440e3df50e8aa5f1a13e5929b72cd003461ff03d44d8c84bdada176b24459021d398b2b91b61a9c0b553a8714c703d32452c691a33f1581e98c2439514ca3e7deeef90850f8d6d89bf1d3a5762a56ef769ea588f5c1705bfb7b944cfbbb0632718ee3722f4e1929b35706d6413a315a11bc16349af109a7e675df2ab1eebe93", "excel123"}, {NULL} }; static cl_int cl_error; static sxc_password *inbuffer; static sxc_hash *outbuffer; static sxc_salt currentsalt; static cl_mem mem_in, mem_out, mem_setting; static struct fmt_main *self; static size_t insize, outsize, settingsize; #define STEP 0 #define SEED 256 // This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" static const char * warn[] = { "xfer: ", ", crypt: ", ", xfer: " }; /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel); } static void create_clobj(size_t gws, struct fmt_main *self) { insize = sizeof(sxc_password) * gws; outsize = sizeof(sxc_hash) * gws; settingsize = sizeof(sxc_salt); inbuffer = mem_calloc(1, insize); outbuffer = mem_alloc(outsize); saved_key = mem_calloc(gws, sizeof(*saved_key)); crypt_out = mem_calloc(gws, sizeof(*crypt_out)); /// Allocate memory mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem in"); mem_setting = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem setting"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem out"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting), &mem_setting), "Error while setting mem_salt kernel argument"); } static void release_clobj(void) { if (crypt_out) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(inbuffer); MEM_FREE(outbuffer); MEM_FREE(saved_key); MEM_FREE(crypt_out); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { self = _self; opencl_prepare_dev(gpu_id); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; snprintf(build_opts, sizeof(build_opts), "-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d", (int)sizeof(inbuffer->v), (int)sizeof(currentsalt.salt), (int)sizeof(outbuffer->v)); opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl", gpu_id, build_opts); crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self, create_clobj, release_clobj, sizeof(sxc_password), 0, db); // Auto tune execution from shared/included code. autotune_run(self, 1, 0, 1000); } } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy; char *keeptr; char *p; int res, extra; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += FORMAT_TAG_LEN; if ((p = strtokm(ctcopy, "*")) == NULL) /* cipher type */ goto err; res = atoi(p); if (res != 0 && res != 1) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* checksum type */ goto err; res = atoi(p); if (res != 0 && res != 1) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iterations */ goto err; res = atoi(p); if (res <= 0) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* key size */ goto err; res = atoi(p); if (res != 16 && res != 32) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* checksum field (skipped) */ goto err; if (hexlenl(p, &extra) != BINARY_SIZE * 2 || extra) goto err; if (!ishex(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iv length */ goto err; res = atoi(p); if (res <= 0 || res > 16) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iv */ goto err; if (hexlenl(p, &extra) != res * 2 || extra) goto err; if (!ishex(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* salt length */ goto err; res = atoi(p); if (res <= 0 || res > 32) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* salt */ goto err; if (hexlenl(p, &extra) != res * 2 || extra) goto err; if (!ishex(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* original length */ goto err; res = atoi(p); if (res <= 0 || res > 1024) /* 1024 because of "unsigned char output[1024];" in crypt_all */ goto err; if ((p = strtokm(NULL, "*")) == NULL) /* length */ goto err; res = atoi(p); if (res <= 0 || res > 1024) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* content */ goto err; if (hexlenl(p, &extra) != res * 2 || extra) goto err; if (strtokm(NULL, "*") != NULL) /* the end */ goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; static sxc_cpu_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += 6; /* skip over "$sxc$*" */ p = strtokm(ctcopy, "*"); cs.cipher_type = atoi(p); p = strtokm(NULL, "*"); cs.checksum_type = atoi(p); p = strtokm(NULL, "*"); cs.iterations = atoi(p); p = strtokm(NULL, "*"); cs.key_size = atoi(p); strtokm(NULL, "*"); /* skip checksum field */ p = strtokm(NULL, "*"); cs.iv_length = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.iv_length; i++) cs.iv[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.salt_length = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.salt_length; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.original_length = atoi(p); p = strtokm(NULL, "*"); cs.length = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.length; i++) cs.content[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE+1]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; ctcopy += FORMAT_TAG_LEN; /* skip over "$sxc$*" */ strtokm(ctcopy, "*"); strtokm(NULL, "*"); strtokm(NULL, "*"); strtokm(NULL, "*"); p = strtokm(NULL, "*"); for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } MEM_FREE(keeptr); return out; } static void set_salt(void *salt) { cur_salt = (sxc_cpu_salt*)salt; memcpy((char*)currentsalt.salt, cur_salt->salt, cur_salt->salt_length); currentsalt.length = cur_salt->salt_length; currentsalt.iterations = cur_salt->iterations; currentsalt.outlen = cur_salt->key_size; currentsalt.skip_bytes = 0; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting, CL_FALSE, 0, settingsize, &currentsalt, 0, NULL, NULL), "Copy salt to gpu"); } #undef set_key static void set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size); #ifdef _OPENMP #pragma omp parallel for #endif for(index = 0; index < count; index++) { unsigned char hash[20]; SHA_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, (unsigned char *)saved_key[index], strlen(saved_key[index])); SHA1_Final((unsigned char *)hash, &ctx); memcpy(inbuffer[index].v, hash, 20); inbuffer[index].length = 20; } /// Copy data to gpu BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); /// Run kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run kernel"); /// Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back"); if (ocl_autotune_running) return count; #ifdef _OPENMP #pragma omp parallel for #endif for(index = 0; index < count; index++) { BF_KEY bf_key; SHA_CTX ctx; int bf_ivec_pos; unsigned char ivec[8]; unsigned char output[1024]; bf_ivec_pos = 0; memcpy(ivec, cur_salt->iv, 8); BF_set_key(&bf_key, cur_salt->key_size, (const unsigned char*)outbuffer[index].v); BF_cfb64_encrypt(cur_salt->content, output, cur_salt->length, &bf_key, ivec, &bf_ivec_pos, 0); SHA1_Init(&ctx); SHA1_Update(&ctx, output, cur_salt->original_length); SHA1_Final((unsigned char*)crypt_out[index], &ctx); } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static unsigned int iteration_count(void *salt) { sxc_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->iterations; } struct fmt_main fmt_opencl_sxc = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { "iteration count", }, { FORMAT_TAG }, sxc_tests }, { init, done, reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash /* Not usable with $SOURCE_HASH$ */ }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash /* Not usable with $SOURCE_HASH$ */ }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
deconvolution_4x4.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void deconv4x4s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q = 0; q < inch; q++) { const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch * 16 + q * 16; const float* r0 = img0; const float* k0 = kernel0; const float* k1 = kernel0 + 4; const float* k2 = kernel0 + 8; const float* k3 = kernel0 + 12; #if __ARM_NEON float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); #endif // __ARM_NEON for (int i = 0; i < h; i++) { float* outptr = out.row(i); float* outptr0 = outptr; float* outptr1 = outptr0 + outw; float* outptr2 = outptr1 + outw; float* outptr3 = outptr2 + outw; int j = 0; #if __ARM_NEON for (; j + 3 < w; j += 4) { float32x4_t _v = vld1q_f32(r0); // float32x4_t _out00 = vld1q_f32(outptr0 + 0); _out00 = vmlaq_lane_f32(_out00, _v, vget_low_f32(_k0), 0); vst1q_f32(outptr0 + 0, _out00); float32x4_t _out01 = vld1q_f32(outptr0 + 1); _out01 = vmlaq_lane_f32(_out01, _v, vget_low_f32(_k0), 1); vst1q_f32(outptr0 + 1, _out01); float32x4_t _out02 = vld1q_f32(outptr0 + 2); _out02 = vmlaq_lane_f32(_out02, _v, vget_high_f32(_k0), 0); vst1q_f32(outptr0 + 2, _out02); float32x4_t _out03 = vld1q_f32(outptr0 + 3); _out03 = vmlaq_lane_f32(_out03, _v, vget_high_f32(_k0), 1); vst1q_f32(outptr0 + 3, _out03); // float32x4_t _out10 = vld1q_f32(outptr1 + 0); _out10 = vmlaq_lane_f32(_out10, _v, vget_low_f32(_k1), 0); vst1q_f32(outptr1 + 0, _out10); float32x4_t _out11 = vld1q_f32(outptr1 + 1); _out11 = vmlaq_lane_f32(_out11, _v, vget_low_f32(_k1), 1); vst1q_f32(outptr1 + 1, _out11); float32x4_t _out12 = vld1q_f32(outptr1 + 2); _out12 = vmlaq_lane_f32(_out12, _v, vget_high_f32(_k1), 0); vst1q_f32(outptr1 + 2, _out12); float32x4_t _out13 = vld1q_f32(outptr1 + 3); _out13 = vmlaq_lane_f32(_out13, _v, vget_high_f32(_k1), 1); vst1q_f32(outptr1 + 3, _out13); // float32x4_t _out20 = vld1q_f32(outptr2 + 0); _out20 = vmlaq_lane_f32(_out20, _v, vget_low_f32(_k2), 0); vst1q_f32(outptr2 + 0, _out20); float32x4_t _out21 = vld1q_f32(outptr2 + 1); _out21 = vmlaq_lane_f32(_out21, _v, vget_low_f32(_k2), 1); vst1q_f32(outptr2 + 1, _out21); float32x4_t _out22 = vld1q_f32(outptr2 + 2); _out22 = vmlaq_lane_f32(_out22, _v, vget_high_f32(_k2), 0); vst1q_f32(outptr2 + 2, _out22); float32x4_t _out23 = vld1q_f32(outptr2 + 3); _out23 = vmlaq_lane_f32(_out23, _v, vget_high_f32(_k2), 1); vst1q_f32(outptr2 + 3, _out23); // float32x4_t _out30 = vld1q_f32(outptr3 + 0); _out30 = vmlaq_lane_f32(_out30, _v, vget_low_f32(_k3), 0); vst1q_f32(outptr3 + 0, _out30); float32x4_t _out31 = vld1q_f32(outptr3 + 1); _out31 = vmlaq_lane_f32(_out31, _v, vget_low_f32(_k3), 1); vst1q_f32(outptr3 + 1, _out31); float32x4_t _out32 = vld1q_f32(outptr3 + 2); _out32 = vmlaq_lane_f32(_out32, _v, vget_high_f32(_k3), 0); vst1q_f32(outptr3 + 2, _out32); float32x4_t _out33 = vld1q_f32(outptr3 + 3); _out33 = vmlaq_lane_f32(_out33, _v, vget_high_f32(_k3), 1); vst1q_f32(outptr3 + 3, _out33); r0 += 4; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } #endif // __ARM_NEON for (; j < w; j++) { float val = r0[0]; outptr0[0] += val * k0[0]; outptr0[1] += val * k0[1]; outptr0[2] += val * k0[2]; outptr0[3] += val * k0[3]; outptr1[0] += val * k1[0]; outptr1[1] += val * k1[1]; outptr1[2] += val * k1[2]; outptr1[3] += val * k1[3]; outptr2[0] += val * k2[0]; outptr2[1] += val * k2[1]; outptr2[2] += val * k2[2]; outptr2[3] += val * k2[3]; outptr3[0] += val * k3[0]; outptr3[1] += val * k3[1]; outptr3[2] += val * k3[2]; outptr3[3] += val * k3[3]; r0++; outptr0++; outptr1++; outptr2++; outptr3++; } } } } } static void deconv4x4s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q = 0; q < inch; q++) { const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch * 16 + q * 16; const float* r0 = img0; const float* k0 = kernel0; const float* k1 = kernel0 + 4; const float* k2 = kernel0 + 8; const float* k3 = kernel0 + 12; #if __ARM_NEON float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); #endif // __ARM_NEON for (int i = 0; i < h; i++) { float* outptr = out.row(i * 2); float* outptr0 = outptr; float* outptr1 = outptr0 + outw; float* outptr2 = outptr1 + outw; float* outptr3 = outptr2 + outw; int j = 0; #if __ARM_NEON for (; j + 3 < w; j += 4) { float32x4_t _v = vld1q_f32(r0); // row 0 float32x4x2_t _out0 = vld2q_f32(outptr0); // 0,2,4,6 _out0.val[0] = vmlaq_lane_f32(_out0.val[0], _v, vget_low_f32(_k0), 0); // 1,3,5,7 _out0.val[1] = vmlaq_lane_f32(_out0.val[1], _v, vget_low_f32(_k0), 1); vst2q_f32(outptr0, _out0); _out0 = vld2q_f32(outptr0 + 2); // 2,4,6,8 _out0.val[0] = vmlaq_lane_f32(_out0.val[0], _v, vget_high_f32(_k0), 0); // 3,5,7,9 _out0.val[1] = vmlaq_lane_f32(_out0.val[1], _v, vget_high_f32(_k0), 1); vst2q_f32(outptr0 + 2, _out0); // row 1 float32x4x2_t _out1 = vld2q_f32(outptr1); // 0,2,4,6 _out1.val[0] = vmlaq_lane_f32(_out1.val[0], _v, vget_low_f32(_k1), 0); // 1,3,5,7 _out1.val[1] = vmlaq_lane_f32(_out1.val[1], _v, vget_low_f32(_k1), 1); vst2q_f32(outptr1, _out1); _out1 = vld2q_f32(outptr1 + 2); // 2,4,6,8 _out1.val[0] = vmlaq_lane_f32(_out1.val[0], _v, vget_high_f32(_k1), 0); // 3,5,7,9 _out1.val[1] = vmlaq_lane_f32(_out1.val[1], _v, vget_high_f32(_k1), 1); vst2q_f32(outptr1 + 2, _out1); // row 2 float32x4x2_t _out2 = vld2q_f32(outptr2); _out2.val[0] = vmlaq_lane_f32(_out2.val[0], _v, vget_low_f32(_k2), 0); _out2.val[1] = vmlaq_lane_f32(_out2.val[1], _v, vget_low_f32(_k2), 1); vst2q_f32(outptr2, _out2); _out2 = vld2q_f32(outptr2 + 2); _out2.val[0] = vmlaq_lane_f32(_out2.val[0], _v, vget_high_f32(_k2), 0); _out2.val[1] = vmlaq_lane_f32(_out2.val[1], _v, vget_high_f32(_k2), 1); vst2q_f32(outptr2 + 2, _out2); // row 3 float32x4x2_t _out3 = vld2q_f32(outptr3); _out3.val[0] = vmlaq_lane_f32(_out3.val[0], _v, vget_low_f32(_k3), 0); _out3.val[1] = vmlaq_lane_f32(_out3.val[1], _v, vget_low_f32(_k3), 1); vst2q_f32(outptr3, _out3); _out3 = vld2q_f32(outptr3 + 2); _out3.val[0] = vmlaq_lane_f32(_out3.val[0], _v, vget_high_f32(_k3), 0); _out3.val[1] = vmlaq_lane_f32(_out3.val[1], _v, vget_high_f32(_k3), 1); vst2q_f32(outptr3 + 2, _out3); r0 += 4; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; } #endif // __ARM_NEON for (; j < w; j++) { float val = r0[0]; outptr0[0] += val * k0[0]; outptr0[1] += val * k0[1]; outptr0[2] += val * k0[2]; outptr0[3] += val * k0[3]; outptr1[0] += val * k1[0]; outptr1[1] += val * k1[1]; outptr1[2] += val * k1[2]; outptr1[3] += val * k1[3]; outptr2[0] += val * k2[0]; outptr2[1] += val * k2[1]; outptr2[2] += val * k2[2]; outptr2[3] += val * k2[3]; outptr3[0] += val * k3[0]; outptr3[1] += val * k3[1]; outptr3[2] += val * k3[2]; outptr3[3] += val * k3[3]; r0++; outptr0 += 2; outptr1 += 2; outptr2 += 2; outptr3 += 2; } } } } }
block_map.h
/* The main differences of block_multimap from unordered_multimap are: 1) Block oriented methods (e.g., insert, equal_range, find) have been added that operate on arrays of elements. 2) A maximum number of elements per key can be specified with MAX_ELEM. 3) USE_ACC Only: Values are stored in result arrays without being paired with keys. Hence, equal_range() returns a mapped_type pointer instead of a pair of iterators. The first mapped_type entry is a count of values that follow. */ #ifndef _BLOCK_MAP_H #define _BLOCK_MAP_H #include <cstddef> // size_t #include <utility> // std::pair #define MAX_ELEM 7 // comment out for performance testing #if defined(USE_ACC) #define CHUNK_SZ 4 #include "KVstore.hpp" /* these are global to avoid overhead at runtime on the stack */ tick_t tA, tB, tC, tD; unsigned long long tsetup, tfill, tdrain, tcache; /* * * * * * * * * * Map, Accelerator * * * * * * * * * */ // See C:\cygwin\lib\gcc\i686-pc-cygwin\5.4.0\include\c++\bits\hashtable_policy.h:300,1420 template<class _Key, class _Tp> struct clocal_iterator { typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair<const key_type, mapped_type> value_type; typedef const value_type* const_pointer; typedef typename KVstore<key_type, mapped_type>::slot_s slot_s; slot_s *slot; std::pair<_Key, _Tp> val; inline void update_val(void) { if (slot == nullptr) return; if (slot->probes == 0) { slot = nullptr; return; } val.first = slot->key; val.second = slot->value; } clocal_iterator() noexcept : slot(nullptr) { } explicit clocal_iterator(slot_s *__p) noexcept : slot(__p) { update_val(); } const_pointer operator->() const noexcept { if (slot == nullptr) return nullptr; return reinterpret_cast<const_pointer>(&val); } clocal_iterator operator++(int) noexcept { clocal_iterator __tmp(*this); slot = nullptr; return __tmp; } }; // See C:\cygwin\lib\gcc\i686-pc-cygwin\5.4.0\include\c++\bits\hashtable_policy.h:315,1497 template<class _Key, class _Tp> inline bool operator==( const clocal_iterator<_Key, _Tp>& __x, const clocal_iterator<_Key, _Tp>& __y) { return __x.slot == __y.slot; } template<class _Key, class _Tp> //, // class _Hash = hash<_Key>, // class _Pred = std::equal_to<_Key>, // class _Alloc = std::allocator<std::pair<const _Key, _Tp> > class block_map { public: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair<const key_type, mapped_type> value_type; // typedef _Hash hasher; // typedef _Pred key_equal; // typedef _Alloc allocator_type; // iterator-related typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef value_type* iterator; typedef const value_type* const_iterator; typedef value_type* local_iterator; // typedef const value_type* const_local_iterator; // See C:\cygwin\lib\gcc\i686-pc-cygwin\5.4.0\include\c++\bits\hashtable_policy.h:1679 using const_local_iterator = clocal_iterator<key_type, mapped_type>; typedef size_t size_type; typedef ptrdiff_t difference_type; KVstore<key_type, mapped_type> acc; // Key-Value Accelerator typedef typename KVstore<key_type, mapped_type>::slot_s slot_s; size_type count(const key_type& __x) // const { slot_s *slot = acc._search(__x); return (slot) ? 1 : 0; } size_type bucket_size(size_type __n) const { slot_s *slot = acc.data_base + __n; return (slot->probes) ? 1 : 0; } const_local_iterator cbegin(size_type __n) const { slot_s *slot = acc.data_base + __n; return const_local_iterator(slot); } const_local_iterator cend(size_type __n) const { return const_local_iterator(nullptr); } iterator end() noexcept { return iterator(nullptr); } inline std::pair<iterator, bool> insert(const value_type& __x) // returns true if new { acc._put(__x.first, __x.second); // FIXME: figure how to return iterator when // entire value_type is not stored in container // or just return mapped_type pointer? return std::make_pair(nullptr, false); } #if 1 // begin insert void insert(const_pointer __arr, size_type __n) { #if 0 && defined(USE_STREAM) && defined(__ARM_ARCH) mtcp(XREG_CP15_CACHE_SIZE_SEL, 0); #endif // end USE_STREAM && __ARM_ARCH while (__n--) insert(*__arr++); #if 0 && defined(USE_STREAM) && defined(__ARM_ARCH) dsb(); // tget(tA); // acc.cache_flush(); // tget(tB); // tinc(tcache, tdiff(tB,tA)); #endif // end USE_STREAM && __ARM_ARCH } #else // else insert // TODO: version with drain only, modify args to drain(kvpair)? // NOTE: Be careful of overlapping probes even when keys are sorted. // Probes will need to be tested for overlap to prevent a hazard. void insert(const_pointer __arr, size_type __n) { tget(tA); std::sort(__arr, __arr+__n); // uses combination of quicksort, heapsort, and insertion sort tget(tB); CACHE_SEND(acc, __arr, sizeof(value_type)*__n); tget(tC); acc.fill(value, __n, __arr, sizeof(value_type)); tget(tD); CACHE_RECV(acc, value, sizeof(mapped_type)*__n); tget(tE); } #endif // end insert inline mapped_type* equal_range(const key_type& __x) // returns nullptr if no match { return nullptr; } void equal_range( mapped_type** __rng, const key_type* __x, size_type __n) { while (__n--) *__rng++ = equal_range(*__x++); } inline mapped_type find(const key_type& __x) // returns zero if no match { mapped_type __v; acc._get(__x, __v); return __v; } #if 0 // begin find void find(mapped_type* __fnd, const key_type* __x, size_type __n) { while (__n--) *__fnd++ = find(*__x++); } #else // else find void find(mapped_type* __fnd, const key_type* __x, size_type __n) { tget(tA); CACHE_SEND(acc, __x, sizeof(key_type)*__n); tget(tB); acc.fill(__fnd, __n, __x, sizeof(key_type)); tget(tC); CACHE_RECV(acc, __fnd, sizeof(mapped_type)*__n); tget(tD); tinc(tcache, tdiff(tB,tA) + tdiff(tD,tC)); tinc(tfill, tdiff(tC,tB)); } #endif // end find size_type erase(const key_type& __k) { return 0; /* TODO: */ } inline size_type size() const noexcept { return acc.elements; } inline size_type bucket_count() const noexcept { // acc.topsearch needed to iterate through all buckets return acc.data_len + acc.topsearch - 1; } inline float load_factor() const noexcept { return static_cast<float>(size()) / static_cast<float>(bucket_count()); } void reserve(size_type __n) { acc.setup(__n); } // * * * * * * * * * * non-standard methods * * * * * * * * * * // void print_stats(void) { typedef unsigned long ul_t; printf("table addr: %p\n", acc.data_base); printf("table size: %lu\n", (ul_t)acc.data_len*sizeof(slot_s)); printf("size: %lu\n", (ul_t)size()); printf("load_factor (elem): %f\n", load_factor()); printf("bucket_count: %lu\n", (ul_t)bucket_count()); printf("max_psl: %lu\n", (ul_t)acc.topsearch); #if defined(PSL_HISTO) { unsigned *hbin = (unsigned *)malloc(sizeof(unsigned)*acc.topsearch); acc.psl_histo(hbin); printf("PSL Count\n"); for (unsigned i = 0; i < acc.topsearch; i++) { printf("%u %u\n", i+1, hbin[i]); } printf("PSL End\n"); free(hbin); } #endif // end PSL_HISTO #if defined(SPILL) printf("spill size: %lu\n", (ul_t)acc.spill.size()); #endif // end SPILL } void clear_time(void) { tsetup = tfill = tdrain = tcache = 0; } void print_time(void) { printf(" Fill time: %f sec\n", tvesec(tfill)); printf(" Drain time: %f sec\n", tvesec(tdrain)); printf(" Cache time: %f sec\n", tvesec(tcache)); } }; // class block_map /* * * * * * * * * * MultiMap, Accelerator * * * * * * * * * */ template<class _Key, class _Tp> struct clocal_iterator_mm { typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair<const key_type, mapped_type> value_type; typedef const value_type* const_pointer; typedef typename KVstore<key_type, mapped_type*>::slot_s slot_s; slot_s *slot; unsigned idx; std::pair<_Key, _Tp> val; inline void update_val(void) { if (slot == nullptr) return; if (slot->probes == 0 || slot->value == nullptr || idx > slot->value[0]) { slot = nullptr; return; } val.first = slot->key; val.second = slot->value[idx]; } clocal_iterator_mm() noexcept : slot(nullptr), idx(0) { } explicit clocal_iterator_mm(slot_s *__p) noexcept : slot(__p), idx(1) { update_val(); } const_pointer operator->() const noexcept { if (slot == nullptr) return nullptr; return reinterpret_cast<const_pointer>(&val); } clocal_iterator_mm operator++(int) noexcept { clocal_iterator_mm __tmp(*this); if (slot != nullptr) { idx++; update_val(); } return __tmp; } }; template<class _Key, class _Tp> inline bool operator==( const clocal_iterator_mm<_Key, _Tp>& __x, const clocal_iterator_mm<_Key, _Tp>& __y) { return __x.slot == __y.slot; } template<class _Key, class _Tp> //, // class _Hash = hash<_Key>, // class _Pred = std::equal_to<_Key>, // class _Alloc = std::allocator<std::pair<const _Key, _Tp> > class block_multimap { public: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair<const key_type, mapped_type> value_type; // typedef _Hash hasher; // typedef _Pred key_equal; // typedef _Alloc allocator_type; // iterator-related typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef value_type* iterator; typedef const value_type* const_iterator; typedef value_type* local_iterator; // typedef const value_type* const_local_iterator; using const_local_iterator = clocal_iterator_mm<key_type, mapped_type>; typedef size_t size_type; typedef ptrdiff_t difference_type; size_type element_count; // total number of elements in container size_type maxelem; // maximum number of elements per key KVstore<key_type, mapped_type*> acc; // Key-Value Accelerator typedef typename KVstore<key_type, mapped_type*>::slot_s slot_s; size_type count(const key_type& __x) // const { slot_s *slot = acc._search(__x); return (slot && slot->value) ? slot->value[0] : 0; } size_type bucket_size(size_type __n) const { slot_s *slot = acc.data_base + __n; return (slot->probes && slot->value) ? slot->value[0] : 0; } const_local_iterator cbegin(size_type __n) const { slot_s *slot = acc.data_base + __n; return const_local_iterator(slot); } const_local_iterator cend(size_type __n) const { return const_local_iterator(nullptr); } iterator end() noexcept { return iterator(nullptr); } iterator insert(const value_type& __x) // returns no indication if new { mapped_type *mptr = nullptr; slot_s *slot; slot = acc._update1(__x.first, mptr); // tget(tA); if (mptr == acc.null_value) { mptr = (mapped_type *)malloc(sizeof(mapped_type)*CHUNK_SZ); // chk_alloc(mptr, sizeof(mapped_type)*CHUNK_SZ, "malloc in insert()"); mptr[0] = 1; if (maxelem < 1) maxelem = 1; mptr[1] = __x.second; } else { if (++mptr[0] > maxelem) maxelem = mptr[0]; if (mptr[0] <= MAX_ELEM) { if (mptr[0] % CHUNK_SZ == 0) { unsigned chunks = mptr[0] / CHUNK_SZ; mptr = (mapped_type *)realloc(mptr, sizeof(mapped_type)*CHUNK_SZ*(chunks+1)); // chk_alloc(mptr, sizeof(mapped_type)*CHUNK_SZ*(chunks+1), "realloc in insert()"); } mptr[mptr[0]] = __x.second; } } element_count++; // tget(tB); acc._update2(slot, mptr); // tinc(tupdate, tdiff(tB,tA)); // FIXME: figure how to return iterator when // entire value_type is not stored in container // or just return mptr. return end(); } #if 1 // begin insert void insert(const_pointer __arr, size_type __n) { #if 0 && defined(USE_STREAM) && defined(__ARM_ARCH) mtcp(XREG_CP15_CACHE_SIZE_SEL, 0); #endif // end USE_STREAM && __ARM_ARCH while (__n--) insert(*__arr++); #if 0 && defined(USE_STREAM) && defined(__ARM_ARCH) dsb(); // tget(tA); // acc.cache_flush(); // tget(tB); // tinc(tcache, tdiff(tB,tA)); #endif // end USE_STREAM && __ARM_ARCH } #else // else insert // NOTE: Be careful of overlapping probes even when keys are sorted. // Probes will need to be tested for overlap to prevent a hazard. void insert(const_pointer __arr, size_type __n) { tget(tA); std::sort(__arr, __arr+__n); // uses combination of quicksort, heapsort, and insertion sort tget(tB); CACHE_SEND(acc, __arr, sizeof(value_type)*__n); tget(tC); acc.fill(value, __n, __arr, sizeof(value_type)); tget(tD); CACHE_RECV(acc, value, sizeof(mapped_type*)*__n); tget(tE); } #endif // end insert inline mapped_type* equal_range(const key_type& __x) // returns nullptr if no match { mapped_type* mptr; acc._get(__x, mptr); return mptr; } #if 0 // begin equal_range void equal_range( mapped_type** __rng, const key_type* __x, size_type __n) { while (__n--) *__rng++ = equal_range(*__x++); } #else // else equal_range void equal_range( mapped_type** __rng, const key_type* __x, size_type __n) { tget(tA); CACHE_SEND(acc, __x, sizeof(key_type)*__n); tget(tB); acc.fill(__rng, __n, __x, sizeof(key_type)); tget(tC); CACHE_RECV(acc, __rng, sizeof(mapped_type*)*__n); tget(tD); tinc(tcache, tdiff(tB,tA) + tdiff(tD,tC)); tinc(tfill, tdiff(tC,tB)); } #endif // end equal_range iterator find(const key_type& __x) // returns end if no match { return end(); /* TODO: */ } void find(iterator* __fnd, const key_type* __x, size_type __n) { while (__n--) *__fnd++ = find(*__x++); } size_type erase(const key_type& __k) { return 0; /* TODO: */ } inline size_type size() const noexcept { return element_count; } inline size_type bucket_count() const noexcept { // acc.topsearch needed to iterate through all buckets return acc.data_len + acc.topsearch - 1; } inline float load_factor() const noexcept { return static_cast<float>(size()) / static_cast<float>(bucket_count()); } void reserve(size_type __n) { acc.setup(__n); } // * * * * * * * * * * non-standard methods * * * * * * * * * * // void print_stats(void) { typedef unsigned long ul_t; printf("table addr: %p\n", acc.data_base); printf("table size: %lu\n", (ul_t)acc.data_len*sizeof(slot_s)); printf("size: %lu unique: %lu duplicates: %lu %.2f%%\n", (ul_t)size(), (ul_t)acc.elements, (ul_t)(size()-acc.elements), (double)(size()-acc.elements)/size()*100.0); printf("load_factor (elem): %f\n", load_factor()); printf("load_factor (keys): %f\n", (double)acc.elements/bucket_count()); printf("bucket_count: %lu\n", (ul_t)bucket_count()); printf("max_elem_per_key: %lu\n", (ul_t)maxelem); printf("max_psl: %lu\n", (ul_t)acc.topsearch); } void clear_time(void) { tsetup = tfill = tdrain = tcache = 0; } void print_time(void) { printf(" Fill time: %f sec\n", tvesec(tfill)); printf(" Drain time: %f sec\n", tvesec(tdrain)); printf(" Cache time: %f sec\n", tvesec(tcache)); } }; // class block_multimap #else // not USE_ACC #include <unordered_map> /* * * * * * * * * * Map, Standard * * * * * * * * * */ template<class _Key, class _Tp> //, // class _Hash = hash<_Key>, // class _Pred = std::equal_to<_Key>, // class _Alloc = std::allocator<std::pair<const _Key, _Tp> > class block_map : public std::unordered_map<_Key, _Tp> { private: using base_map = std::unordered_map<_Key, _Tp>; public: typedef typename base_map::key_type key_type; typedef typename base_map::mapped_type mapped_type; typedef typename base_map::value_type value_type; // typedef typename base_map::hasher hasher; // typedef typename base_map::key_equal key_equal; // typedef typename base_map::allocator_type allocator_type; // iterator-related typedef typename base_map::pointer pointer; typedef typename base_map::const_pointer const_pointer; typedef typename base_map::reference reference; typedef typename base_map::const_reference const_reference; typedef typename base_map::iterator iterator; typedef typename base_map::const_iterator const_iterator; typedef typename base_map::local_iterator local_iterator; typedef typename base_map::const_local_iterator const_local_iterator; typedef typename base_map::size_type size_type; typedef typename base_map::difference_type difference_type; // TODO: other insert, erase methods inline std::pair<iterator, bool> insert(const value_type& __x) // returns true if new { return base_map::insert(__x); } void insert(const_pointer __arr, size_type __n) { while (__n--) this->insert(*__arr++); } inline std::pair<iterator, iterator> equal_range(const key_type& __x) // returns {end, end} if no match { return base_map::equal_range(__x); } void equal_range( std::pair<iterator, iterator>* __rng, const key_type* __x, size_type __n) { while (__n--) *__rng++ = this->equal_range(*__x++); } #if 0 // begin find inline iterator find(const key_type& __x) // returns end if no match { return base_map::find(__x); } void find(iterator* __fnd, const key_type* __x, size_type __n) { while (__n--) *__fnd++ = this->find(*__x++); } #else // else find inline mapped_type find(const key_type& __x) // returns zero if no match { iterator __it = base_map::find(__x); if (__it == base_map::end()) return 0; return __it->second; } void find(mapped_type* __fnd, const key_type* __x, size_type __n) { #if defined(_OPENMP) #pragma omp parallel for for (size_type i = 0; i < __n; i++) __fnd[i] = this->find(__x[i]); #else // not _OPENMP while (__n--) *__fnd++ = this->find(*__x++); #endif // end _OPENMP } #endif // end find // * * * * * * * * * * non-standard methods * * * * * * * * * * // void print_stats(void) { typedef unsigned long ul_t; size_type max_elem_per_bucket = 0; // gather stats in one pass through table for (size_type i = 0; i < this->bucket_count(); ++i) { size_type bkt_sz = this->bucket_size(i); if (bkt_sz > max_elem_per_bucket) max_elem_per_bucket = bkt_sz; } printf("size: %lu\n", (ul_t)this->size()); printf("load_factor (elem): %f\n", this->load_factor()); printf("bucket_count: %lu\n", (ul_t)this->bucket_count()); printf("max_elem_per_bucket: %lu\n", (ul_t)max_elem_per_bucket); } void clear_time(void) { } void print_time(void) { } }; // class block_map /* * * * * * * * * * MultiMap, Standard * * * * * * * * * */ template<class _Key, class _Tp> //, // class _Hash = hash<_Key>, // class _Pred = std::equal_to<_Key>, // class _Alloc = std::allocator<std::pair<const _Key, _Tp> > class block_multimap : public std::unordered_multimap<_Key, _Tp> { private: using base_map = std::unordered_multimap<_Key, _Tp>; typename base_map::size_type element_count; public: typedef typename base_map::key_type key_type; typedef typename base_map::mapped_type mapped_type; typedef typename base_map::value_type value_type; // typedef typename base_map::hasher hasher; // typedef typename base_map::key_equal key_equal; // typedef typename base_map::allocator_type allocator_type; // iterator-related typedef typename base_map::pointer pointer; typedef typename base_map::const_pointer const_pointer; typedef typename base_map::reference reference; typedef typename base_map::const_reference const_reference; typedef typename base_map::iterator iterator; typedef typename base_map::const_iterator const_iterator; typedef typename base_map::local_iterator local_iterator; typedef typename base_map::const_local_iterator const_local_iterator; typedef typename base_map::size_type size_type; typedef typename base_map::difference_type difference_type; // TODO: other insert, erase methods #if defined(MAX_ELEM) // limit number of stored elements per key iterator insert(const value_type& __x) // returns no indication if new { element_count++; if (base_map::count(__x.first) < MAX_ELEM) return base_map::insert(__x); return base_map::end(); } size_type erase(const key_type& __k) { element_count--; return base_map::erase(__k); } size_type size() const noexcept { return element_count; } float load_factor() const noexcept { return static_cast<float>(element_count) / static_cast<float>(base_map::bucket_count()); } #else // not MAX_ELEM inline iterator insert(const value_type& __x) // returns no indication if new { return base_map::insert(__x); } #endif // end MAX_ELEM void insert(const_pointer __arr, size_type __n) { while (__n--) this->insert(*__arr++); } inline std::pair<iterator, iterator> equal_range(const key_type& __x) // returns {end, end} if no match { return base_map::equal_range(__x); } void equal_range( std::pair<iterator, iterator>* __rng, const key_type* __x, size_type __n) { #if defined(_OPENMP) #pragma omp parallel for for (size_type i = 0; i < __n; i++) __rng[i] = this->equal_range(__x[i]); #else // not _OPENMP while (__n--) *__rng++ = this->equal_range(*__x++); #endif // end _OPENMP } inline iterator find(const key_type& __x) // returns end if no match { return base_map::find(__x); } void find(iterator* __fnd, const key_type* __x, size_type __n) { while (__n--) *__fnd++ = this->find(*__x++); } // * * * * * * * * * * non-standard methods * * * * * * * * * * // void print_stats(void) { typedef unsigned long ul_t; size_type max_elem_per_bucket = 0; size_type max_elem_per_key = 0; size_type max_psl = 0; // max probe sequence length size_type keycnt = 0; // key count // gather stats in one pass through table std::unordered_map<key_type,size_type> epkcnt; // elem per key count for (size_type i = 0; i < this->bucket_count(); ++i) { size_type psl = 0; // probe sequence length size_type bkt_sz = this->bucket_size(i); if (bkt_sz > max_elem_per_bucket) max_elem_per_bucket = bkt_sz; epkcnt.clear(); for (auto local_it = this->cbegin(i); local_it != this->cend(i); ++local_it) { psl++; if (++epkcnt[local_it->first] == 1 && psl > max_psl) max_psl = psl; } for (auto& x: epkcnt) { if (x.second > max_elem_per_key) { max_elem_per_key = x.second; } } keycnt += epkcnt.size(); } printf("size: %lu unique: %lu duplicates: %lu %.2f%%\n", (ul_t)this->size(), (ul_t)keycnt, (ul_t)(this->size()-keycnt), (double)(this->size()-keycnt)/this->size()*100.0); printf("load_factor (elem): %f\n", this->load_factor()); printf("load_factor (keys): %f\n", (double)keycnt/this->bucket_count()); printf("bucket_count: %lu\n", (ul_t)this->bucket_count()); printf("max_elem_per_bucket: %lu\n", (ul_t)max_elem_per_bucket); printf("max_elem_per_key: %lu\n", (ul_t)max_elem_per_key); printf("max_psl: %lu\n", (ul_t)max_psl); } void clear_time(void) { } void print_time(void) { } }; // class block_multimap #endif // end USE_ACC #endif /* end _BLOCK_MAP_H */
declare_variant_mixed_codegen.c
// RUN: %clang_cc1 -verify -fopenmp -x c -triple x86_64-unknown-linux -emit-llvm %s -o - | FileCheck %s --check-prefix HOST // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-unknown-linux -emit-pch -o %t -fopenmp-version=45 %s // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-unknown-linux -include-pch %t -verify %s -emit-llvm -o - -fopenmp-version=45 | FileCheck %s --check-prefix HOST // RUN: %clang_cc1 -verify -fopenmp -x c -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc -fopenmp-version=45 // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -fopenmp-version=45 | FileCheck %s --check-prefix GPU // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -emit-pch -o %t -fopenmp-version=45 // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -o - -fopenmp-version=45 | FileCheck %s --check-prefix GPU // RUN: %clang_cc1 -verify -fopenmp -x c -triple x86_64-unknown-linux -emit-llvm %s -o - | FileCheck %s --check-prefix HOST // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-unknown-linux -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-unknown-linux -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix HOST // RUN: %clang_cc1 -verify -fopenmp -x c -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix GPU // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -emit-pch -o %t // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -o - | FileCheck %s --check-prefix GPU // expected-no-diagnostics #ifndef HEADER #define HEADER int dev(double i) { return 0; } int hst(double i) { return 1; } #pragma omp declare variant(hst) match(device = {kind(host)}) #pragma omp declare variant(dev) match(device = {kind(gpu)}) int base(); // HOST-LABEL: define void @foo() // HOST: call i32 @hst(double -1.000000e+00) // HOST: call i32 @hst(double -2.000000e+00) // HOST: call void [[OFFL:@.+_foo_l36]]() void foo() { base(-1); hst(-2); #pragma omp target { base(-3); dev(-4); } } // HOST: define {{.*}}void [[OFFL]]() // HOST: call i32 @hst(double -3.000000e+00) // HOST: call i32 @dev(double -4.000000e+00) // GPU: define {{.*}}void @__omp_offloading_{{.+}}_foo_l36() // GPU: call i32 @dev(double -3.000000e+00) // GPU: call i32 @dev(double -4.000000e+00) // GPU-NOT: @base // GPU: define {{.*}}i32 @dev(double // GPU: ret i32 0 #endif // HEADER
GB_binop__div_fc32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__div_fc32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__div_fc32) // A.*B function (eWiseMult): GB (_AemultB_03__div_fc32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__div_fc32) // A*D function (colscale): GB (_AxD__div_fc32) // D*A function (rowscale): GB (_DxB__div_fc32) // C+=B function (dense accum): GB (_Cdense_accumB__div_fc32) // C+=b function (dense accum): GB (_Cdense_accumb__div_fc32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__div_fc32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__div_fc32) // C=scalar+B GB (_bind1st__div_fc32) // C=scalar+B' GB (_bind1st_tran__div_fc32) // C=A+scalar GB (_bind2nd__div_fc32) // C=A'+scalar GB (_bind2nd_tran__div_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = GB_FC32_div (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_FC32_div (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_DIV || GxB_NO_FC32 || GxB_NO_DIV_FC32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__div_fc32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__div_fc32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__div_fc32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__div_fc32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__div_fc32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *restrict Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__div_fc32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *restrict Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__div_fc32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__div_fc32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__div_fc32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__div_fc32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__div_fc32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__div_fc32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; GxB_FC32_t bij = Bx [p] ; Cx [p] = GB_FC32_div (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__div_fc32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC32_t aij = Ax [p] ; Cx [p] = GB_FC32_div (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_div (x, aij) ; \ } GrB_Info GB (_bind1st_tran__div_fc32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_div (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__div_fc32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__lnot_int32_fp64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_int32_fp64 // op(A') function: GB_tran__lnot_int32_fp64 // C type: int32_t // A type: double // cast: int32_t cij ; GB_CAST_SIGNED(cij,aij,32) // unaryop: cij = !(aij != 0) #define GB_ATYPE \ double #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ int32_t z ; GB_CAST_SIGNED(z,x,32) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_INT32 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int32_fp64 ( int32_t *restrict Cx, const double *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_int32_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
openmp.h
// -*- C++ -*- #ifndef GRAPHGRIND_BACKEND_OPENMP_H #define GRAPHGRIND_BACKEND_OPENMP_H #include "config.h" #include "graptor/partitioner.h" #include "graptor/legacy/parallel.h" #include "graptor/utils.h" #include <iostream> #include <fstream> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <sched.h> #include <errno.h> #include <cstring> #include <utility> #include <algorithm> #ifdef _OPENMP #include <omp.h> #endif #define parallel_for _Pragma("omp parallel for") for inline uint32_t graptor_num_threads() { return omp_get_num_threads(); } #if NUMA template<typename Fn> void map_partitionL( const partitioner & part, Fn fn ) { #pragma omp parallel for proc_bind(spread) for( unsigned n=0; n < num_numa_node; ++n ) { auto lo = part.numa_start_of(n); auto hi = part.numa_end_of(n); #pragma omp parallel for for( auto p=lo; p < hi; ++p ) fn( p ); } } #else // not NUMA template<typename Fn> void map_partitionL( const partitioner & part, Fn fn ) { auto num_partitions = part.get_num_partitions(); #pragma omp parallel for for( decltype(num_partitions) p=0; p < num_partitions; ++p ) fn( p ); } #endif // NUMA #if NUMA template<typename Fn> void map_vertexL( const partitioner & part, Fn fn ) { map_partitionL( part, [&]( typename partitioner::PID p ) { auto lo = part.start_of(p); auto hi = part.end_of(p); #pragma omp parallel for for( auto v=lo; v < hi; ++v ) fn( v ); } ); } #else template<typename Fn> void map_vertexL( const partitioner & part, Fn fn ) { auto n = part.get_num_vertices(); #pragma omp parallel for for( typename partitioner::VID v=0; v < n; ++v ) fn( v ); } #endif #endif // GRAPHGRIND_BACKEND_OPENMP_H
perftest.c
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * Copyright (C) The University of Tennessee and The University * of Tennessee Research Foundation. 2015. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "libperf.h" #include "libperf_int.h" #include <ucs/sys/string.h> #include <ucs/sys/sys.h> #include <ucs/debug/log.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <netdb.h> #include <getopt.h> #include <string.h> #include <sys/types.h> #include <locale.h> #if HAVE_MPI # include <mpi.h> #elif HAVE_RTE # include<rte.h> #endif #define MAX_BATCH_FILES 32 enum { TEST_FLAG_PRINT_RESULTS = UCS_BIT(0), TEST_FLAG_PRINT_TEST = UCS_BIT(1), TEST_FLAG_SET_AFFINITY = UCS_BIT(8), TEST_FLAG_NUMERIC_FMT = UCS_BIT(9), TEST_FLAG_PRINT_FINAL = UCS_BIT(10), TEST_FLAG_PRINT_CSV = UCS_BIT(11) }; typedef struct sock_rte_group { int is_server; int connfd; } sock_rte_group_t; typedef struct test_type { const char *name; ucx_perf_api_t api; ucx_perf_cmd_t command; ucx_perf_test_type_t test_type; const char *desc; } test_type_t; struct perftest_context { ucx_perf_params_t params; const char *server_addr; int port; #if HAVE_MPI int mpi; #endif unsigned cpu; unsigned flags; unsigned num_batch_files; char *batch_files[MAX_BATCH_FILES]; char *test_names[MAX_BATCH_FILES]; sock_rte_group_t sock_rte_group; }; #define TEST_PARAMS_ARGS "t:n:s:W:O:w:D:i:H:oSCqM:T:d:x:A:B" test_type_t tests[] = { {"am_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG, "active message latency"}, {"put_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency"}, {"add_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_PINGPONG, "atomic add latency"}, {"get", UCX_PERF_API_UCT, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate"}, {"fadd", UCX_PERF_API_UCT, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / message rate"}, {"swap", UCX_PERF_API_UCT, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / message rate"}, {"cswap", UCX_PERF_API_UCT, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / message rate"}, {"am_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI, "active message bandwidth / message rate"}, {"put_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth / message rate"}, {"add_mr", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add message rate"}, {"tag_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_PINGPONG, "UCP tag match latency"}, {"tag_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP tag match bandwidth"}, {"ucp_put_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "UCP put latency"}, {"ucp_put_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP put bandwidth"}, {"ucp_get", UCX_PERF_API_UCP, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP get latency / bandwidth / message rate"}, {"ucp_add", UCX_PERF_API_UCP, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP atomic add bandwidth / message rate"}, {"ucp_fadd", UCX_PERF_API_UCP, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP atomic fetch-and-add latency / bandwidth / message rate"}, {"ucp_swap", UCX_PERF_API_UCP, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP atomic swap latency / bandwidth / message rate"}, {"ucp_cswap", UCX_PERF_API_UCP, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP atomic compare-and-swap latency / bandwidth / message rate"}, {"stream_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP stream bandwidth"}, {"stream_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_PINGPONG, "UCP stream latency"}, {NULL} }; static int safe_send(int sock, void *data, size_t size) { size_t total = 0; int ret; while (total < size) { ret = send(sock, (char*)data + total, size - total, 0); if (ret < 0) { ucs_error("send() failed: %m"); return -1; } total += ret; } return 0; } static int safe_recv(int sock, void *data, size_t size) { size_t total = 0; int ret; while (total < size) { ret = recv(sock, (char*)data + total, size - total, 0); if (ret < 0) { ucs_error("recv() failed: %m"); return -1; } total += ret; } return 0; } static void print_progress(char **test_names, unsigned num_names, const ucx_perf_result_t *result, unsigned flags, int final) { static const char *fmt_csv = "%.0f,%.3f,%.3f,%.3f,%.2f,%.2f,%.0f,%.0f\n"; static const char *fmt_numeric = "%'14.0f %9.3f %9.3f %9.3f %10.2f %10.2f %'11.0f %'11.0f\n"; static const char *fmt_plain = "%14.0f %9.3f %9.3f %9.3f %10.2f %10.2f %11.0f %11.0f\n"; unsigned i; if (!(flags & TEST_FLAG_PRINT_RESULTS) || (!final && (flags & TEST_FLAG_PRINT_FINAL))) { return; } if (flags & TEST_FLAG_PRINT_CSV) { for (i = 0; i < num_names; ++i) { printf("%s,", test_names[i]); } } printf((flags & TEST_FLAG_PRINT_CSV) ? fmt_csv : (flags & TEST_FLAG_NUMERIC_FMT) ? fmt_numeric : fmt_plain, (double)result->iters, result->latency.typical * 1000000.0, result->latency.moment_average * 1000000.0, result->latency.total_average * 1000000.0, result->bandwidth.moment_average / (1024.0 * 1024.0), result->bandwidth.total_average / (1024.0 * 1024.0), result->msgrate.moment_average, result->msgrate.total_average); fflush(stdout); } static void print_header(struct perftest_context *ctx) { const char *test_api_str; const char *test_data_str; test_type_t *test; unsigned i; if (ctx->flags & TEST_FLAG_PRINT_TEST) { for (test = tests; test->name; ++test) { if ((test->command == ctx->params.command) && (test->test_type == ctx->params.test_type)) { break; } } if (test->name != NULL) { if (test->api == UCX_PERF_API_UCT) { test_api_str = "transport layer"; switch (ctx->params.uct.data_layout) { case UCT_PERF_DATA_LAYOUT_SHORT: test_data_str = "short"; break; case UCT_PERF_DATA_LAYOUT_BCOPY: test_data_str = "bcopy"; break; case UCT_PERF_DATA_LAYOUT_ZCOPY: test_data_str = "zcopy"; break; default: test_data_str = "(undefined)"; break; } } else if (test->api == UCX_PERF_API_UCP) { test_api_str = "protocol layer"; test_data_str = "(automatic)"; /* TODO contig/stride/stream */ } else { return; } printf("+------------------------------------------------------------------------------------------+\n"); printf("| API: %-60s |\n", test_api_str); printf("| Test: %-60s |\n", test->desc); printf("| Data layout: %-60s |\n", test_data_str); printf("| Message size: %-60zu |\n", ucx_perf_get_message_size(&ctx->params)); } } if (ctx->flags & TEST_FLAG_PRINT_CSV) { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { for (i = 0; i < ctx->num_batch_files; ++i) { printf("%s,", basename(ctx->batch_files[i])); } printf("iterations,typical_lat,avg_lat,overall_lat,avg_bw,overall_bw,avg_mr,overall_mr\n"); } } else { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { printf("+--------------+-----------------------------+---------------------+-----------------------+\n"); printf("| | latency (usec) | bandwidth (MB/s) | message rate (msg/s) |\n"); printf("+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); printf("| # iterations | typical | average | overall | average | overall | average | overall |\n"); printf("+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); } else if (ctx->flags & TEST_FLAG_PRINT_TEST) { printf("+------------------------------------------------------------------------------------------+\n"); } } } static void print_test_name(struct perftest_context *ctx) { char buf[200]; unsigned i, pos; if (!(ctx->flags & TEST_FLAG_PRINT_CSV) && (ctx->num_batch_files > 0)) { strcpy(buf, "+--------------+---------+---------+---------+----------+----------+-----------+-----------+"); pos = 1; for (i = 0; i < ctx->num_batch_files; ++i) { if (i != 0) { buf[pos++] = '/'; } memcpy(&buf[pos], ctx->test_names[i], ucs_min(strlen(ctx->test_names[i]), sizeof(buf) - pos - 1)); pos += strlen(ctx->test_names[i]); } if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { printf("%s\n", buf); } } } static void usage(struct perftest_context *ctx, const char *program) { test_type_t *test; printf("Usage: %s [ server-hostname ] [ options ]\n", program); printf("\n"); #if HAVE_MPI printf("This test can be also launched as an MPI application\n"); #elif HAVE_RTE printf("This test can be also launched as an libRTE application\n"); #endif printf(" Common options:\n"); printf("\n"); printf(" Test options:\n"); printf(" -t <test> Test to run.\n"); for (test = tests; test->name; ++test) { printf(" %11s : %s.\n", test->name, test->desc); } printf("\n"); printf(" -D <layout>[,<layout>] Data layout. Default is \"short\" in UCT," " \"contig\" in UCP and previous one " "in batch mode. Second parameter is for " "receive side in UCP only.\n"); printf(" short : Use short messages API (cannot used for get).\n"); printf(" bcopy : Use copy-out API (cannot used for atomics).\n"); printf(" zcopy : Use zero-copy API (cannot used for atomics).\n"); printf(" contig : Use continuous datatype in UCP tests.\n"); printf(" iov : Use IOV datatype in UCP tests.\n"); printf("\n"); printf(" -d <device> Device to use for testing.\n"); printf(" -x <tl> Transport to use for testing.\n"); printf(" -c <cpu> Set affinity to this CPU. (off)\n"); printf(" -n <iters> Number of iterations to run. (%ld)\n", ctx->params.max_iter); printf(" -s <size> List of buffer sizes separated by comma, which " "make up a single message. Default is (%zu). " "For example, \"-s 16,48,8192,8192,14\"\n", ctx->params.msg_size_list[0]); printf(" -H <size> AM Header size. (%zu)\n", ctx->params.am_hdr_size); printf(" -w <iters> Number of warm-up iterations. (%zu)\n", ctx->params.warmup_iter); printf(" -W <count> Flow control window size, for active messages. (%u)\n", ctx->params.uct.fc_window); printf(" -O <count> Maximal number of uncompleted outstanding sends. (%u)\n", ctx->params.max_outstanding); printf(" -i <count> Distance between starting address of consecutive " "IOV entries. The same as UCT uct_iov_t stride.\n"); printf(" -N Use numeric formatting - thousands separator.\n"); printf(" -f Print only final numbers.\n"); printf(" -v Print CSV-formatted output.\n"); printf(" -p <port> TCP port to use for data exchange. (%d)\n", ctx->port); printf(" -b <batchfile> Batch mode. Read and execute tests from a file.\n"); printf(" Every line of the file is a test to run. " "The first word is the\n"); printf(" test name, and the rest are command-line " "arguments for the test.\n"); printf(" -M <thread> Thread support level for progress engine (single).\n"); printf(" single : Only the master thread can access.\n"); printf(" serialized : One thread can access at a time.\n"); printf(" multi : Multiple threads can access.\n"); printf(" -T <threads> Number of threads in the test (1); " "also implies \"-M multi\".\n"); printf(" -A <mode> Async progress mode. (thread)\n"); printf(" thread : Use separate progress thread.\n"); printf(" signal : Use signal based timer.\n"); printf(" -B Register memory with NONBLOCK flag.\n"); printf(" -C Use wildcard for tag tests.\n"); printf(" -S Use synchronous mode for tag sends.\n"); #if HAVE_MPI printf(" -P <0|1> Disable/enable MPI mode (%d)\n", ctx->mpi); #endif printf(" -h Show this help message.\n"); printf("\n"); } static const char *__basename(const char *path) { const char *p = strrchr(path, '/'); return (p == NULL) ? path : p; } static ucs_status_t parse_ucp_datatype_params(const char *optarg, ucp_perf_datatype_t *datatype) { const char *iov_type = "iov"; const size_t iov_type_size = strlen("iov"); const char *contig_type = "contig"; const size_t contig_type_size = strlen("contig"); if (0 == strncmp(optarg, iov_type, iov_type_size)) { *datatype = UCP_PERF_DATATYPE_IOV; } else if (0 == strncmp(optarg, contig_type, contig_type_size)) { *datatype = UCP_PERF_DATATYPE_CONTIG; } else { return UCS_ERR_INVALID_PARAM; } return UCS_OK; } static ucs_status_t parse_message_sizes_params(const char *optarg, ucx_perf_params_t *params) { char *optarg_ptr, *optarg_ptr2; size_t token_num, token_it; const char delim = ','; optarg_ptr = (char *)optarg; token_num = 0; /* count the number of given message sizes */ while ((optarg_ptr = strchr(optarg_ptr, delim)) != NULL) { ++optarg_ptr; ++token_num; } ++token_num; free(params->msg_size_list); /* free previously allocated buffer */ params->msg_size_list = malloc(sizeof(*params->msg_size_list) * token_num); if (NULL == params->msg_size_list) { return UCS_ERR_NO_MEMORY; } optarg_ptr = (char *)optarg; errno = 0; for (token_it = 0; token_it < token_num; ++token_it) { params->msg_size_list[token_it] = strtoul(optarg_ptr, &optarg_ptr2, 10); if (((ERANGE == errno) && (ULONG_MAX == params->msg_size_list[token_it])) || ((errno != 0) && (params->msg_size_list[token_it] == 0)) || (optarg_ptr == optarg_ptr2)) { free(params->msg_size_list); params->msg_size_list = NULL; /* prevent double free */ ucs_error("Invalid option substring argument at position %lu", token_it); return UCS_ERR_INVALID_PARAM; } optarg_ptr = optarg_ptr2 + 1; } params->msg_size_cnt = token_num; return UCS_OK; } static void init_test_params(ucx_perf_params_t *params) { params->api = UCX_PERF_API_LAST; params->command = UCX_PERF_CMD_LAST; params->test_type = UCX_PERF_TEST_TYPE_LAST; params->thread_mode = UCS_THREAD_MODE_SINGLE; params->thread_count = 1; params->async_mode = UCS_ASYNC_MODE_THREAD; params->wait_mode = UCX_PERF_WAIT_MODE_LAST; params->max_outstanding = 1; params->warmup_iter = 10000; params->am_hdr_size = 8; params->alignment = ucs_get_page_size(); params->max_iter = 1000000l; params->max_time = 0.0; params->report_interval = 1.0; params->flags = UCX_PERF_TEST_FLAG_VERBOSE; params->uct.fc_window = UCT_PERF_TEST_MAX_FC_WINDOW; params->uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; params->msg_size_cnt = 1; params->iov_stride = 0; params->ucp.send_datatype = UCP_PERF_DATATYPE_CONTIG; params->ucp.recv_datatype = UCP_PERF_DATATYPE_CONTIG; strcpy(params->uct.dev_name, "<none>"); strcpy(params->uct.tl_name, "<none>"); params->msg_size_list = malloc(sizeof(*params->msg_size_list) * params->msg_size_cnt); params->msg_size_list[0] = 8; } static ucs_status_t parse_test_params(ucx_perf_params_t *params, char opt, const char *optarg) { test_type_t *test; char *optarg2 = NULL; /* TODO: currently, UCP supports only ucp_stream_recv_data_nb path, * add option when ucp_stream_recv_nb is implemented */ params->flags |= UCX_PERF_TEST_FLAG_STREAM_RECV_DATA; switch (opt) { case 'd': ucs_snprintf_zero(params->uct.dev_name, sizeof(params->uct.dev_name), "%s", optarg); return UCS_OK; case 'x': ucs_snprintf_zero(params->uct.tl_name, sizeof(params->uct.tl_name), "%s", optarg); return UCS_OK; case 't': for (test = tests; test->name; ++test) { if (!strcmp(optarg, test->name)) { params->api = test->api; params->command = test->command; params->test_type = test->test_type; break; } } if (test->name == NULL) { ucs_error("Invalid option argument for -t"); return UCS_ERR_INVALID_PARAM; } return UCS_OK; case 'D': if (0 == strcmp(optarg, "short")) { params->uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; } else if (0 == strcmp(optarg, "bcopy")) { params->uct.data_layout = UCT_PERF_DATA_LAYOUT_BCOPY; } else if (0 == strcmp(optarg, "zcopy")) { params->uct.data_layout = UCT_PERF_DATA_LAYOUT_ZCOPY; } else if (UCS_OK == parse_ucp_datatype_params(optarg, &params->ucp.send_datatype)) { optarg2 = strchr(optarg, ','); if (optarg2) { if (UCS_OK != parse_ucp_datatype_params(optarg2 + 1, &params->ucp.recv_datatype)) { return -1; } } } else { ucs_error("Invalid option argument for -D"); return -1; } return UCS_OK; case 'i': params->iov_stride = atol(optarg); return UCS_OK; case 'n': params->max_iter = atol(optarg); return UCS_OK; case 's': return parse_message_sizes_params(optarg, params); case 'H': params->am_hdr_size = atol(optarg); return UCS_OK; case 'W': params->uct.fc_window = atoi(optarg); return UCS_OK; case 'O': params->max_outstanding = atoi(optarg); return UCS_OK; case 'w': params->warmup_iter = atol(optarg); return UCS_OK; case 'o': params->flags |= UCX_PERF_TEST_FLAG_ONE_SIDED; return UCS_OK; case 'B': params->flags |= UCX_PERF_TEST_FLAG_MAP_NONBLOCK; return UCS_OK; case 'q': params->flags &= ~UCX_PERF_TEST_FLAG_VERBOSE; return UCS_OK; case 'C': params->flags |= UCX_PERF_TEST_FLAG_TAG_WILDCARD; return UCS_OK; case 'S': params->flags |= UCX_PERF_TEST_FLAG_TAG_SYNC; return UCS_OK; case 'M': if (0 == strcmp(optarg, "single")) { params->thread_mode = UCS_THREAD_MODE_SINGLE; return UCS_OK; } else if (0 == strcmp(optarg, "serialized")) { params->thread_mode = UCS_THREAD_MODE_SERIALIZED; return UCS_OK; } else if (0 == strcmp(optarg, "multi")) { params->thread_mode = UCS_THREAD_MODE_MULTI; return UCS_OK; } else { ucs_error("Invalid option argument for -M"); return UCS_ERR_INVALID_PARAM; } case 'T': params->thread_count = atoi(optarg); params->thread_mode = UCS_THREAD_MODE_MULTI; return UCS_OK; case 'A': if (0 == strcmp(optarg, "thread")) { params->async_mode = UCS_ASYNC_MODE_THREAD; return UCS_OK; } else if (0 == strcmp(optarg, "signal")) { params->async_mode = UCS_ASYNC_MODE_SIGNAL; return UCS_OK; } else { ucs_error("Invalid option argument for -A"); return UCS_ERR_INVALID_PARAM; } default: return UCS_ERR_INVALID_PARAM; } } static ucs_status_t read_batch_file(FILE *batch_file, ucx_perf_params_t *params, char** test_name_p) { #define MAX_SIZE 256 #define MAX_ARG_SIZE 2048 ucs_status_t status; char buf[MAX_ARG_SIZE]; int argc; char *argv[MAX_SIZE + 1]; int c; char *p; do { if (fgets(buf, sizeof(buf) - 1, batch_file) == NULL) { return UCS_ERR_NO_ELEM; } argc = 0; p = strtok(buf, " \t\n\r"); while (p && (argc < MAX_SIZE)) { argv[argc++] = p; p = strtok(NULL, " \t\n\r"); } argv[argc] = NULL; } while ((argc == 0) || (argv[0][0] == '#')); optind = 1; while ((c = getopt (argc, argv, TEST_PARAMS_ARGS)) != -1) { status = parse_test_params(params, c, optarg); if (status != UCS_OK) { ucs_error("Invalid argument in batch file: -%c, status(%d):\"%s\"", c, status, ucs_status_string(status)); return status; } } *test_name_p = strdup(argv[0]); return UCS_OK; } static ucs_status_t parse_opts(struct perftest_context *ctx, int argc, char **argv) { ucs_status_t status; int c; ucs_trace_func(""); init_test_params(&ctx->params); ctx->server_addr = NULL; ctx->num_batch_files = 0; ctx->port = 13337; ctx->flags = 0; #if HAVE_MPI ctx->mpi = !isatty(0); #endif optind = 1; while ((c = getopt (argc, argv, "p:b:Nfvc:P:h" TEST_PARAMS_ARGS)) != -1) { switch (c) { case 'p': ctx->port = atoi(optarg); break; case 'b': if (ctx->num_batch_files < MAX_BATCH_FILES) { ctx->batch_files[ctx->num_batch_files++] = strdup(optarg); } break; case 'N': ctx->flags |= TEST_FLAG_NUMERIC_FMT; break; case 'f': ctx->flags |= TEST_FLAG_PRINT_FINAL; break; case 'v': ctx->flags |= TEST_FLAG_PRINT_CSV; break; case 'c': ctx->flags |= TEST_FLAG_SET_AFFINITY; ctx->cpu = atoi(optarg); break; case 'P': #if HAVE_MPI ctx->mpi = atoi(optarg); break; #endif case 'h': usage(ctx, __basename(argv[0])); return UCS_ERR_CANCELED; default: status = parse_test_params(&ctx->params, c, optarg); if (status != UCS_OK) { usage(ctx, __basename(argv[0])); return status; } break; } } if (optind < argc) { ctx->server_addr = argv[optind]; } return UCS_OK; } static unsigned sock_rte_group_size(void *rte_group) { return 2; } static unsigned sock_rte_group_index(void *rte_group) { sock_rte_group_t *group = rte_group; return group->is_server ? 0 : 1; } static void sock_rte_barrier(void *rte_group) { #pragma omp master { sock_rte_group_t *group = rte_group; const unsigned magic = 0xdeadbeef; unsigned sync; sync = magic; safe_send(group->connfd, &sync, sizeof(unsigned)); sync = 0; safe_recv(group->connfd, &sync, sizeof(unsigned)); ucs_assert(sync == magic); } #pragma omp barrier } static void sock_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { sock_rte_group_t *group = rte_group; size_t size; int i; size = 0; for (i = 0; i < iovcnt; ++i) { size += iovec[i].iov_len; } safe_send(group->connfd, &size, sizeof(size)); for (i = 0; i < iovcnt; ++i) { safe_send(group->connfd, iovec[i].iov_base, iovec[i].iov_len); } } static void sock_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { sock_rte_group_t *group = rte_group; int group_index; size_t size; group_index = sock_rte_group_index(rte_group); if (src == group_index) { return; } ucs_assert_always(src == (1 - group_index)); safe_recv(group->connfd, &size, sizeof(size)); ucs_assert_always(size <= max); safe_recv(group->connfd, buffer, size); } static void sock_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final); } static ucx_perf_rte_t sock_rte = { .group_size = sock_rte_group_size, .group_index = sock_rte_group_index, .barrier = sock_rte_barrier, .post_vec = sock_rte_post_vec, .recv = sock_rte_recv, .exchange_vec = (void*)ucs_empty_function, .report = sock_rte_report, }; static ucs_status_t setup_sock_rte(struct perftest_context *ctx) { struct sockaddr_in inaddr; struct hostent *he; ucs_status_t status; int optval = 1; int sockfd, connfd; int ret; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ucs_error("socket() failed: %m"); status = UCS_ERR_IO_ERROR; goto err; } if (ctx->server_addr == NULL) { optval = 1; ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (ret < 0) { ucs_error("setsockopt(SO_REUSEADDR) failed: %m"); status = UCS_ERR_INVALID_PARAM; goto err_close_sockfd; } inaddr.sin_family = AF_INET; inaddr.sin_port = htons(ctx->port); inaddr.sin_addr.s_addr = INADDR_ANY; memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = bind(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("bind() failed: %m"); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } ret = listen(sockfd, 10); if (ret < 0) { ucs_error("listen() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } printf("Waiting for connection...\n"); /* Accept next connection */ connfd = accept(sockfd, NULL, NULL); if (connfd < 0) { ucs_error("accept() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } close(sockfd); safe_recv(connfd, &ctx->params, sizeof(ctx->params)); if (ctx->params.msg_size_cnt) { ctx->params.msg_size_list = malloc(sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt); if (NULL == ctx->params.msg_size_list) { status = UCS_ERR_NO_MEMORY; goto err_close_connfd; } safe_recv(connfd, ctx->params.msg_size_list, sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt); } ctx->sock_rte_group.connfd = connfd; ctx->sock_rte_group.is_server = 1; } else { he = gethostbyname(ctx->server_addr); if (he == NULL || he->h_addr_list == NULL) { ucs_error("host %s not found: %s", ctx->server_addr, hstrerror(h_errno)); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } inaddr.sin_family = he->h_addrtype; inaddr.sin_port = htons(ctx->port); ucs_assert(he->h_length == sizeof(inaddr.sin_addr)); memcpy(&inaddr.sin_addr, he->h_addr_list[0], he->h_length); memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = connect(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("connect() failed: %m"); status = UCS_ERR_UNREACHABLE; goto err_close_sockfd; } safe_send(sockfd, &ctx->params, sizeof(ctx->params)); if (ctx->params.msg_size_cnt) { safe_send(sockfd, ctx->params.msg_size_list, sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt); } ctx->sock_rte_group.connfd = sockfd; ctx->sock_rte_group.is_server = 0; } if (ctx->sock_rte_group.is_server) { ctx->flags |= TEST_FLAG_PRINT_TEST; } else { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.rte_group = &ctx->sock_rte_group; ctx->params.rte = &sock_rte; ctx->params.report_arg = ctx; return UCS_OK; err_close_connfd: close(connfd); goto err; err_close_sockfd: close(sockfd); err: return status; } static ucs_status_t cleanup_sock_rte(struct perftest_context *ctx) { close(ctx->sock_rte_group.connfd); return UCS_OK; } #if HAVE_MPI static unsigned mpi_rte_group_size(void *rte_group) { int size; MPI_Comm_size(MPI_COMM_WORLD, &size); return size; } static unsigned mpi_rte_group_index(void *rte_group) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); return rank; } static void mpi_rte_barrier(void *rte_group) { #pragma omp master MPI_Barrier(MPI_COMM_WORLD); #pragma omp barrier } static void mpi_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { int group_size; int my_rank; int dest, i; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); for (dest = 0; dest < group_size; ++dest) { if (dest == my_rank) { continue; } for (i = 0; i < iovcnt; ++i) { MPI_Send(iovec[i].iov_base, iovec[i].iov_len, MPI_BYTE, dest, i == (iovcnt - 1), /* Send last iov with tag == 1 */ MPI_COMM_WORLD); } } *req = (void*)(uintptr_t)1; } static void mpi_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { MPI_Status status; size_t offset; int my_rank; int count; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); if (src == my_rank) { return; } offset = 0; do { ucs_assert_always(offset < max); MPI_Recv(buffer + offset, max - offset, MPI_BYTE, src, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_BYTE, &count); offset += count; } while (status.MPI_TAG != 1); } static void mpi_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final); } static ucx_perf_rte_t mpi_rte = { .group_size = mpi_rte_group_size, .group_index = mpi_rte_group_index, .barrier = mpi_rte_barrier, .post_vec = mpi_rte_post_vec, .recv = mpi_rte_recv, .exchange_vec = (void*)ucs_empty_function, .report = mpi_rte_report, }; #elif HAVE_RTE static unsigned ext_rte_group_size(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_size(group); } static unsigned ext_rte_group_index(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_rank(group); } static void ext_rte_barrier(void *rte_group) { #pragma omp master { rte_group_t group = (rte_group_t)rte_group; int rc; rc = rte_barrier(group); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_barrier"); } } #pragma omp barrier } static void ext_rte_post_vec(void *rte_group, const struct iovec* iovec, int iovcnt, void **req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session; rte_iovec_t *r_vec; int i, rc; rc = rte_srs_session_create(group, 0, &session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_create"); } r_vec = calloc(iovcnt, sizeof(rte_iovec_t)); if (r_vec == NULL) { return; } for (i = 0; i < iovcnt; ++i) { r_vec[i].iov_base = iovec[i].iov_base; r_vec[i].type = rte_datatype_uint8_t; r_vec[i].count = iovec[i].iov_len; } rc = rte_srs_set_data(session, "KEY_PERF", r_vec, iovcnt); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_set_data"); } *req = session; free(r_vec); } static void ext_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session = (rte_srs_session_t)req; void *rte_buffer = NULL; rte_iovec_t r_vec; uint32_t offset; int size; int rc; rc = rte_srs_get_data(session, rte_group_index_to_ec(group, src), "KEY_PERF", &rte_buffer, &size); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_get_data"); return; } r_vec.iov_base = buffer; r_vec.type = rte_datatype_uint8_t; r_vec.count = max; offset = 0; rte_unpack(&r_vec, rte_buffer, &offset); rc = rte_srs_session_destroy(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_destroy"); } free(rte_buffer); } static void ext_rte_exchange_vec(void *rte_group, void * req) { rte_srs_session_t session = (rte_srs_session_t)req; int rc; rc = rte_srs_exchange_data(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_exchange_data"); } } static void ext_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final); } static ucx_perf_rte_t ext_rte = { .group_size = ext_rte_group_size, .group_index = ext_rte_group_index, .barrier = ext_rte_barrier, .report = ext_rte_report, .post_vec = ext_rte_post_vec, .recv = ext_rte_recv, .exchange_vec = ext_rte_exchange_vec, }; #endif static ucs_status_t setup_mpi_rte(struct perftest_context *ctx) { ucs_trace_func(""); #if HAVE_MPI int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); if (size != 2) { ucs_error("This test should run with exactly 2 processes (actual: %d)", size); return UCS_ERR_INVALID_PARAM; } MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 1) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.rte_group = NULL; ctx->params.rte = &mpi_rte; ctx->params.report_arg = ctx; #elif HAVE_RTE rte_group_t group; rte_init(NULL, NULL, &group); if (1 == rte_group_rank(group)) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.rte_group = group; ctx->params.rte = &ext_rte; ctx->params.report_arg = ctx; #endif return UCS_OK; } static ucs_status_t cleanup_mpi_rte(struct perftest_context *ctx) { #if HAVE_MPI MPI_Finalize(); #elif HAVE_RTE rte_finalize(); #endif return UCS_OK; } static ucs_status_t check_system(struct perftest_context *ctx) { cpu_set_t cpuset; unsigned i, count, nr_cpus; int ret; ucs_trace_func(""); ret = sysconf(_SC_NPROCESSORS_CONF); if (ret < 0) { ucs_error("failed to get local cpu count: %m"); return UCS_ERR_INVALID_PARAM; } nr_cpus = ret; memset(&cpuset, 0, sizeof(cpuset)); if (ctx->flags & TEST_FLAG_SET_AFFINITY) { if (ctx->cpu >= nr_cpus) { ucs_error("cpu (%u) ot of range (0..%u)", ctx->cpu, nr_cpus - 1); return UCS_ERR_INVALID_PARAM; } CPU_SET(ctx->cpu, &cpuset); ret = sched_setaffinity(0, sizeof(cpuset), &cpuset); if (ret) { ucs_warn("sched_setaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } } else { ret = sched_getaffinity(0, sizeof(cpuset), &cpuset); if (ret) { ucs_warn("sched_getaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } count = 0; for (i = 0; i < CPU_SETSIZE; ++i) { if (CPU_ISSET(i, &cpuset)) { ++count; } } if (count > 2) { ucs_warn("CPU affinity is not set (bound to %u cpus)." " Performance may be impacted.", count); } } return UCS_OK; } static ucs_status_t run_test_recurs(struct perftest_context *ctx, ucx_perf_params_t *parent_params, unsigned depth) { ucx_perf_params_t params; ucx_perf_result_t result; ucs_status_t status; FILE *batch_file; ucs_trace_func("depth=%u, num_files=%u", depth, ctx->num_batch_files); if (depth >= ctx->num_batch_files) { print_test_name(ctx); return ucx_perf_run(parent_params, &result); } batch_file = fopen(ctx->batch_files[depth], "r"); if (batch_file == NULL) { ucs_error("Failed to open batch file '%s': %m", ctx->batch_files[depth]); return UCS_ERR_IO_ERROR; } params = *parent_params; while ((status = read_batch_file(batch_file, &params, &ctx->test_names[depth])) == UCS_OK) { status = run_test_recurs(ctx, &params, depth + 1); free(ctx->test_names[depth]); if ((NULL == parent_params->msg_size_list) && (NULL != params.msg_size_list)) { free(params.msg_size_list); params.msg_size_list = NULL; } } fclose(batch_file); return UCS_OK; } static ucs_status_t run_test(struct perftest_context *ctx) { ucs_status_t status; ucs_trace_func(""); setlocale(LC_ALL, "en_US"); print_header(ctx); status = run_test_recurs(ctx, &ctx->params, 0); if (status != UCS_OK) { ucs_error("Failed to run test: %s", ucs_status_string(status)); } return status; } int main(int argc, char **argv) { struct perftest_context ctx; ucs_status_t status; int rte = 0; int ret; /* Parse command line */ if (parse_opts(&ctx, argc, argv) != UCS_OK) { ret = -127; goto out; } #ifdef __COVERITY__ /* coverity[dont_call] */ rte = rand(); /* Shut up deadcode error */ #endif #if HAVE_MPI /* Don't try MPI when running interactively */ if (ctx.mpi && (MPI_Init(&argc, &argv) == 0)) { rte = 1; } #elif HAVE_RTE rte = 1; #endif status = check_system(&ctx); if (status != UCS_OK) { ret = -1; goto out; } /* Create RTE */ status = (rte) ? setup_mpi_rte(&ctx) : setup_sock_rte(&ctx); if (status != UCS_OK) { ret = -1; goto out; } /* Run the test */ status = run_test(&ctx); if (status != UCS_OK) { ret = -1; goto out_cleanup_rte; } ret = 0; out_cleanup_rte: (rte) ? cleanup_mpi_rte(&ctx) : cleanup_sock_rte(&ctx); out: if (ctx.params.msg_size_list) { free(ctx.params.msg_size_list); } return ret; }
convolution_sgemm_pack8to1_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #if !(__AVX512VNNI__ || __AVXVNNI__ || __AVX2__ || __XOP__) #if NCNN_RUNTIME_CPU && NCNN_AVX512VNNI && __AVX512F__ && !__AVX512VNNI__ void im2col_sgemm_pack8to1_int8_sse_avx512vnni(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt); #endif #if NCNN_RUNTIME_CPU && NCNN_AVXVNNI && __AVX2__ && !__AVXVNNI__ void im2col_sgemm_pack8to1_int8_sse_avxvnni(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt); #endif #if NCNN_RUNTIME_CPU && NCNN_AVX2 && __AVX__ && !__AVX2__ void im2col_sgemm_pack8to1_int8_sse_avx2(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt); #endif #if NCNN_RUNTIME_CPU && NCNN_XOP && __SSE2__ && !__XOP__ void im2col_sgemm_pack8to1_int8_sse_xop(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt); #endif #endif static void im2col_sgemm_pack8to1_int8_sse(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt) { #if !(__AVX512VNNI__ || __AVXVNNI__ || __AVX2__ || __XOP__) #if NCNN_RUNTIME_CPU && NCNN_AVX512VNNI && __AVX512F__ && !__AVX512VNNI__ if (ncnn::cpu_support_x86_avx512_vnni()) { im2col_sgemm_pack8to1_int8_sse_avx512vnni(bottom_im2col, top_blob, kernel, opt); return; } #endif #if NCNN_RUNTIME_CPU && NCNN_AVXVNNI && __AVX2__ && !__AVXVNNI__ if (ncnn::cpu_support_x86_avx_vnni()) { im2col_sgemm_pack8to1_int8_sse_avxvnni(bottom_im2col, top_blob, kernel, opt); return; } #endif #if NCNN_RUNTIME_CPU && NCNN_AVX2 && __AVX__ && !__AVX2__ if (ncnn::cpu_support_x86_avx2()) { im2col_sgemm_pack8to1_int8_sse_avx2(bottom_im2col, top_blob, kernel, opt); return; } #endif #if NCNN_RUNTIME_CPU && NCNN_XOP && __SSE2__ && !__XOP__ if (ncnn::cpu_support_x86_xop()) { im2col_sgemm_pack8to1_int8_sse_xop(bottom_im2col, top_blob, kernel, opt); return; } #endif #endif // Mat bottom_im2col(size, maxk, inch, 8u, 8, opt.workspace_allocator); const int size = bottom_im2col.w; const int maxk = bottom_im2col.h; const int inch = bottom_im2col.c; const int outch = top_blob.c; // permute Mat tmp; #if __AVX2__ if (size >= 4) tmp.create(4 * maxk, inch, size / 4 + (size % 4) / 2 + size % 2, 8u, 8, opt.workspace_allocator); else if (size >= 2) tmp.create(2 * maxk, inch, size / 2 + size % 2, 8u, 8, opt.workspace_allocator); else tmp.create(maxk, inch, size, 8u, 8, opt.workspace_allocator); #else if (size >= 2) tmp.create(2 * maxk, inch, size / 2 + size % 2, 8u, 8, opt.workspace_allocator); else tmp.create(maxk, inch, size, 8u, 8, opt.workspace_allocator); #endif { #if __AVX2__ int remain_size_start = 0; int nn_size = size >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 4; int64_t* tmpptr = tmp.channel(i / 4); for (int q = 0; q < inch; q++) { const int64_t* img0 = (const int64_t*)bottom_im2col.channel(q) + i; for (int k = 0; k < maxk; k++) { __m256i _v = _mm256_loadu_si256((const __m256i*)img0); _mm256_storeu_si256((__m256i*)tmpptr, _v); tmpptr += 4; img0 += size; } } } remain_size_start += nn_size << 2; nn_size = (size - remain_size_start) >> 1; #else int remain_size_start = 0; int nn_size = (size - remain_size_start) >> 1; #endif #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 2; #if __AVX2__ int64_t* tmpptr = tmp.channel(i / 4 + (i % 4) / 2); #else int64_t* tmpptr = tmp.channel(i / 2); #endif for (int q = 0; q < inch; q++) { const int64_t* img0 = (const int64_t*)bottom_im2col.channel(q) + i; for (int k = 0; k < maxk; k++) { __m128i _v = _mm_loadu_si128((const __m128i*)img0); _mm_storeu_si128((__m128i*)tmpptr, _v); tmpptr += 2; img0 += size; } } } remain_size_start += nn_size << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { #if __AVX2__ int64_t* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2); #else int64_t* tmpptr = tmp.channel(i / 2 + i % 2); #endif for (int q = 0; q < inch; q++) { const int64_t* img0 = (const int64_t*)bottom_im2col.channel(q) + i; for (int k = 0; k < maxk; k++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += size; } } } } int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; int* outptr0 = top_blob.channel(p); int* outptr1 = top_blob.channel(p + 1); int* outptr2 = top_blob.channel(p + 2); int* outptr3 = top_blob.channel(p + 3); int i = 0; #if __AVX2__ for (; i + 3 < size; i += 4) { const signed char* tmpptr = tmp.channel(i / 4); const signed char* kptr0 = kernel.channel(p / 4); int nn = inch * maxk; // inch always > 0 __m256i _sum00_11 = _mm256_setzero_si256(); __m256i _sum10_01 = _mm256_setzero_si256(); __m256i _sum02_13 = _mm256_setzero_si256(); __m256i _sum12_03 = _mm256_setzero_si256(); __m256i _sum04_15 = _mm256_setzero_si256(); __m256i _sum14_05 = _mm256_setzero_si256(); __m256i _sum06_17 = _mm256_setzero_si256(); __m256i _sum16_07 = _mm256_setzero_si256(); int j = 0; for (; j < nn; j++) { __m128i _val01 = _mm_loadu_si128((const __m128i*)tmpptr); __m256i _val01_16 = _mm256_cvtepi8_epi16(_val01); __m128i _w01 = _mm_loadu_si128((const __m128i*)kptr0); __m128i _w23 = _mm_loadu_si128((const __m128i*)(kptr0 + 16)); __m256i _w01_16 = _mm256_cvtepi8_epi16(_w01); __m256i _w23_16 = _mm256_cvtepi8_epi16(_w23); __m256i _val10_16 = _mm256_permute4x64_epi64(_val01_16, 78); #if __AVXVNNI__ || __AVX512VNNI__ _sum00_11 = _mm256_dpwssd_epi32(_sum00_11, _val01_16, _w01_16); _sum10_01 = _mm256_dpwssd_epi32(_sum10_01, _val10_16, _w01_16); _sum02_13 = _mm256_dpwssd_epi32(_sum02_13, _val01_16, _w23_16); _sum12_03 = _mm256_dpwssd_epi32(_sum12_03, _val10_16, _w23_16); #else __m256i _sl00_11 = _mm256_mullo_epi16(_val01_16, _w01_16); __m256i _sh00_11 = _mm256_mulhi_epi16(_val01_16, _w01_16); __m256i _sl10_01 = _mm256_mullo_epi16(_val10_16, _w01_16); __m256i _sh10_01 = _mm256_mulhi_epi16(_val10_16, _w01_16); __m256i _sl02_13 = _mm256_mullo_epi16(_val01_16, _w23_16); __m256i _sh02_13 = _mm256_mulhi_epi16(_val01_16, _w23_16); __m256i _sl12_03 = _mm256_mullo_epi16(_val10_16, _w23_16); __m256i _sh12_03 = _mm256_mulhi_epi16(_val10_16, _w23_16); _sum00_11 = _mm256_add_epi32(_sum00_11, _mm256_unpacklo_epi16(_sl00_11, _sh00_11)); _sum10_01 = _mm256_add_epi32(_sum10_01, _mm256_unpacklo_epi16(_sl10_01, _sh10_01)); _sum02_13 = _mm256_add_epi32(_sum02_13, _mm256_unpacklo_epi16(_sl02_13, _sh02_13)); _sum12_03 = _mm256_add_epi32(_sum12_03, _mm256_unpacklo_epi16(_sl12_03, _sh12_03)); _sum00_11 = _mm256_add_epi32(_sum00_11, _mm256_unpackhi_epi16(_sl00_11, _sh00_11)); _sum10_01 = _mm256_add_epi32(_sum10_01, _mm256_unpackhi_epi16(_sl10_01, _sh10_01)); _sum02_13 = _mm256_add_epi32(_sum02_13, _mm256_unpackhi_epi16(_sl02_13, _sh02_13)); _sum12_03 = _mm256_add_epi32(_sum12_03, _mm256_unpackhi_epi16(_sl12_03, _sh12_03)); #endif __m128i _val23 = _mm_loadu_si128((const __m128i*)(tmpptr + 16)); __m256i _val23_16 = _mm256_cvtepi8_epi16(_val23); __m256i _val32_16 = _mm256_permute4x64_epi64(_val23_16, 78); #if __AVXVNNI__ || __AVX512VNNI__ _sum04_15 = _mm256_dpwssd_epi32(_sum04_15, _val23_16, _w01_16); _sum14_05 = _mm256_dpwssd_epi32(_sum14_05, _val32_16, _w01_16); _sum06_17 = _mm256_dpwssd_epi32(_sum06_17, _val23_16, _w23_16); _sum16_07 = _mm256_dpwssd_epi32(_sum16_07, _val32_16, _w23_16); #else __m256i _sl04_15 = _mm256_mullo_epi16(_val23_16, _w01_16); __m256i _sh04_15 = _mm256_mulhi_epi16(_val23_16, _w01_16); __m256i _sl14_05 = _mm256_mullo_epi16(_val32_16, _w01_16); __m256i _sh14_05 = _mm256_mulhi_epi16(_val32_16, _w01_16); __m256i _sl06_17 = _mm256_mullo_epi16(_val23_16, _w23_16); __m256i _sh06_17 = _mm256_mulhi_epi16(_val23_16, _w23_16); __m256i _sl16_07 = _mm256_mullo_epi16(_val32_16, _w23_16); __m256i _sh16_07 = _mm256_mulhi_epi16(_val32_16, _w23_16); _sum04_15 = _mm256_add_epi32(_sum04_15, _mm256_unpacklo_epi16(_sl04_15, _sh04_15)); _sum14_05 = _mm256_add_epi32(_sum14_05, _mm256_unpacklo_epi16(_sl14_05, _sh14_05)); _sum06_17 = _mm256_add_epi32(_sum06_17, _mm256_unpacklo_epi16(_sl06_17, _sh06_17)); _sum16_07 = _mm256_add_epi32(_sum16_07, _mm256_unpacklo_epi16(_sl16_07, _sh16_07)); _sum04_15 = _mm256_add_epi32(_sum04_15, _mm256_unpackhi_epi16(_sl04_15, _sh04_15)); _sum14_05 = _mm256_add_epi32(_sum14_05, _mm256_unpackhi_epi16(_sl14_05, _sh14_05)); _sum06_17 = _mm256_add_epi32(_sum06_17, _mm256_unpackhi_epi16(_sl06_17, _sh06_17)); _sum16_07 = _mm256_add_epi32(_sum16_07, _mm256_unpackhi_epi16(_sl16_07, _sh16_07)); #endif tmpptr += 32; kptr0 += 32; } // transpose 4x8 { __m256i _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = _mm256_unpacklo_epi32(_sum00_11, _sum10_01); _tmp1 = _mm256_unpacklo_epi32(_sum02_13, _sum12_03); _tmp2 = _mm256_unpackhi_epi32(_sum00_11, _sum10_01); _tmp3 = _mm256_unpackhi_epi32(_sum02_13, _sum12_03); _sum00_11 = _mm256_unpacklo_epi64(_tmp0, _tmp1); _sum10_01 = _mm256_unpackhi_epi64(_tmp0, _tmp1); _sum02_13 = _mm256_unpacklo_epi64(_tmp2, _tmp3); _sum12_03 = _mm256_unpackhi_epi64(_tmp2, _tmp3); } { __m256i _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = _mm256_unpacklo_epi32(_sum04_15, _sum14_05); _tmp1 = _mm256_unpacklo_epi32(_sum06_17, _sum16_07); _tmp2 = _mm256_unpackhi_epi32(_sum04_15, _sum14_05); _tmp3 = _mm256_unpackhi_epi32(_sum06_17, _sum16_07); _sum04_15 = _mm256_unpacklo_epi64(_tmp0, _tmp1); _sum14_05 = _mm256_unpackhi_epi64(_tmp0, _tmp1); _sum06_17 = _mm256_unpacklo_epi64(_tmp2, _tmp3); _sum16_07 = _mm256_unpackhi_epi64(_tmp2, _tmp3); } _sum00_11 = _mm256_add_epi32(_sum00_11, _sum10_01); _sum02_13 = _mm256_add_epi32(_sum02_13, _sum12_03); _sum00_11 = _mm256_add_epi32(_sum00_11, _sum02_13); _sum04_15 = _mm256_add_epi32(_sum04_15, _sum14_05); _sum06_17 = _mm256_add_epi32(_sum06_17, _sum16_07); _sum04_15 = _mm256_add_epi32(_sum04_15, _sum06_17); __m256i _perm_mask = _mm256_set_epi32(6, 3, 4, 1, 7, 2, 5, 0); _sum00_11 = _mm256_permutevar8x32_epi32(_sum00_11, _perm_mask); _sum04_15 = _mm256_permutevar8x32_epi32(_sum04_15, _perm_mask); int sum[16]; _mm256_storeu_si256((__m256i*)sum, _sum00_11); _mm256_storeu_si256((__m256i*)(sum + 8), _sum04_15); outptr0[0] = sum[0]; outptr1[0] = sum[1]; outptr2[0] = sum[2]; outptr3[0] = sum[3]; outptr0[1] = sum[4]; outptr1[1] = sum[5]; outptr2[1] = sum[6]; outptr3[1] = sum[7]; outptr0[2] = sum[8]; outptr1[2] = sum[9]; outptr2[2] = sum[10]; outptr3[2] = sum[11]; outptr0[3] = sum[12]; outptr1[3] = sum[13]; outptr2[3] = sum[14]; outptr3[3] = sum[15]; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } #endif for (; i + 1 < size; i += 2) { #if __AVX2__ const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2); #else const signed char* tmpptr = tmp.channel(i / 2); #endif const signed char* kptr0 = kernel.channel(p / 4); int nn = inch * maxk; // inch always > 0 #if __AVX2__ __m256i _sum00_11 = _mm256_setzero_si256(); __m256i _sum10_01 = _mm256_setzero_si256(); __m256i _sum02_13 = _mm256_setzero_si256(); __m256i _sum12_03 = _mm256_setzero_si256(); #else __m128i _sum00 = _mm_setzero_si128(); __m128i _sum01 = _mm_setzero_si128(); __m128i _sum02 = _mm_setzero_si128(); __m128i _sum03 = _mm_setzero_si128(); __m128i _sum10 = _mm_setzero_si128(); __m128i _sum11 = _mm_setzero_si128(); __m128i _sum12 = _mm_setzero_si128(); __m128i _sum13 = _mm_setzero_si128(); #endif int j = 0; for (; j < nn; j++) { #if __AVX2__ __m128i _val01 = _mm_loadu_si128((const __m128i*)tmpptr); __m256i _val01_16 = _mm256_cvtepi8_epi16(_val01); __m128i _w01 = _mm_loadu_si128((const __m128i*)kptr0); __m128i _w23 = _mm_loadu_si128((const __m128i*)(kptr0 + 16)); __m256i _w01_16 = _mm256_cvtepi8_epi16(_w01); __m256i _w23_16 = _mm256_cvtepi8_epi16(_w23); __m256i _val10_16 = _mm256_permute4x64_epi64(_val01_16, 78); #if __AVXVNNI__ || __AVX512VNNI__ _sum00_11 = _mm256_dpwssd_epi32(_sum00_11, _val01_16, _w01_16); _sum10_01 = _mm256_dpwssd_epi32(_sum10_01, _val10_16, _w01_16); _sum02_13 = _mm256_dpwssd_epi32(_sum02_13, _val01_16, _w23_16); _sum12_03 = _mm256_dpwssd_epi32(_sum12_03, _val10_16, _w23_16); #else __m256i _sl00_11 = _mm256_mullo_epi16(_val01_16, _w01_16); __m256i _sh00_11 = _mm256_mulhi_epi16(_val01_16, _w01_16); __m256i _sl10_01 = _mm256_mullo_epi16(_val10_16, _w01_16); __m256i _sh10_01 = _mm256_mulhi_epi16(_val10_16, _w01_16); __m256i _sl02_13 = _mm256_mullo_epi16(_val01_16, _w23_16); __m256i _sh02_13 = _mm256_mulhi_epi16(_val01_16, _w23_16); __m256i _sl12_03 = _mm256_mullo_epi16(_val10_16, _w23_16); __m256i _sh12_03 = _mm256_mulhi_epi16(_val10_16, _w23_16); _sum00_11 = _mm256_add_epi32(_sum00_11, _mm256_unpacklo_epi16(_sl00_11, _sh00_11)); _sum10_01 = _mm256_add_epi32(_sum10_01, _mm256_unpacklo_epi16(_sl10_01, _sh10_01)); _sum02_13 = _mm256_add_epi32(_sum02_13, _mm256_unpacklo_epi16(_sl02_13, _sh02_13)); _sum12_03 = _mm256_add_epi32(_sum12_03, _mm256_unpacklo_epi16(_sl12_03, _sh12_03)); _sum00_11 = _mm256_add_epi32(_sum00_11, _mm256_unpackhi_epi16(_sl00_11, _sh00_11)); _sum10_01 = _mm256_add_epi32(_sum10_01, _mm256_unpackhi_epi16(_sl10_01, _sh10_01)); _sum02_13 = _mm256_add_epi32(_sum02_13, _mm256_unpackhi_epi16(_sl02_13, _sh02_13)); _sum12_03 = _mm256_add_epi32(_sum12_03, _mm256_unpackhi_epi16(_sl12_03, _sh12_03)); #endif #else __m128i _val01 = _mm_loadu_si128((const __m128i*)tmpptr); __m128i _extval01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _val01); __m128i _val0 = _mm_unpacklo_epi8(_val01, _extval01); __m128i _val1 = _mm_unpackhi_epi8(_val01, _extval01); __m128i _w01 = _mm_loadu_si128((const __m128i*)kptr0); __m128i _w23 = _mm_loadu_si128((const __m128i*)(kptr0 + 16)); __m128i _extw01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w01); __m128i _extw23 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w23); __m128i _w0 = _mm_unpacklo_epi8(_w01, _extw01); __m128i _w1 = _mm_unpackhi_epi8(_w01, _extw01); __m128i _w2 = _mm_unpacklo_epi8(_w23, _extw23); __m128i _w3 = _mm_unpackhi_epi8(_w23, _extw23); #if __XOP__ _sum00 = _mm_maddd_epi16(_val0, _w0, _sum00); _sum01 = _mm_maddd_epi16(_val0, _w1, _sum01); _sum02 = _mm_maddd_epi16(_val0, _w2, _sum02); _sum03 = _mm_maddd_epi16(_val0, _w3, _sum03); _sum10 = _mm_maddd_epi16(_val1, _w0, _sum10); _sum11 = _mm_maddd_epi16(_val1, _w1, _sum11); _sum12 = _mm_maddd_epi16(_val1, _w2, _sum12); _sum13 = _mm_maddd_epi16(_val1, _w3, _sum13); #else __m128i _sl00 = _mm_mullo_epi16(_val0, _w0); __m128i _sh00 = _mm_mulhi_epi16(_val0, _w0); __m128i _sl01 = _mm_mullo_epi16(_val0, _w1); __m128i _sh01 = _mm_mulhi_epi16(_val0, _w1); __m128i _sl02 = _mm_mullo_epi16(_val0, _w2); __m128i _sh02 = _mm_mulhi_epi16(_val0, _w2); __m128i _sl03 = _mm_mullo_epi16(_val0, _w3); __m128i _sh03 = _mm_mulhi_epi16(_val0, _w3); __m128i _sl10 = _mm_mullo_epi16(_val1, _w0); __m128i _sh10 = _mm_mulhi_epi16(_val1, _w0); __m128i _sl11 = _mm_mullo_epi16(_val1, _w1); __m128i _sh11 = _mm_mulhi_epi16(_val1, _w1); __m128i _sl12 = _mm_mullo_epi16(_val1, _w2); __m128i _sh12 = _mm_mulhi_epi16(_val1, _w2); __m128i _sl13 = _mm_mullo_epi16(_val1, _w3); __m128i _sh13 = _mm_mulhi_epi16(_val1, _w3); _sum00 = _mm_add_epi32(_sum00, _mm_unpacklo_epi16(_sl00, _sh00)); _sum01 = _mm_add_epi32(_sum01, _mm_unpacklo_epi16(_sl01, _sh01)); _sum02 = _mm_add_epi32(_sum02, _mm_unpacklo_epi16(_sl02, _sh02)); _sum03 = _mm_add_epi32(_sum03, _mm_unpacklo_epi16(_sl03, _sh03)); _sum00 = _mm_add_epi32(_sum00, _mm_unpackhi_epi16(_sl00, _sh00)); _sum01 = _mm_add_epi32(_sum01, _mm_unpackhi_epi16(_sl01, _sh01)); _sum02 = _mm_add_epi32(_sum02, _mm_unpackhi_epi16(_sl02, _sh02)); _sum03 = _mm_add_epi32(_sum03, _mm_unpackhi_epi16(_sl03, _sh03)); _sum10 = _mm_add_epi32(_sum10, _mm_unpacklo_epi16(_sl10, _sh10)); _sum11 = _mm_add_epi32(_sum11, _mm_unpacklo_epi16(_sl11, _sh11)); _sum12 = _mm_add_epi32(_sum12, _mm_unpacklo_epi16(_sl12, _sh12)); _sum13 = _mm_add_epi32(_sum13, _mm_unpacklo_epi16(_sl13, _sh13)); _sum10 = _mm_add_epi32(_sum10, _mm_unpackhi_epi16(_sl10, _sh10)); _sum11 = _mm_add_epi32(_sum11, _mm_unpackhi_epi16(_sl11, _sh11)); _sum12 = _mm_add_epi32(_sum12, _mm_unpackhi_epi16(_sl12, _sh12)); _sum13 = _mm_add_epi32(_sum13, _mm_unpackhi_epi16(_sl13, _sh13)); #endif #endif tmpptr += 16; kptr0 += 32; } #if __AVX2__ // transpose 4x8 { __m256i _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = _mm256_unpacklo_epi32(_sum00_11, _sum10_01); _tmp1 = _mm256_unpacklo_epi32(_sum02_13, _sum12_03); _tmp2 = _mm256_unpackhi_epi32(_sum00_11, _sum10_01); _tmp3 = _mm256_unpackhi_epi32(_sum02_13, _sum12_03); _sum00_11 = _mm256_unpacklo_epi64(_tmp0, _tmp1); _sum10_01 = _mm256_unpackhi_epi64(_tmp0, _tmp1); _sum02_13 = _mm256_unpacklo_epi64(_tmp2, _tmp3); _sum12_03 = _mm256_unpackhi_epi64(_tmp2, _tmp3); } _sum00_11 = _mm256_add_epi32(_sum00_11, _sum10_01); _sum02_13 = _mm256_add_epi32(_sum02_13, _sum12_03); _sum00_11 = _mm256_add_epi32(_sum00_11, _sum02_13); __m256i _perm_mask = _mm256_set_epi32(6, 3, 4, 1, 7, 2, 5, 0); _sum00_11 = _mm256_permutevar8x32_epi32(_sum00_11, _perm_mask); int sum[8]; _mm256_storeu_si256((__m256i*)sum, _sum00_11); #else // transpose 4x4 { __m128i _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = _mm_unpacklo_epi32(_sum00, _sum01); _tmp1 = _mm_unpacklo_epi32(_sum02, _sum03); _tmp2 = _mm_unpackhi_epi32(_sum00, _sum01); _tmp3 = _mm_unpackhi_epi32(_sum02, _sum03); _sum00 = _mm_unpacklo_epi64(_tmp0, _tmp1); _sum01 = _mm_unpackhi_epi64(_tmp0, _tmp1); _sum02 = _mm_unpacklo_epi64(_tmp2, _tmp3); _sum03 = _mm_unpackhi_epi64(_tmp2, _tmp3); } { __m128i _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = _mm_unpacklo_epi32(_sum10, _sum11); _tmp1 = _mm_unpacklo_epi32(_sum12, _sum13); _tmp2 = _mm_unpackhi_epi32(_sum10, _sum11); _tmp3 = _mm_unpackhi_epi32(_sum12, _sum13); _sum10 = _mm_unpacklo_epi64(_tmp0, _tmp1); _sum11 = _mm_unpackhi_epi64(_tmp0, _tmp1); _sum12 = _mm_unpacklo_epi64(_tmp2, _tmp3); _sum13 = _mm_unpackhi_epi64(_tmp2, _tmp3); } _sum00 = _mm_add_epi32(_sum00, _sum01); _sum02 = _mm_add_epi32(_sum02, _sum03); _sum10 = _mm_add_epi32(_sum10, _sum11); _sum12 = _mm_add_epi32(_sum12, _sum13); _sum00 = _mm_add_epi32(_sum00, _sum02); _sum10 = _mm_add_epi32(_sum10, _sum12); int sum[8]; _mm_storeu_si128((__m128i*)sum, _sum00); _mm_storeu_si128((__m128i*)(sum + 4), _sum10); #endif outptr0[0] = sum[0]; outptr1[0] = sum[1]; outptr2[0] = sum[2]; outptr3[0] = sum[3]; outptr0[1] = sum[4]; outptr1[1] = sum[5]; outptr2[1] = sum[6]; outptr3[1] = sum[7]; outptr0 += 2; outptr1 += 2; outptr2 += 2; outptr3 += 2; } for (; i < size; i++) { #if __AVX2__ const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2); #else const signed char* tmpptr = tmp.channel(i / 2 + i % 2); #endif const signed char* kptr0 = kernel.channel(p / 4); int nn = inch * maxk; // inch always > 0 #if __AVX2__ __m256i _sum0_1 = _mm256_setzero_si256(); __m256i _sum2_3 = _mm256_setzero_si256(); #else __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); __m128i _sum2 = _mm_setzero_si128(); __m128i _sum3 = _mm_setzero_si128(); #endif int j = 0; for (; j < nn; j++) { #if __AVX2__ __m128i _val = _mm_loadl_epi64((const __m128i*)tmpptr); _val = _mm_cvtepi8_epi16(_val); __m128i _w01 = _mm_loadu_si128((const __m128i*)kptr0); __m128i _w23 = _mm_loadu_si128((const __m128i*)(kptr0 + 16)); __m256i _w01_16 = _mm256_cvtepi8_epi16(_w01); __m256i _w23_16 = _mm256_cvtepi8_epi16(_w23); __m256i _valval = _mm256_inserti128_si256(_mm256_castsi128_si256(_val), _val, 1); #if __AVXVNNI__ || __AVX512VNNI__ _sum0_1 = _mm256_dpwssd_epi32(_sum0_1, _valval, _w01_16); _sum2_3 = _mm256_dpwssd_epi32(_sum2_3, _valval, _w23_16); #else __m256i _sl0_1 = _mm256_mullo_epi16(_valval, _w01_16); __m256i _sh0_1 = _mm256_mulhi_epi16(_valval, _w01_16); __m256i _sl2_3 = _mm256_mullo_epi16(_valval, _w23_16); __m256i _sh2_3 = _mm256_mulhi_epi16(_valval, _w23_16); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpacklo_epi16(_sl0_1, _sh0_1)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpacklo_epi16(_sl2_3, _sh2_3)); _sum0_1 = _mm256_add_epi32(_sum0_1, _mm256_unpackhi_epi16(_sl0_1, _sh0_1)); _sum2_3 = _mm256_add_epi32(_sum2_3, _mm256_unpackhi_epi16(_sl2_3, _sh2_3)); #endif #else __m128i _val = _mm_loadl_epi64((const __m128i*)tmpptr); #if __SSE4_1__ _val = _mm_cvtepi8_epi16(_val); #else _val = _mm_unpacklo_epi8(_val, _mm_cmpgt_epi8(_mm_setzero_si128(), _val)); #endif __m128i _w01 = _mm_loadu_si128((const __m128i*)kptr0); __m128i _w23 = _mm_loadu_si128((const __m128i*)(kptr0 + 16)); __m128i _extw01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w01); __m128i _extw23 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w23); __m128i _w0 = _mm_unpacklo_epi8(_w01, _extw01); __m128i _w1 = _mm_unpackhi_epi8(_w01, _extw01); __m128i _w2 = _mm_unpacklo_epi8(_w23, _extw23); __m128i _w3 = _mm_unpackhi_epi8(_w23, _extw23); #if __XOP__ _sum0 = _mm_maddd_epi16(_val, _w0, _sum0); _sum1 = _mm_maddd_epi16(_val, _w1, _sum1); _sum2 = _mm_maddd_epi16(_val, _w2, _sum2); _sum3 = _mm_maddd_epi16(_val, _w3, _sum3); #else __m128i _sl0 = _mm_mullo_epi16(_val, _w0); __m128i _sh0 = _mm_mulhi_epi16(_val, _w0); __m128i _sl1 = _mm_mullo_epi16(_val, _w1); __m128i _sh1 = _mm_mulhi_epi16(_val, _w1); __m128i _sl2 = _mm_mullo_epi16(_val, _w2); __m128i _sh2 = _mm_mulhi_epi16(_val, _w2); __m128i _sl3 = _mm_mullo_epi16(_val, _w3); __m128i _sh3 = _mm_mulhi_epi16(_val, _w3); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0)); _sum1 = _mm_add_epi32(_sum1, _mm_unpacklo_epi16(_sl1, _sh1)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl2, _sh2)); _sum3 = _mm_add_epi32(_sum3, _mm_unpacklo_epi16(_sl3, _sh3)); _sum0 = _mm_add_epi32(_sum0, _mm_unpackhi_epi16(_sl0, _sh0)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl1, _sh1)); _sum2 = _mm_add_epi32(_sum2, _mm_unpackhi_epi16(_sl2, _sh2)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl3, _sh3)); #endif #endif tmpptr += 8; kptr0 += 32; } #if __AVX2__ __m128i _sum0 = _mm256_extracti128_si256(_sum0_1, 0); __m128i _sum1 = _mm256_extracti128_si256(_sum0_1, 1); __m128i _sum2 = _mm256_extracti128_si256(_sum2_3, 0); __m128i _sum3 = _mm256_extracti128_si256(_sum2_3, 1); #endif // transpose 4x4 { __m128i _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = _mm_unpacklo_epi32(_sum0, _sum1); _tmp1 = _mm_unpacklo_epi32(_sum2, _sum3); _tmp2 = _mm_unpackhi_epi32(_sum0, _sum1); _tmp3 = _mm_unpackhi_epi32(_sum2, _sum3); _sum0 = _mm_unpacklo_epi64(_tmp0, _tmp1); _sum1 = _mm_unpackhi_epi64(_tmp0, _tmp1); _sum2 = _mm_unpacklo_epi64(_tmp2, _tmp3); _sum3 = _mm_unpackhi_epi64(_tmp2, _tmp3); } _sum0 = _mm_add_epi32(_sum0, _sum1); _sum2 = _mm_add_epi32(_sum2, _sum3); _sum0 = _mm_add_epi32(_sum0, _sum2); int sum[4]; _mm_storeu_si128((__m128i*)sum, _sum0); outptr0[0] = sum[0]; outptr1[0] = sum[1]; outptr2[0] = sum[2]; outptr3[0] = sum[3]; outptr0 += 1; outptr1 += 1; outptr2 += 1; outptr3 += 1; } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { int* outptr0 = top_blob.channel(p); int i = 0; #if __AVX2__ for (; i + 3 < size; i += 4) { const signed char* tmpptr = tmp.channel(i / 4); const signed char* kptr0 = kernel.channel(p / 4 + p % 4); int nn = inch * maxk; // inch always > 0 __m256i _sum0_2 = _mm256_setzero_si256(); __m256i _sum1_3 = _mm256_setzero_si256(); __m256i _sum4_6 = _mm256_setzero_si256(); __m256i _sum5_7 = _mm256_setzero_si256(); int j = 0; for (; j < nn; j++) { __m128i _val01 = _mm_loadu_si128((const __m128i*)tmpptr); __m128i _val23 = _mm_loadu_si128((const __m128i*)(tmpptr + 16)); __m256i _val01_16 = _mm256_cvtepi8_epi16(_val01); __m256i _val23_16 = _mm256_cvtepi8_epi16(_val23); __m128i _w01 = _mm_loadl_epi64((const __m128i*)kptr0); __m256i _w01_16 = _mm256_cvtepi8_epi16(_w01); _w01_16 = _mm256_permute4x64_epi64(_w01_16, _MM_SHUFFLE(1, 0, 1, 0)); __m256i _sl00_10 = _mm256_mullo_epi16(_val01_16, _w01_16); __m256i _sh00_10 = _mm256_mulhi_epi16(_val01_16, _w01_16); __m256i _sl20_30 = _mm256_mullo_epi16(_val23_16, _w01_16); __m256i _sh20_30 = _mm256_mulhi_epi16(_val23_16, _w01_16); _sum0_2 = _mm256_add_epi32(_sum0_2, _mm256_unpacklo_epi16(_sl00_10, _sh00_10)); _sum1_3 = _mm256_add_epi32(_sum1_3, _mm256_unpackhi_epi16(_sl00_10, _sh00_10)); _sum4_6 = _mm256_add_epi32(_sum4_6, _mm256_unpacklo_epi16(_sl20_30, _sh20_30)); _sum5_7 = _mm256_add_epi32(_sum5_7, _mm256_unpackhi_epi16(_sl20_30, _sh20_30)); tmpptr += 32; kptr0 += 8; } _sum0_2 = _mm256_add_epi32(_sum0_2, _sum1_3); _sum4_6 = _mm256_add_epi32(_sum4_6, _sum5_7); __m128i _sum0 = _mm256_extracti128_si256(_sum0_2, 0); __m128i _sum2 = _mm256_extracti128_si256(_sum0_2, 1); __m128i _sum4 = _mm256_extracti128_si256(_sum4_6, 0); __m128i _sum6 = _mm256_extracti128_si256(_sum4_6, 1); outptr0[0] = _mm_reduce_add_epi32(_sum0); outptr0[1] = _mm_reduce_add_epi32(_sum2); outptr0[2] = _mm_reduce_add_epi32(_sum4); outptr0[3] = _mm_reduce_add_epi32(_sum6); outptr0 += 4; } #endif for (; i + 1 < size; i += 2) { #if __AVX2__ const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2); #else const signed char* tmpptr = tmp.channel(i / 2); #endif const signed char* kptr0 = kernel.channel(p / 4 + p % 4); int nn = inch * maxk; // inch always > 0 #if __AVX2__ __m256i _sum0_2 = _mm256_setzero_si256(); __m256i _sum1_3 = _mm256_setzero_si256(); #else __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); __m128i _sum2 = _mm_setzero_si128(); __m128i _sum3 = _mm_setzero_si128(); #endif int j = 0; for (; j < nn; j++) { #if __AVX2__ __m128i _val01 = _mm_loadu_si128((const __m128i*)tmpptr); __m256i _val01_16 = _mm256_cvtepi8_epi16(_val01); __m128i _w01 = _mm_loadl_epi64((const __m128i*)kptr0); __m256i _w01_16 = _mm256_cvtepi8_epi16(_w01); _w01_16 = _mm256_permute4x64_epi64(_w01_16, _MM_SHUFFLE(1, 0, 1, 0)); __m256i _sl00_10 = _mm256_mullo_epi16(_val01_16, _w01_16); __m256i _sh00_10 = _mm256_mulhi_epi16(_val01_16, _w01_16); _sum0_2 = _mm256_add_epi32(_sum0_2, _mm256_unpacklo_epi16(_sl00_10, _sh00_10)); _sum1_3 = _mm256_add_epi32(_sum1_3, _mm256_unpackhi_epi16(_sl00_10, _sh00_10)); #else __m128i _val01 = _mm_loadu_si128((const __m128i*)tmpptr); __m128i _extval01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _val01); __m128i _val0 = _mm_unpacklo_epi8(_val01, _extval01); __m128i _val1 = _mm_unpackhi_epi8(_val01, _extval01); __m128i _w01 = _mm_loadl_epi64((const __m128i*)kptr0); #if __SSE4_1__ __m128i _w0 = _mm_cvtepi8_epi16(_w01); #else __m128i _extw01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w01); __m128i _w0 = _mm_unpacklo_epi8(_w01, _extw01); #endif __m128i _sl00 = _mm_mullo_epi16(_val0, _w0); __m128i _sh00 = _mm_mulhi_epi16(_val0, _w0); __m128i _sl10 = _mm_mullo_epi16(_val1, _w0); __m128i _sh10 = _mm_mulhi_epi16(_val1, _w0); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl00, _sh00)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl00, _sh00)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl10, _sh10)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl10, _sh10)); #endif tmpptr += 16; kptr0 += 8; } #if __AVX2__ _sum0_2 = _mm256_add_epi32(_sum0_2, _sum1_3); __m128i _sum0 = _mm256_extracti128_si256(_sum0_2, 0); __m128i _sum2 = _mm256_extracti128_si256(_sum0_2, 1); #else _sum0 = _mm_add_epi32(_sum0, _sum1); _sum2 = _mm_add_epi32(_sum2, _sum3); #endif outptr0[0] = _mm_reduce_add_epi32(_sum0); outptr0[1] = _mm_reduce_add_epi32(_sum2); outptr0 += 2; } for (; i < size; i++) { #if __AVX2__ const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2); #else const signed char* tmpptr = tmp.channel(i / 2 + i % 2); #endif const signed char* kptr0 = kernel.channel(p / 4 + p % 4); int nn = inch * maxk; // inch always > 0 __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); int j = 0; for (; j < nn; j++) { __m128i _val01 = _mm_loadl_epi64((const __m128i*)tmpptr); #if __SSE4_1__ __m128i _val0 = _mm_cvtepi8_epi16(_val01); #else __m128i _extval01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _val01); __m128i _val0 = _mm_unpacklo_epi8(_val01, _extval01); #endif __m128i _w01 = _mm_loadl_epi64((const __m128i*)kptr0); #if __SSE4_1__ __m128i _w0 = _mm_cvtepi8_epi16(_w01); #else __m128i _extw01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w01); __m128i _w0 = _mm_unpacklo_epi8(_w01, _extw01); #endif __m128i _sl00 = _mm_mullo_epi16(_val0, _w0); __m128i _sh00 = _mm_mulhi_epi16(_val0, _w0); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl00, _sh00)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl00, _sh00)); tmpptr += 8; kptr0 += 8; } _sum0 = _mm_add_epi32(_sum0, _sum1); outptr0[0] = _mm_reduce_add_epi32(_sum0); outptr0 += 1; } } } static void convolution_im2col_sgemm_transform_kernel_pack8to1_int8_sse(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h) { const int maxk = kernel_w * kernel_h; // interleave // src = maxk-inch-outch // dst = 8a-4b-maxk-inch/8a-outch/4b Mat kernel = _kernel.reshape(maxk, inch, outch); if (outch >= 4) kernel_tm.create(32 * maxk, inch / 8, outch / 4 + outch % 4, (size_t)1u); else kernel_tm.create(8 * maxk, inch / 8, outch, (size_t)1u); int q = 0; for (; q + 3 < outch; q += 4) { signed char* g00 = kernel_tm.channel(q / 4); for (int p = 0; p + 7 < inch; p += 8) { for (int k = 0; k < maxk; k++) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 8; j++) { const signed char* k00 = kernel.channel(q + i).row<const signed char>(p + j); g00[0] = k00[k]; g00++; } } } } } // TODO unroll 2 for (; q < outch; q++) { signed char* g00 = kernel_tm.channel(q / 4 + q % 4); for (int p = 0; p + 7 < inch; p += 8) { for (int k = 0; k < maxk; k++) { for (int j = 0; j < 8; j++) { const signed char* k00 = kernel.channel(q).row<const signed char>(p + j); g00[0] = k00[k]; g00++; } } } } } static void convolution_im2col_sgemm_pack8to1_int8_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int size = outw * outh; const int maxk = kernel_w * kernel_h; // im2col Mat bottom_im2col(size, maxk, inch, 8u, 8, opt.workspace_allocator); { const int gap = w * stride_h - outw * stride_w; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < inch; p++) { const Mat img = bottom_blob.channel(p); int64_t* ptr = bottom_im2col.channel(p); for (int u = 0; u < kernel_h; u++) { for (int v = 0; v < kernel_w; v++) { const int64_t* sptr = img.row<const int64_t>(dilation_h * u) + dilation_w * v; for (int i = 0; i < outh; i++) { int j = 0; for (; j < outw; j++) { ptr[0] = sptr[0]; sptr += stride_w; ptr += 1; } sptr += gap; } } } } } im2col_sgemm_pack8to1_int8_sse(bottom_im2col, top_blob, kernel, opt); }
laplace2d-04s.c
/* * Copyright 2012 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <math.h> #include <string.h> #include <stdio.h> #include <omp.h> #define NN 4096 #define NM 4096 double A[NN][NM]; double Anew[NN][NM]; int main(int argc, char** argv) { const int n = NN; const int m = NM; const int iter_max = 200; const double tol = 1.0e-6; double error = 1.0; memset(A, 0, n * m * sizeof(double)); memset(Anew, 0, n * m * sizeof(double)); for (int j = 0; j < n; j++) { A[j][0] = 1.0; Anew[j][0] = 1.0; } printf("Jacobi relaxation Calculation: %d x %d mesh\n", n, m); double st = omp_get_wtime(); int iter = 0; #pragma omp target data map(alloc:Anew) map(A) while ( error > tol && iter < iter_max ) { error = 0.0; #pragma omp target teams distribute for( int j = 1; j < n-1; j++) { #pragma omp parallel for reduction(max:error) for( int i = 1; i < m-1; i++ ) { Anew[j][i] = 0.25 * ( A[j][i+1] + A[j][i-1] + A[j-1][i] + A[j+1][i]); error = fmax( error, fabs(Anew[j][i] - A[j][i])); } } #pragma omp target teams distribute for( int j = 1; j < n-1; j++) { #pragma omp parallel for for( int i = 1; i < m-1; i++ ) { A[j][i] = Anew[j][i]; } } if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error); iter++; } double et = omp_get_wtime(); printf(" total: %f s\n", (et - st)); return 0; }
mmGPU.c
/* Tempo sequencial: real 0m31,842s user 0m31,713s sys 0m0,083s real 0m30,929s user 0m30,789s sys 0m0,074s real 0m31,569s user 0m31,408s sys 0m0,077s real 0m30,880s user 0m30,749s sys 0m0,067s real 0m31,120s user 0m30,967s sys 0m0,087s Tempo Paralelo - Multicore: real 0m9,663s user 1m1,498s sys 0m2,830s real 0m9,897s user 1m1,072s sys 0m2,809s real 0m9,767s user 1m0,906s sys 0m2,798s real 0m9,857s user 1m1,442s sys 0m2,972s real 0m9,709s user 1m1,580s sys 0m3,002s Tempo paralelo - GPU distribute real 0m30,728s user 0m30,683s sys 0m0,184s real 0m30,883s user 0m30,952s sys 0m0,122s real 0m31,138s user 0m31,304s sys 0m0,087s real 0m31,675s user 0m31,759s sys 0m0,050s real 0m31,450s user 0m31,600s sys 0m0,043s distribute parallel for real 0m9,370s user 0m54,341s sys 0m0,196s real 0m9,421s user 0m55,248s sys 0m0,227s real 0m8,649s user 0m59,349s sys 0m0,220s real 0m8,653s user 0m59,911s sys 0m0,234s real 0m8,644s user 0m59,108s sys 0m0,195s distribute parallel for simd real 0m9,144s user 0m56,485s sys 0m0,878s real 0m9,119s user 0m58,920s sys 0m0,247s real 0m8,835s user 0m57,115s sys 0m0,208s real 0m8,842s user 0m57,008s sys 0m0,170s real 0m8,984s user 0m56,533s sys 0m0,232s */ #include <stdio.h> #include <stdlib.h> void mm(double *a, double *b, double *c, int width) { #pragma omp target map(to \ : a [0:(width * width)], b [0:(width * width)]) map(from \ : c [0:(width * width)]) #pragma omp teams distribute parallel for for (int i = 0; i < width; i++) { for (int j = 0; j < width; j++) { double sum = 0; for (int k = 0; k < width; k++) { double x = a[i * width + k]; double y = b[k * width + j]; sum += x * y; } c[i * width + j] = sum; } } } int main() { int width = 2000; double *a = (double *)malloc(width * width * sizeof(double)); double *b = (double *)malloc(width * width * sizeof(double)); double *c = (double *)malloc(width * width * sizeof(double)); #pragma omp parallel for collapse(2) for (int i = 0; i < width; i++) { for (int j = 0; j < width; j++) { a[i * width + j] = i; b[i * width + j] = j; c[i * width + j] = 0; } } mm(a, b, c, width); }
tools.h
#ifndef YGGTOOLS_H_ #define YGGTOOLS_H_ #ifdef _MSC_VER #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS 1 #endif #endif #ifdef _OPENMP #include <omp.h> #endif #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <errno.h> #include <time.h> #ifdef USE_OSR_YGG struct complex_float{ float re; float im; }; struct complex_double{ double re; double im; }; struct complex_long_double{ long double re; long double im; }; typedef struct complex_float complex_float; typedef struct complex_double complex_double; typedef struct complex_long_double complex_long_double; #define creal(x) x.re #define crealf(x) x.re #define creall(x) x.re #define cimag(x) x.im #define cimagf(x) x.im #define cimagl(x) x.im #else /*USE_YGG_OSR*/ #ifdef _MSC_VER #ifdef __cplusplus #include <complex> typedef std::complex<float> complex_float; typedef std::complex<double> complex_double; typedef std::complex<long double> complex_long_double; #ifndef creal #define creal(x) x.real() #define crealf(x) x.real() #define creall(x) x.real() #define cimag(x) x.imag() #define cimagf(x) x.imag() #define cimagl(x) x.imag() #endif /*creal*/ #else /*__cplusplus*/ #include <complex.h> typedef _Fcomplex complex_float; typedef _Dcomplex complex_double; typedef _Lcomplex complex_long_double; #define print_complex(x) printf("%lf+%lfj\n", (double)(x._Val[0]), (double)(x._Val[1])) #endif /*__cplusplus*/ #else // Unix #ifdef __cplusplus #include <complex> typedef std::complex<float> complex_float; typedef std::complex<double> complex_double; typedef std::complex<long double> complex_long_double; #ifndef creal #define creal(x) x.real() #define crealf(x) x.real() #define creall(x) x.real() #define cimag(x) x.imag() #define cimagf(x) x.imag() #define cimagl(x) x.imag() #endif /*creal*/ #else /*__cplusplus*/ #include <complex.h> typedef float _Complex complex_float; typedef double _Complex complex_double; typedef long double _Complex complex_long_double; #endif /*__cplusplus*/ #endif /*Unix*/ #endif /*USE_YGG_OSR*/ #ifndef print_complex #define print_complex(x) printf("%lf+%lfj\n", (double)creal(x), (double)cimag(x)) #endif #ifdef __cplusplus /* If this is a C++ compiler, use C linkage */ extern "C" { #endif #include <math.h> // Required to prevent error when using mingw on windows #ifdef _DEBUG #undef _DEBUG #include <Python.h> #include <numpy/arrayobject.h> #include <numpy/ndarrayobject.h> #include <numpy/npy_common.h> #define _DEBUG #else #include <Python.h> #include <numpy/arrayobject.h> #include <numpy/ndarrayobject.h> #include <numpy/npy_common.h> #endif typedef struct complex_float_t { float re; float im; } complex_float_t; typedef struct complex_double_t { double re; double im; } complex_double_t; typedef struct complex_long_double_t { long double re; long double im; } complex_long_double_t; // Platform specific #ifdef _WIN32 #include "regex/regex_win32.h" #include "getline_win32.h" #else #include "regex_posix.h" #endif #ifdef _MSC_VER #include "windows_stdint.h" // Use local copy for MSVC support // Prevent windows.h from including winsock.h #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <process.h> #define ygg_getpid _getpid #define sleep(tsec) Sleep(1000*tsec) #define usleep(usec) Sleep(usec/1000) #else #include <stdint.h> #include <unistd.h> #define ygg_getpid getpid #endif #define STRBUFF 100 /*! @brief Maximum message size. */ #ifdef IPCDEF #define YGG_MSG_MAX 2048 #else #define YGG_MSG_MAX 1048576 #endif /*! @brief End of file message. */ #define YGG_MSG_EOF "EOF!!!" /*! @brief End of client message. */ #define YGG_CLIENT_EOF "YGG_END_CLIENT" /*! @brief Resonable size for buffer. */ #define YGG_MSG_BUF 2048 /*! @brief Sleep time in micro-seconds */ #define YGG_SLEEP_TIME 250000 /*! @brief Size for buffers to contain names of Python objects. */ #define PYTHON_NAME_SIZE 1000 /*! @brief Define old style names for compatibility. */ #define PSI_MSG_MAX YGG_MSG_MAX #define PSI_MSG_BUF YGG_MSG_BUF #define PSI_MSG_EOF YGG_MSG_EOF #ifdef PSI_DEBUG #define YGG_DEBUG PSI_DEBUG #endif static int _ygg_error_flag = 0; /*! @brief Define macros to allow counts of variables. */ // https://codecraft.co/2014/11/25/variadic-macros-tricks/ #ifdef _MSC_VER // https://stackoverflow.com/questions/48710758/how-to-fix-variadic-macro-related-issues-with-macro-overloading-in-msvc-mic #define MSVC_BUG(MACRO, ARGS) MACRO ARGS // name to remind that bug fix is due to MSVC :-) #define _GET_NTH_ARG_2(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, N, ...) N #define _GET_NTH_ARG(...) MSVC_BUG(_GET_NTH_ARG_2, (__VA_ARGS__)) #define COUNT_VARARGS(...) _GET_NTH_ARG("ignored", ##__VA_ARGS__, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) #define VA_MACRO(MACRO, ...) MSVC_BUG(CONCATE, (MACRO, COUNT_VARARGS(__VA_ARGS__)))(__VA_ARGS__) #else #define _GET_NTH_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, N, ...) N #define COUNT_VARARGS(...) _GET_NTH_ARG("ignored", ##__VA_ARGS__, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) #endif #define UNUSED(arg) ((void)&(arg)) /*! @brief Memory to allow thread association to be set via macro. */ static int global_thread_id = -1; #define ASSOCIATED_WITH_THREAD(COMM, THREAD) global_thread_id = THREAD; COMM; global_thread_id = -1; #ifdef _OPENMP #pragma omp threadprivate(global_thread_id) #endif /*! @brief Get an unsigned long seed from the least significant 32bits of a pointer. @param[in] ptr Pointer that should be turned into a seed. @return Unsigned long seed. */ static inline unsigned long ptr2seed(void *ptr) { uint64_t v = (uint64_t)ptr; unsigned long seed = (unsigned long)(v & 0xFFFFFFFFLL); return seed; }; /*! @brief Structure used to wrap va_list and allow pointer passing. @param va va_list Wrapped variable argument list. */ typedef struct va_list_t { va_list va; int using_ptrs; void **ptrs; int nptrs; int iptr; int for_fortran; } va_list_t; /*! @brief Structure used to wrap Python objects. */ typedef struct python_t { char name[PYTHON_NAME_SIZE]; void *args; void *kwargs; PyObject *obj; } python_t; /*! @brief Get the ID for the current thread (if inside one). @returns int Thread ID. */ static inline int get_thread_id() { int out = 0; if (global_thread_id >= 0) return global_thread_id; #ifdef _OPENMP if (omp_in_parallel()) out = omp_get_thread_num(); /* #elif defined pthread_self */ /* // TODO: Finalize/test support for pthread */ /* out = pthread_self(); */ #endif return out; }; /*! @brief Initialize a structure to contain a Python object. @returns python_t New Python object structure. */ static inline python_t init_python() { python_t out; out.name[0] = '\0'; out.args = NULL; out.kwargs = NULL; out.obj = NULL; return out; }; /*! @brief Initialize Numpy arrays if it is not initalized. @returns int 0 if successful, other values indicate errors. */ static inline int init_numpy_API() { int out = 0; #ifdef _OPENMP #pragma omp critical (numpy) { #endif if (PyArray_API == NULL) { if (_import_array() < 0) { PyErr_Print(); out = -2; } } #ifdef _OPENMP } #endif return out; }; /*! @brief Initialize Python if it is not initialized. @returns int 0 if successful, other values indicate errors. */ static inline int init_python_API() { int out = 0; #ifdef _OPENMP #pragma omp critical (python) { #endif if (!(Py_IsInitialized())) { char *name = getenv("YGG_PYTHON_EXEC"); if (name != NULL) { wchar_t *wname = Py_DecodeLocale(name, NULL); if (wname == NULL) { printf("Error decoding YGG_PYTHON_EXEC\n"); out = -1; } else { Py_SetProgramName(wname); PyMem_RawFree(wname); } } if (out >= 0) { Py_Initialize(); if (!(Py_IsInitialized())) out = -1; } } if (out >= 0) { out = init_numpy_API(); } #ifdef _OPENMP } #endif return out; }; //============================================================================== /*! Logging Alliases are set at compile-time based on the value of YGG_CLIENT_DEBUG. If set to INFO, only messages logged with info or error alias are printed. If set to DEBUG, messages logged with error, info or debug aliases are printed. Otherwise, only error messages are printed. If the YGG_CLIENT_DEBUG is changed, any code including this header must be recompiled for the change to take effect. */ //============================================================================== /*! @brief Print a log message. Prints a formatted message, prepending it with the process id and appending it with a newline. @param[in] prefix a constant character pointer to the prefix that should preceed the message and process id. @param[in] fmt a constant character pointer to a format string. @param[in] ap va_list of arguments to be formatted in the format string. */ static inline void yggLog(const char* prefix, const char* fmt, va_list ap) { fprintf(stdout, "%s: %d:%d ", prefix, ygg_getpid(), get_thread_id()); vfprintf(stdout, fmt, ap); fprintf(stdout, "\n"); fflush(stdout); }; /*! @brief Print an info log message. Prints a formatted message, prepending it with INFO and the process id. A newline character is added to the end of the message. @param[in] fmt a constant character pointer to a format string. @param[in] ... arguments to be formatted in the format string. */ static inline void yggInfo(const char* fmt, ...) { va_list ap; va_start(ap, fmt); yggLog("INFO", fmt, ap); va_end(ap); }; /*! @brief Print an debug log message. Prints a formatted message, prepending it with DEBUG and the process id. A newline character is added to the end of the message. @param[in] fmt a constant character pointer to a format string. @param[in] ... arguments to be formatted in the format string. */ static inline void yggDebug(const char* fmt, ...) { va_list ap; va_start(ap, fmt); yggLog("DEBUG", fmt, ap); va_end(ap); }; /*! @brief Print an error log message from a variable argument list. Prints a formatted message, prepending it with ERROR and the process id. A newline character is added to the end of the message. @param[in] fmt a constant character pointer to a format string. @param[in] ap va_list Variable argument list. @param[in] ... arguments to be formatted in the format string. */ static inline void yggError_va(const char* fmt, va_list ap) { yggLog("ERROR", fmt, ap); _ygg_error_flag = 1; }; /*! @brief Print an error log message. Prints a formatted message, prepending it with ERROR and the process id. A newline character is added to the end of the message. @param[in] fmt a constant character pointer to a format string. @param[in] ... arguments to be formatted in the format string. */ static inline void yggError(const char* fmt, ...) { va_list ap; va_start(ap, fmt); yggError_va(fmt, ap); va_end(ap); }; #ifdef YGG_DEBUG #if YGG_DEBUG <= 10 #define ygglog_error yggError #define ygglog_info yggInfo #define ygglog_debug yggDebug #elif YGG_DEBUG <= 20 #define ygglog_error yggError #define ygglog_info yggInfo #define ygglog_debug while (0) yggDebug #elif YGG_DEBUG <= 40 #define ygglog_error yggError #define ygglog_info while (0) yggInfo #define ygglog_debug while (0) yggDebug #else #define ygglog_error while (0) yggError #define ygglog_info while (0) yggInfo #define ygglog_debug while (0) yggDebug #endif #else #define ygglog_error yggError #define ygglog_info while (0) yggInfo #define ygglog_debug while (0) yggDebug #endif /*! @brief Get the length (in bytes) of a character array containing 4 byte unicode characters. @param[in] strarg char* Pointer to character array. @returns size_t Length of strarg in bytes. */ static inline size_t strlen4(char* strarg) { if(!strarg) return 0; //strarg is NULL pointer char* str = strarg; for(;*str;str+=4) ; // empty body return (str - strarg); } /*! @brief Called snprintf and realloc buffer if the formatted string is larger than the provided buffer. @param[in] dst char** Pointer to buffer where formatted message should be stored. @param[in,out] max_len size_t* Pointer to maximum size of buffer that will be modified when the buffer is reallocated. @param[in,out] offset size_t* Pointer to offset in buffer where the formatted message should be stored. This will be updated to the end of the updated message. @param[in] format_str const char* Format string that should be used. @param[in] ... Additional arguments are passed to snprintf as parameters for formatting. @returns int -1 if there is an error, otherwise the number of new characters written to the buffer. */ static inline int snprintf_realloc(char** dst, size_t* max_len, size_t* offset, const char* format_str, ...) { va_list arglist; va_start(arglist, format_str); int fmt_len = 0; while (1) { va_list arglist_copy; va_copy(arglist_copy, arglist); fmt_len = vsnprintf(dst[0] + offset[0], max_len[0] - offset[0], format_str, arglist_copy); if (fmt_len > (int)(max_len[0] - offset[0])) { max_len[0] = max_len[0] + fmt_len + 1; char* temp = (char*)realloc(dst[0], max_len[0]); if (temp == NULL) { ygglog_error("snprintf_realloc: Error reallocating buffer."); fmt_len = -1; break; } dst[0] = temp; } else { offset[0] = offset[0] + fmt_len; break; } } va_end(arglist); return fmt_len; }; /*! @brief Check if a character array matches a message and is non-zero length. @param[in] pattern constant character pointer to string that should be checked. @param[in] buf constant character pointer to string that should be checked. @returns int 1 if buf matches pattern, 0 otherwise. */ static inline int not_empty_match(const char *pattern, const char *buf) { if (buf == NULL) return 0; if (buf[0] == '\0') return 0; if (strcmp(buf, pattern) == 0) { return 1; } else { return 0; } }; /*! @brief Check if a character array matches the internal EOF message. @param[in] buf constant character pointer to string that should be checked. @returns int 1 if buf is the EOF message, 0 otherwise. */ static inline int is_eof(const char *buf) { return not_empty_match(YGG_MSG_EOF, buf); }; /*! @brief Check if a character array matches "recv". @param[in] buf constant character pointer to string that should be checked. @returns int 1 if buf is the "recv" message, 0 otherwise. */ static inline int is_recv(const char *buf) { return not_empty_match("recv", buf); }; /*! @brief Check if a character array matches "send". @param[in] buf constant character pointer to string that should be checked. @returns int 1 if buf is the "send" message, 0 otherwise. */ static inline int is_send(const char *buf) { return not_empty_match("send", buf); }; /*! @brief Initialize a variable argument list from an existing va_list. @returns va_list_t New variable argument list structure. */ static inline va_list_t init_va_list() { va_list_t out; out.using_ptrs = 0; out.ptrs = NULL; out.nptrs = 0; out.iptr = 0; out.for_fortran = 0; return out; }; /*! Initialize a variable argument list from an array of pointers. @param[in] nptrs int Number of pointers. @param[in] ptrs void** Array of pointers. @returns va_list_t New variable argument list structure. */ static inline va_list_t init_va_ptrs(const int nptrs, void** ptrs) { va_list_t out; out.using_ptrs = 1; out.ptrs = ptrs; out.nptrs = nptrs; out.iptr = 0; out.for_fortran = 0; return out; }; /*! Finalize a variable argument list. @param[in] va_list_t Variable argument list. */ static inline void end_va_list(va_list_t *ap) { if (!(ap->using_ptrs)) { va_end(ap->va); } }; /*! Copy a variable argument list. @param[in] va_list_t Variable argument list structure to copy. @returns va_list_t New variable argument list structure. */ static inline va_list_t copy_va_list(va_list_t ap) { va_list_t out; if (ap.using_ptrs) { out = init_va_ptrs(ap.nptrs, ap.ptrs); out.iptr = ap.iptr; } else { out = init_va_list(); va_copy(out.va, ap.va); } out.for_fortran = ap.for_fortran; return out; }; /*! @brief Method for skipping a number of bytes in the argument list. @param[in] ap va_list_t* Structure containing variable argument list. @param[in] nbytes size_t Number of bytes that should be skipped. */ static inline void va_list_t_skip(va_list_t *ap, size_t nbytes) { if (ap->using_ptrs) { ap->iptr++; } else { if (nbytes == sizeof(void*)) { va_arg(ap->va, void*); } else if (nbytes == sizeof(size_t)) { va_arg(ap->va, size_t); } else if (nbytes == sizeof(char*)) { va_arg(ap->va, char*); } else { printf("WARNING: Cannot get argument of size %ld.\n", nbytes); va_arg(ap->va, void*); // va_arg(ap->va, char[nbytes]); } } }; #ifdef __cplusplus /* If this is a C++ compiler, end C linkage */ } #endif #endif /*YGGTOOLS_H_*/
omp_target_disassociate_ptr.c
// omp_target_disassociate_ptr should always fail if the hold reference count is // non-zero, regardless of the dynamic reference count. When the latter is // finite, the implementation happens to choose to report the hold diagnostic. // RUN: %libomptarget-compile-generic -fopenmp-extensions // RUN: %not %libomptarget-run-generic 0 2>&1 | %fcheck-generic // RUN: %not %libomptarget-run-generic 1 2>&1 | %fcheck-generic // RUN: %not %libomptarget-run-generic inf 2>&1 | %fcheck-generic // RUN: %libomptarget-compile-generic -fopenmp-extensions -DHOLD_MORE // RUN: %not %libomptarget-run-generic 0 2>&1 | %fcheck-generic // RUN: %not %libomptarget-run-generic 1 2>&1 | %fcheck-generic // RUN: %not %libomptarget-run-generic inf 2>&1 | %fcheck-generic #include <omp.h> #include <stdio.h> #include <limits.h> #include <string.h> int main(int argc, char *argv[]) { // Parse command line. int DynRef; if (argc != 2) { fprintf(stderr, "bad arguments\n"); return 1; } if (0 == strcmp(argv[1], "inf")) DynRef = INT_MAX; else DynRef = atoi(argv[1]); // Allocate and set dynamic reference count as specified. int DevNum = omp_get_default_device(); int X; void *XDev = omp_target_alloc(sizeof X, DevNum); if (!XDev) { fprintf(stderr, "omp_target_alloc failed\n"); return 1; } if (DynRef == INT_MAX) { if (omp_target_associate_ptr(&X, &XDev, sizeof X, 0, DevNum)) { fprintf(stderr, "omp_target_associate_ptr failed\n"); return 1; } } else { for (int I = 0; I < DynRef; ++I) { #pragma omp target enter data map(alloc: X) } } // Disassociate while hold reference count > 0. int Status = 0; #pragma omp target data map(ompx_hold,alloc: X) #if HOLD_MORE #pragma omp target data map(ompx_hold,alloc: X) #pragma omp target data map(ompx_hold,alloc: X) #endif { // CHECK: Libomptarget error: Trying to disassociate a pointer with a // CHECK-SAME: non-zero hold reference count // CHECK-NEXT: omp_target_disassociate_ptr failed if (omp_target_disassociate_ptr(&X, DevNum)) { fprintf(stderr, "omp_target_disassociate_ptr failed\n"); Status = 1; } } return Status; }
GB_binop__min_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__min_int8) // A.*B function (eWiseMult): GB (_AemultB_08__min_int8) // A.*B function (eWiseMult): GB (_AemultB_02__min_int8) // A.*B function (eWiseMult): GB (_AemultB_04__min_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__min_int8) // A*D function (colscale): GB (_AxD__min_int8) // D*A function (rowscale): GB (_DxB__min_int8) // C+=B function (dense accum): GB (_Cdense_accumB__min_int8) // C+=b function (dense accum): GB (_Cdense_accumb__min_int8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_int8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_int8) // C=scalar+B GB (_bind1st__min_int8) // C=scalar+B' GB (_bind1st_tran__min_int8) // C=A+scalar GB (_bind2nd__min_int8) // C=A'+scalar GB (_bind2nd_tran__min_int8) // C type: int8_t // A type: int8_t // B,b type: int8_t // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ int8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int8_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IMIN (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MIN || GxB_NO_INT8 || GxB_NO_MIN_INT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__min_int8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__min_int8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__min_int8) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__min_int8) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__min_int8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__min_int8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__min_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__min_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__min_int8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__min_int8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *Cx = (int8_t *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__min_int8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int8_t *Cx = (int8_t *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IMIN (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (x, aij) ; \ } GrB_Info GB (_bind1st_tran__min_int8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
World.h
#ifndef __WORLD__H__ #define __WORLD__H__ #include <Eigen/Core> #include <Eigen/SparseCore> #include <Eigen/SparseCholesky> #include <vector> #include <set> #include <Eigen/Dense> #include "Constraint/ConstraintHeader.h" #include "../utils/collisionBrutal.h" #include "../constants.h" namespace FEM { // class Constraint; template <typename TinyScalar, typename TinyConstants> class World { public: World( TinyScalar time_step = 1.0/100.0, int max_iteration = 30, TinyScalar damping_coeff = 0.999, bool is_precessing_collision = false ); ~World(); void Initialize(); void Reset(); void AddBody( const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x0, const std::vector<Constraint<TinyScalar, TinyConstants>*>& c, const std::vector<TinyScalar>& masses, const std::vector<int>& contactIdx, const std::vector<Eigen::Vector3i>& contactFace); void AddBody( const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x0, const std::vector<Constraint<TinyScalar, TinyConstants>*>& c, const std::vector<TinyScalar>& masses, const std::vector<int>& contactIdx, const std::vector<Eigen::Vector3i>& contactFace, const std::vector<std::vector<int>> &rigidBodyIndices, const std::vector<int> &nonrigid, const std::vector<int> &rigid, const std::vector<Link<TinyScalar, TinyConstants>*> &links); void AddBody( const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x0, const std::vector<int>& contactIdx, const std::vector<Eigen::Vector3i>& contactFace); void AddConstraint(Constraint<TinyScalar, TinyConstants>* c); void RemoveConstraint(Constraint<TinyScalar, TinyConstants>* c); void TimeStepping(bool isIntegrated = true); // void TimeSteppingRigid(bool isIntegrated = true); void UpdatePositionsAndVelocities(const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x_n1); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> ProjectiveDynamicsMethod(); void PreComputation(); void EvaluateJMatrix(Eigen::SparseMatrix<TinyScalar>& J); void EvaluateLMatrix(Eigen::SparseMatrix<TinyScalar>& L); void EvaluateAMatrix(); void EvaluateDVector(const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x,Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& d); void FactorizeLDLT(const Eigen::SparseMatrix<TinyScalar>& A,Eigen::SimplicialLDLT<Eigen::SparseMatrix<TinyScalar>>& ldltSolver); void SetExternalForce(Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> external_force); const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& GetExternalForce() {return mExternalForces;}; const TinyScalar& GetTimeStep(){return mTimeStep;}; const TinyScalar& GetTime(){return mTime;}; const std::vector<Constraint<TinyScalar, TinyConstants>*>& GetConstraints(){return mConstraints;}; const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& GetPositions(){return mX;}; const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& GetVelocities(){return mV;}; const int& GetNumVertices(){return mNumVertices;}; void do_solve_friction(Eigen::Matrix<TinyScalar, 3, 1> &p0, TinyScalar m0, Eigen::Matrix<TinyScalar, 3, 1> &r0, std::vector<Eigen::Matrix<TinyScalar, 3, 1>> &ps, std::vector<TinyScalar> &ms, std::vector<Eigen::Matrix<TinyScalar, 3, 1>> &rs, std::vector<bool> &stick, TinyScalar mu); // private: bool mIsInitialized; bool mIsCollision; std::vector<Constraint<TinyScalar, TinyConstants>*> mConstraints; int mConstraintDofs; int mNumVertices; TinyScalar mTimeStep; TinyScalar mTime; int mFrame; int mMaxIteration, mMaxIteration1; TinyScalar mDampingCoefficient; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mX,mV, mNonrigidX,mJointQ, mJointQd; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mInitX,mInitV; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mExternalForces; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mQn; // (qt + hvt + h^2M^-1fext) Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> m_rhs_speed; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mJointTorque; std::vector<TinyScalar> mUnitMass; Eigen::SparseMatrix<TinyScalar> mMassMatrix; Eigen::SparseMatrix<TinyScalar> mInvMassMatrix; Eigen::SparseMatrix<TinyScalar> mIdentityMatrix; Eigen::SparseMatrix<TinyScalar> mJ,mL; Eigen::SparseMatrix<TinyScalar> m_A; Eigen::SparseMatrix<TinyScalar> m_ATA; Eigen::SparseMatrix<TinyScalar> mMh2L; Eigen::SimplicialLDLT<Eigen::SparseMatrix<TinyScalar>> mDynamicSolver,mQuasiStaticSolver,mDynamicSolverM; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mV_without_collision; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mCollision_V_next; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mCollision_X_next; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mPosition_current_next; TinyScalar self_collision_tolerance = 0.01; // TODO TinyScalar m_self_collision_tol2; bool m_handle_self_collision = true; int m_current_index; int m_next_index; /// @brief (IO) std::vector<TinyScalar> m_rhs_base_times; /// @brief (IO) std::vector<TinyScalar> m_friction_times; /// @brief (IO) std::vector<TinyScalar> m_self_friction_times; std::vector<TinyScalar> m_self_collision_ordering_times; using ForceType = Eigen::Matrix<TinyScalar, 3, -1, Eigen::RowMajor>; /// @brief Storage needed to handle self friction ForceType m_contact_forces[2]; /// @brief Storage needed to handle self friction ForceType m_self_contact_forces[2]; /// @brief Storage needed to handle self friction ForceType m_self_contact_repercusion_forces[2]; /// @brief Storage needed to handle self friction Eigen::Matrix<TinyScalar, 3, Eigen::Dynamic> m_alpha[2]; struct SelfCollisionGraphNeighboor { /** * The index of vertex adjacent through this edge. */ std::size_t index; /** * The index of the self-collision represented by this index. */ std::size_t collision_index; }; /** * An adjacency list representing the self-collision graph. The vertices of * this graph are the vertices of the mesh. The edges are the self-collision * between the vertices. * @see SelfCollisionGraphNeighboor * @see computeSelfCollisionGraph */ int mNumContactVertices; std::map<int, int> mMapAll2Contact; std::vector<Eigen::Vector3i> mContactFace, mObsFace; std::vector<int> mContactIdx; CollisionMesh<TinyScalar, TinyConstants>* mCollisionMesh; // Left for children's equations // TODO : make it clean /// @brief Right hand side of the global step equation Eigen::Matrix<TinyScalar, 3, -1, Eigen::RowMajor> m_rhs; std::vector<TinyScalar> m_masses; CollisionBrutal<TinyScalar, TinyConstants>* mCollisionDetector; void computeCollisionComputationOrder() noexcept; std::vector<int> CollisionHandling(); TinyScalar getVertexMass(size_t vertex_index) const; void updateCollisionScene() noexcept; void convertCollisionIndexBack(); void convertCollisionIndex(); void updateCollisionInIter(const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& v, const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x); void ComputeV0NTr(); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> ComputeOriX(const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &x_n1); void ComputeSolution( const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &deltar, const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &ori_c, Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &hvf, Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &s); std::vector<std::vector<int>> mrigidBodies; int mDof, mStoreDof; TinyScalar mAddTorque, mAlpha, mFriction; Eigen::Matrix<TinyScalar, Eigen::Dynamic, Eigen::Dynamic> QbMmQcLQfm1QcLT, QbMmQcLMfm1QcLT; Eigen::SparseMatrix<TinyScalar> mH2ML, Qf, Qc, Qb, Qc_L, Qb_M, mLf, h2Mf, mC; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> mcf, mcs, V0; std::vector<int> mnonrigidIdx, mrigidIdx, mrigidSizes; std::vector<Transformation<TinyScalar, TinyConstants> > T, Tr; std::vector<Link<TinyScalar, TinyConstants>*> mlinks; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> v_n1; std::vector<Eigen::Matrix<TinyScalar, 3, 1> > mCollisionMeshPositions, mObsPositions; ArcsimMesh *mMesh, *mObsMesh; Eigen::PermutationMatrix<Eigen::Dynamic,Eigen::Dynamic> mperm; }; #define EPS 5e-7 template <typename TinyScalar, typename TinyConstants> World<TinyScalar, TinyConstants>:: World( TinyScalar time_step, int max_iteration, TinyScalar damping_coeff, bool is_precessing_collision) :mTimeStep(time_step), mFrame(0), mMaxIteration(max_iteration), mDampingCoefficient(damping_coeff), mNumVertices(0), mNumContactVertices(0), mConstraintDofs(0), mIsCollision(is_precessing_collision), mIsInitialized(false) { mDof = 0; mStoreDof = 0; } template <typename TinyScalar, typename TinyConstants> World<TinyScalar, TinyConstants>:: ~World() { delete mCollisionMesh; delete mCollisionDetector; for(auto c : mConstraints) { delete c; } } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: Initialize() { // mIsCollision = m_handle_self_collision = false; mTime = 0.0; mConstraintDofs = 0; for(auto c : mConstraints) { mConstraintDofs += c->GetDof(); } mV.resize(3*mNumVertices); mV.setZero(); mIdentityMatrix.resize(3*mNumVertices,3*mNumVertices); mMassMatrix.resize(3*mNumVertices,3*mNumVertices); mInvMassMatrix.resize(3*mNumVertices,3*mNumVertices); std::vector<Eigen::Triplet<TinyScalar>> i_triplets; std::vector<Eigen::Triplet<TinyScalar>> m_triplets; std::vector<Eigen::Triplet<TinyScalar>> inv_m_triplets; i_triplets.reserve(3*mNumVertices); m_triplets.reserve(3*mNumVertices); inv_m_triplets.reserve(3*mNumVertices); for(int i=0;i<mNumVertices;i++) { m_triplets.push_back(Eigen::Triplet<TinyScalar>(3*i+0,3*i+0,mUnitMass[i])); m_triplets.push_back(Eigen::Triplet<TinyScalar>(3*i+1,3*i+1,mUnitMass[i])); m_triplets.push_back(Eigen::Triplet<TinyScalar>(3*i+2,3*i+2,mUnitMass[i])); inv_m_triplets.push_back(Eigen::Triplet<TinyScalar>(3*i+0,3*i+0,1.0/mUnitMass[i])); inv_m_triplets.push_back(Eigen::Triplet<TinyScalar>(3*i+1,3*i+1,1.0/mUnitMass[i])); inv_m_triplets.push_back(Eigen::Triplet<TinyScalar>(3*i+2,3*i+2,1.0/mUnitMass[i])); i_triplets.push_back(Eigen::Triplet<TinyScalar>(3*i+0,3*i+0,1.0)); i_triplets.push_back(Eigen::Triplet<TinyScalar>(3*i+1,3*i+1,1.0)); i_triplets.push_back(Eigen::Triplet<TinyScalar>(3*i+2,3*i+2,1.0)); } mMassMatrix.setFromTriplets(m_triplets.cbegin(), m_triplets.cend()); mInvMassMatrix.setFromTriplets(inv_m_triplets.cbegin(), inv_m_triplets.cend()); mIdentityMatrix.setFromTriplets(i_triplets.cbegin(), i_triplets.cend()); mExternalForces.resize(3*mNumVertices); mExternalForces.setZero(); mQn.resize(3*mNumVertices); mQn.setZero(); mInitX = mX; mInitV = mV; // collision if (m_handle_self_collision) { m_current_index = 0; m_next_index = 1; for (int i = 0; i < 2; ++i) { m_contact_forces[i].setZero(3, mNumContactVertices); m_self_contact_forces[i].setZero(3, mNumContactVertices); m_self_contact_repercusion_forces[i].setZero(3, mNumContactVertices); m_alpha[i].setZero(3, mNumContactVertices); } // i } // m_handle_self_collision // std::vector<Eigen::Matrix<TinyScalar, 3, 1>> positions; std::vector<int> triangles; // for (int i = 0; i < mContactIdx.size(); i++) { // int id = mContactIdx[i]; // Eigen::Matrix<TinyScalar, 3, 1> v(mX[3*id], mX[3*id+1], mX[3*id+2]); // positions.push_back(v); // } for (int i = 0; i < mContactFace.size(); i++) { triangles.push_back(mContactFace[i][0]); triangles.push_back(mContactFace[i][1]); triangles.push_back(mContactFace[i][2]); } // mCollisionMesh = new CollisionMesh<TinyScalar, TinyConstants>(positions, triangles); // mCollisionDetector = new CollisionBrutal<TinyScalar, TinyConstants>(mCollisionMesh, true); mCollisionMesh = new CollisionMesh<TinyScalar, TinyConstants>(mCollisionMeshPositions, triangles); mObsMesh = new ArcsimMesh(); mObsMesh->Initialize( helper::to_eigen_double<TinyScalar, TinyConstants>(mObsPositions), helper::to_eigen_double<TinyScalar, TinyConstants>(mObsPositions), mObsFace); mMesh = new ArcsimMesh(); mMesh->Initialize( helper::to_eigen_double<TinyScalar, TinyConstants>(mCollisionMeshPositions), helper::to_eigen_double<TinyScalar, TinyConstants>(mCollisionMeshPositions), mContactFace); mCollisionDetector = new CollisionBrutal<TinyScalar, TinyConstants>(mCollisionMesh, true); mCollisionDetector->mObsMesh = mObsMesh; mCollisionDetector->mMesh = mMesh; mCollisionDetector->m_generalized_positions.resize(mNumContactVertices*3); mCollisionDetector->m_generalized_speeds.resize(mNumContactVertices*3); mCollisionDetector->mCollisionMesh->m_positions.resize(mNumContactVertices*3); mCollisionDetector->mCollisionMesh->m_speed.resize(mNumContactVertices*3); m_rhs = Eigen::Matrix<TinyScalar, Eigen::Dynamic, Eigen::Dynamic>::Zero( 3, mContactIdx.size()); mCollisionDetector->m_handle_self_collision = m_handle_self_collision; mCollision_V_next.resize(mNumContactVertices*3); mCollision_X_next.resize(mNumContactVertices*3); std::cout<<"m_rhs rows: "<<m_rhs.rows()<<std::endl; std::cout<<"m_rhs cols: "<<m_rhs.cols()<<std::endl; // collision // rigid bodies T.resize(mrigidBodies.size()); Tr.resize(mrigidBodies.size()); mJointQ.resize(mStoreDof); mJointQd.resize(mStoreDof); for (int i = 0; i < mrigidBodies.size(); ++i) mlinks[i]->WriteT(mJointQ, mJointQd); mJointTorque.resize(std::max(0, int(mrigidBodies.size()-1) )); mJointTorque.setZero(); // rigid bodies // PreComputation(); PreComputation(); mIsInitialized = true; std::cout<<"Total degree of freedom : "<<mX.rows()<<std::endl; std::cout<<"Total constraints : "<<mConstraints.size()<<std::endl; } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: Reset() { mX = mInitX; mV = mInitV; mTime = 0.0; } template <typename TinyScalar, typename TinyConstants> TinyScalar World<TinyScalar, TinyConstants>:: getVertexMass(size_t vertex_index) const { return mH2ML.coeff(mContactIdx[vertex_index]*3,mContactIdx[vertex_index]*3); // return mUnitMass[mContactIdx[vertex_index]]; // return 1.0; // return mCollisionDetector->mCollisionMesh->m_masses[vertex_index]; } // add cloth body template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: AddBody( const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x0, const std::vector<Constraint<TinyScalar, TinyConstants>*>& c, const std::vector<TinyScalar>& masses, const std::vector<int>& contactIdx, const std::vector<Eigen::Vector3i>& contactFace) { std::cout << contactFace.size() << " addbody contactFace\n"; std::cout << contactIdx.size() << " addbody contactIdx\n"; for (const auto& cidx : contactIdx) { int id = cidx + mNumVertices; if (std::find(mContactIdx.begin(), mContactIdx.end(), id) == mContactIdx.end() ) { mContactIdx.push_back(id); mMapAll2Contact.insert(std::make_pair(id, mNumContactVertices++)); mCollisionMeshPositions.push_back(x0.template segment<3>(cidx*3)); } } for (const auto& f : contactFace) { int f0, f1, f2; f0 = mMapAll2Contact[f[0]+mNumVertices]; f1 = mMapAll2Contact[f[1]+mNumVertices]; f2 = mMapAll2Contact[f[2]+mNumVertices]; mContactFace.push_back(Eigen::Vector3i(f0, f1, f2)); } int nv=(x0.rows()/3); for (int i = 0; i < nv*3; ++i) mnonrigidIdx.push_back(mNumVertices*3 + i); mNumVertices+=nv; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> tmpX = mX; // tmpX.resize(mNumVertices*3); mX.resize(mNumVertices*3); mX.head(tmpX.rows()) = tmpX; mX.tail(x0.rows()) = x0; for (auto con : c) { con->fixIndex(mNumVertices - nv); } mConstraints.insert(mConstraints.end(),c.begin(),c.end()); for(int i=0;i<nv;i++){ mUnitMass.push_back(masses[i]); } if(mIsInitialized) Initialize(); } //add obstacle body template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: AddBody( const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x0, const std::vector<int>& contactIdx, const std::vector<Eigen::Vector3i>& contactFace) { int offset = mObsPositions.size(); for (const auto& cidx : contactIdx) { // mContactIdx.push_back(-1); // mCollisionMeshPositions.push_back(x0.segment<3>(cidx*3)); mObsPositions.push_back(x0.template segment<3>(cidx*3)); } // mNumContactVertices += contactIdx.size(); for (const auto& f : contactFace) { int f0, f1, f2; f0 = f[0]+offset; f1 = f[1]+offset; f2 = f[2]+offset; mObsFace.push_back(Eigen::Vector3i(f0, f1, f2)); } if(mIsInitialized) Initialize(); } //add rtq8 soft body template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: AddBody( const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x0, const std::vector<Constraint<TinyScalar, TinyConstants>*>& c, const std::vector<TinyScalar>& masses, const std::vector<int>& contactIdx, const std::vector<Eigen::Vector3i>& contactFace, const std::vector<std::vector<int>> &rigidBodyIndices, const std::vector<int> &nonrigid, const std::vector<int> &rigid, const std::vector<Link<TinyScalar, TinyConstants>*> &links) { printf("AddBody rigid bodies\n"); int offset = mNumVertices, rigidoffset = mrigidIdx.size()/3; for (int i = 0; i < rigidBodyIndices.size(); ++i) { auto tmp = rigidBodyIndices[i]; for (int i = 0; i < tmp.size(); ++i) tmp[i] += offset; Link<TinyScalar, TinyConstants> *link = links[i]; link->bodyIdx = mrigidBodies.size(); mlinks.push_back(link); link->rigidoffset = rigidoffset; rigidoffset += tmp.size(); link->dofIdx = mDof; link->storedofIdx = mStoreDof; if (link->parent == NULL) { mDof += 6; mStoreDof += 12; } else { mDof += 1; mStoreDof += 1; } mrigidBodies.push_back(tmp); mrigidSizes.push_back(tmp.size()); link->indices = tmp; } for (int idx : nonrigid) mnonrigidIdx.push_back(offset * 3 + idx); for (int idx : rigid) mrigidIdx.push_back(offset * 3 + idx); int k = 0; for (auto &idxs : mrigidBodies) { for (int i = 0; i < idxs.size(); ++i) { if (mrigidIdx[k] != idxs[i]*3 || mrigidIdx[k+1] != idxs[i]*3+1 || mrigidIdx[k+2] != idxs[i]*3+2) std::cout << "???" << mrigidIdx[k] << " " << idxs[i]<< std::endl; k += 3; } } // collision std::cout << contactFace.size() << " addbody contactFace\n"; std::cout << contactIdx.size() << " addbody contactIdx\n"; for (const auto& cidx : contactIdx) { int id = cidx + mNumVertices; if (std::find(mContactIdx.begin(), mContactIdx.end(), id) == mContactIdx.end() ) { mContactIdx.push_back(id); mMapAll2Contact.insert(std::make_pair(id, mNumContactVertices++)); mCollisionMeshPositions.push_back(x0.template segment<3>(cidx*3)); } } for (const auto& f : contactFace) { int f0, f1, f2; f0 = mMapAll2Contact[f[0]+mNumVertices]; f1 = mMapAll2Contact[f[1]+mNumVertices]; f2 = mMapAll2Contact[f[2]+mNumVertices]; mContactFace.push_back(Eigen::Vector3i(f0, f1, f2)); } // collision end int nv=(x0.rows()/3); mNumVertices+=nv; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> tmpX = mX; // tmpX.resize(mNumVertices*3); mX.resize(mNumVertices*3); mX.head(tmpX.rows()) = tmpX; mX.tail(x0.rows()) = x0; for (auto con : c) { con->fixIndex(mNumVertices - nv); } mConstraints.insert(mConstraints.end(),c.begin(),c.end()); for(int i=0;i<nv;i++){ mUnitMass.push_back(masses[i]); } if(mIsInitialized) Initialize(); } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: AddConstraint(Constraint<TinyScalar, TinyConstants>* c) { mConstraints.push_back(c); if(mIsInitialized){ mConstraintDofs = 0; for(auto c : mConstraints){ mConstraintDofs += c->GetDof(); } PreComputation(); // PreComputation(); } } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: RemoveConstraint(Constraint<TinyScalar, TinyConstants>* c) { bool isRemoved = false; for(int i=0;i<mConstraints.size();i++) { if(mConstraints[i]==c) { mConstraints.erase(mConstraints.begin()+i); isRemoved = true; break; } } if(isRemoved) { if(mIsInitialized) { mConstraintDofs = 0; for(auto c : mConstraints){ mConstraintDofs += c->GetDof(); } PreComputation(); } } } // template <typename TinyScalar, typename TinyConstants> // void World<TinyScalar, TinyConstants>:: // TimeStepping(bool isIntegrated) // { // if(!mIsInitialized) { // std::cout<<"Engine not initialized."<<std::endl; // return; // } // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> x_n1(mNumVertices*3); // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> v_n1(mNumVertices*3); // mV_without_collision = mV + mTimeStep*(mInvMassMatrix*mExternalForces); // // (qt + hvt + h^2M^-1fext) // mQn = mX + mTimeStep*mV_without_collision; // mPosition_current_next = mQn; // auto tmp = mTimeStep*(mInvMassMatrix*mExternalForces); // x_n1=ProjectiveDynamicsMethod(); // // v_n1=ProjectiveDynamicsMethod(); // // UpdatePositionsAndVelocities(v_n1); // UpdatePositionsAndVelocities(x_n1); // // mV *= mDampingCoefficient; // updateCollisionScene(); // if(isIntegrated) // { // mTime += mTimeStep; // mFrame++; // } // } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: TimeStepping(bool isIntegrated) { if(!mIsInitialized) { std::cout<<"Engine not initialized."<<std::endl; return; } for (int i = 0; i < mrigidBodies.size(); ++i) mlinks[i]->ReadT(mJointQ, mJointQd); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> x_n1(mNumVertices*3); // (qt + hvt + h^2M^-1fext) // mExternalForces[0] = 1; // std::cout << mInvMassMatrix << " mInvMassMatrix\n"; // std::cout << mV[1] << " mV\n"; // std::cout << mExternalForces[1] << " mExternalForces\n"; mV_without_collision = mV + mTimeStep*(mInvMassMatrix*mExternalForces); // std::cout << mV[1] << " mV\n"; // std::cout << mExternalForces[1] << " mExternalForces\n"; // std::cout << mV_without_collision[1] << " mV_without_collision\n"; // (qt + hvt + h^2M^-1fext) mQn = mX + mTimeStep*mV_without_collision; updateCollisionScene(); // std::cout << mQn[1] << " mQn\n"; x_n1 = ProjectiveDynamicsMethod(); // std::cout << x_n1[1] << " x_n1\n"; // std::cout << mX[1] << " mX\n"; UpdatePositionsAndVelocities(x_n1); mV *= mDampingCoefficient; // std::cout << mV[1] << " mV 2\n"; updateCollisionScene(); for (int i = 0; i < mrigidBodies.size(); ++i) mlinks[i]->WriteT(mJointQ, mJointQd); if(isIntegrated) { mTime += mTimeStep; mFrame++; } } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: updateCollisionScene() noexcept { for (int i = 0; i < mContactIdx.size(); i++) { int id = mContactIdx[i]; for (int j = 0; j < 3; j++) { mCollisionDetector->m_generalized_positions[3*i+j] = mX[3*id+j]; mCollisionDetector->m_generalized_speeds[3*i+j] = mV[3*id+j]; mCollisionDetector->mCollisionMesh->m_positions[3*i+j] = mX[3*id+j]; mCollisionDetector->mCollisionMesh->m_speed[3*i+j] = mV[3*id+j]; } mCollisionDetector->mMesh->nodes[i]->x0 = Vec3( TinyConstants::getDouble(mX[3*id+0]) , TinyConstants::getDouble(mX[3*id+1]) , TinyConstants::getDouble(mX[3*id+2])); } // Cleaning the forces for the next step if (m_handle_self_collision) { m_current_index = 0u; m_next_index = 1u; for (unsigned int i = 0u; i < 2u; ++i) { m_contact_forces[i].setZero(); m_self_contact_forces[i].setZero(); m_self_contact_repercusion_forces[i].setZero(); m_alpha[i].setZero(); } } } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: UpdatePositionsAndVelocities(const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x_n1) { // mV = x_n1; // mX = mX + mV * mTimeStep; mV = (x_n1 - mX) * (1.0 / mTimeStep); mX = x_n1; } // template <typename TinyScalar, typename TinyConstants> // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> World<TinyScalar, TinyConstants>:: // ProjectiveDynamicsMethod() // { // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> x_n1(3*mNumVertices); // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> x_n1_new(3*mNumVertices); // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> x_n1_new_v(3*mNumVertices); // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> b(3*mNumVertices); // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> d(3*mConstraintDofs); // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> rhs_speed(3*mNumVertices); // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> v_n1(3*mNumVertices); // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> v_n1_new(3*mNumVertices); // d.setZero(); // b= (1.0/(mTimeStep*mTimeStep))*mMassMatrix*mQn; // TinyScalar h2 = mTimeStep*mTimeStep; // x_n1 = mQn; // v_n1 = mV_without_collision; // if(mIsCollision) { // mCollisionDetector->BaseUpdateCollisions(mCollision_X_next); // updateCollisionInIter(v_n1, x_n1); // } // int i; // TinyScalar err = 100.; // for(i=0; i<mMaxIteration; i++) { // EvaluateDVector(x_n1,d); // m_rhs_speed = mMassMatrix * mV_without_collision + // mTimeStep * (mJ * d - mL * mX); // if(mIsCollision) { // convertCollisionIndex(); // CollisionHandling(); // convertCollisionIndexBack(); // } // v_n1_new = mDynamicSolver.solve(m_rhs_speed/h2); // x_n1_new = mX + v_n1_new*mTimeStep; // if(mIsCollision) { // updateCollisionInIter(v_n1_new, x_n1_new); // } // err = (x_n1_new - x_n1).norm()/x_n1.size(); // if(err < EPS) { // break; // } // x_n1 = x_n1_new; // } // // if(mIsCollision) { // // updateCollisionInIter(v_n1_new, x_n1_new); // // } // std::cout << "error " << err << " "; // if(err < EPS) // std::cout << "good!\n"; // else // std::cout << "not converge!\n"; // return x_n1; // } template <typename TinyScalar, typename TinyConstants> Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> World<TinyScalar, TinyConstants>:: ProjectiveDynamicsMethod() { static int num_max = 0, num_iter = 0; static double total_time = 0; int numUnknown = mnonrigidIdx.size() + mDof; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> x_n1(numUnknown); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> ori_x(3*mNumVertices); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> ori_x_old(3*mNumVertices); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> x_n1_new(numUnknown); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> b(3*mNumVertices); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> d(3*mConstraintDofs); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> ori_c, s, xf, xf_old(mnonrigidIdx.size()); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> hvf(mnonrigidIdx.size()); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> deltar(mnonrigidIdx.size()); deltar.setZero(); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> rhs_speed(3*mNumVertices); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> v_n1(3*mNumVertices); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> v_n1_new(3*mNumVertices); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> prev_mrhsspeed(3*mNumVertices); mNonrigidX.resize(mnonrigidIdx.size()); d.setZero(); prev_mrhsspeed.setZero(); b = (1.0 / (mTimeStep * mTimeStep)) * mMassMatrix * mQn; // std::cout << mTimeStep << " mTimeStep\n"; // std::cout << mQn[1] << " mQn\n"; // std::cout << b[1] << " b\n"; TinyScalar h2 = mTimeStep*mTimeStep; v_n1 = mV_without_collision; x_n1 = (mperm * mQn).template segment(0, mnonrigidIdx.size()); xf_old = x_n1; mNonrigidX = (mperm * mX).template segment(0,mnonrigidIdx.size()); if(mIsCollision) { // mCollisionDetector->BaseUpdateCollisions(mCollision_X_next); updateCollisionInIter(mV_without_collision, mQn); } // std::cout << "\tmv0 "<<((mTimeStep*mV_without_collision).template segment<3>(353*3)).transpose() << std::endl; ori_x_old.fill(0.); for (int i = 0; i < mrigidBodies.size(); ++i) mlinks[i]->guessNext(); TinyScalar err; for(int i = 0; i < mMaxIteration; i++) { ComputeV0NTr(); ori_x = ComputeOriX(x_n1); // std::cout << "ori_x "<< i << " " << ori_x[1] << std::endl; TinyScalar err = (ori_x - ori_x_old).norm()/ori_x.size(); if (err < EPS) { // std::cout << "iter i0=" << i << std::endl; break; } ori_x_old = ori_x; EvaluateDVector(ori_x,d); ori_c = b + mJ * d; // std::cout << "b "<< i << " " << b[1] << std::endl; // std::cout << "d "<< i << " " << d[1] << std::endl; // std::cout << "hvf0 "<< i << " " << hvf[1] << std::endl; // std::cout << "deltar "<< i << " " << deltar[1] << std::endl; // std::cout << "ori_c "<< i << " " << ori_c[1] << std::endl; ComputeSolution(deltar, ori_c, hvf, s); // std::cout << "\thvf0 "<<(hvf.template segment<3>(353*3)).transpose() << std::endl; xf = mNonrigidX + hvf; // std::cout << "mNonrigidX "<< i << " " << mNonrigidX[1] << std::endl; // std::cout << "hvf "<< i << " " << hvf[1] << std::endl; x_n1_new << xf, s; x_n1 = x_n1_new; } ComputeV0NTr(); // std::cout << x_n1_new[1] << " x_n1_new\n"; ori_x = ComputeOriX(x_n1_new); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> old_hvf = hvf; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> old_oric = ori_c; // std::cout << mIsCollision << " mIsCollision\n"; if (mIsCollision) { mCollisionDetector->ClearCollisions(); ori_x_old.setZero(); while (true) { // printf("mIsCollision\n"); auto tmpv = (ori_x - mX) / mTimeStep; updateCollisionInIter(tmpv, ori_x); for (int i = 0; i < mContactIdx.size(); i++) { mCollisionDetector->mMesh->nodes[i]->x = Vec3( TinyConstants::getDouble( mCollision_X_next[3*i+0]), TinyConstants::getDouble( mCollision_X_next[3*i+1]), TinyConstants::getDouble( mCollision_X_next[3*i+2])); } if (mCollisionDetector->BaseUpdateCollisions(mCollision_X_next)) break; // std::cout << "collision start!" << std::endl; ++num_max; num_iter += 100; bool flag = true; for (int i = 0; i < mMaxIteration1; ++i) { ComputeV0NTr(); ori_x = ComputeOriX(x_n1); err = (ori_x - ori_x_old).cwiseAbs().maxCoeff();//.norm()/ori_x.size();// // std::cout << "err1 " << err << std::endl; // std::cout << "\tori_x "<<(ori_x.template segment<3>(mContactIdx[86]*3)).transpose() << std::endl; if (err < EPS && flag) { --num_max; num_iter += i - 100; // std::cout << "iter i1=" << i << std::endl; break; } EvaluateDVector(ori_x,d); auto tmpv = (ori_x - mX) / mTimeStep; updateCollisionInIter(tmpv, ori_x); // std::cout << (tmpv.template segment<3>(mContactIdx[38]*3)).transpose() << std::endl; // std::cout << ori_x.segment<3>(mContactIdx[689]*3).transpose() << std::endl; // m_rhs_speed = mMassMatrix * mV_without_collision; m_rhs_speed = mMassMatrix * mV_without_collision + mTimeStep * (mJ * d - mL * mX); auto tmp = mTimeStep * mC * tmpv * mTimeStep; // std::cout <<"m_rhs_speed bef "<< (m_rhs_speed.template segment<3>(mContactIdx[656]*3)).transpose() << std::endl; m_rhs_speed -= tmp; // std::cout <<"m_rhs_speed aft "<< (m_rhs_speed.template segment<3>(mContactIdx[656]*3)).transpose() << std::endl; // std::cout <<"ori_x "<< (ori_x.template segment<3>(mContactIdx[656]*3)).transpose() << std::endl; if (i == 0) prev_mrhsspeed = m_rhs_speed; // m_rhs_speed = mperm * m_rhs_speed; // m_rhs_speed.segment(0, mnonrigidIdx.size()) -= tmp; // m_rhs_speed = mperm.transpose() * m_rhs_speed; // for (int i = 0; i < mnonrigidIdx.size(); i++) { // m_rhs_speed[mnonrigidIdx[i]] -= tmp[i]; // } convertCollisionIndex(); std::vector<int> cindices = CollisionHandling(); flag = true; // for (int i : cindices) { // auto tmp = (ori_x - ori_x_old).template segment<3>(mContactIdx[i]*3); // // std::cout << i << " " << mContactIdx[i]*3 << " "<< tmp.transpose() << std::endl; // if (tmp.norm() > 1e-5) // flag = false; // } // std::cout << flag << std::endl; // m_rhs_speed.setZero(); convertCollisionIndexBack(); //mrhsspeed is delta // auto diff = m_rhs_speed - prev_mrhsspeed; // std::cout << diff.norm() << std::endl; // std::cout << diff.segment<3>(mContactIdx[406]*3).transpose() << std::endl; // int idx = 0; // for (int i = 0; i < mNumVertices*3; ++i) // if (std::abs(diff[i])>std::abs(diff[idx])) // idx = i; // std::cout << "argmax= "<<idx<<" : "<<diff[idx]<<" "<< m_rhs_speed[idx]<<" "<<prev_mrhsspeed[idx]<< std::endl; TinyScalar alpha = mAlpha; prev_mrhsspeed = (m_rhs_speed * alpha + prev_mrhsspeed * (1 - alpha)); ori_c = b + mJ * d + prev_mrhsspeed / mTimeStep; // std::cout << prev_mrhsspeed.norm() << std::endl; // std::cout << (old_oric - ori_c).norm() << std::endl; // std::cout <<"m_rhs_speed "<< (m_rhs_speed.template segment<3>(mContactIdx[656]*3)).transpose() << std::endl; // ComputeSolution_collision(ori_c, hvf, hvf, s); // deltar = mTimeStep * mLf * (hvf - old_hvf); // old_hvf = hvf; // ComputeSolution(deltar, ori_c, hvf, s); hvf = mDynamicSolverM.solve((mperm * prev_mrhsspeed / mTimeStep).segment(0, mnonrigidIdx.size())); // std::cout <<"hvf "<< (hvf.template segment<3>(mContactIdx[449]*3)).transpose() << std::endl; // std::cout <<"hvf "<< (hvf.template segment<3>(mContactIdx[515]*3)).transpose() << std::endl; // std::cout <<"hvf "<< (hvf.template segment<3>(mContactIdx[517]*3)).transpose() << std::endl; // std::cout <<"hvf "<< (hvf.template segment<3>(mContactIdx[656]*3)).transpose() << std::endl; // std::cout <<"mass "<< mH2ML.coeff(mContactIdx[656]*3,mContactIdx[656]*3) << std::endl; xf = mNonrigidX + hvf; x_n1_new << xf, s; x_n1 = x_n1_new; ori_x_old = ori_x; } } } // ComputeV0NTr(); // ori_x = ComputeOriX(x_n1_new); return ori_x; } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: convertCollisionIndex() { for (int i = 0; i < mContactIdx.size(); i++) { int id = mContactIdx[i]; m_rhs.template block<3,1>(0,i) = m_rhs_speed.template block<3,1>(id*3,0); } } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: updateCollisionInIter(const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& v, const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x) { for (int i = 0; i < mContactIdx.size(); i++) { int id = mContactIdx[i]; mCollision_V_next.template block<3,1>(i*3,0) = v.template block<3,1>(id*3,0); mCollision_X_next.template block<3,1>(i*3,0) = x.template block<3,1>(id*3,0); } } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: convertCollisionIndexBack() { for (int i = 0; i < mContactIdx.size(); i++) { int id = mContactIdx[i]; m_rhs_speed.template block<3,1>(id*3,0) = m_rhs.template block<3,1>(0,i); } } // template <typename TinyScalar, typename TinyConstants> // void World<TinyScalar, TinyConstants>:: // PreComputation() // { // EvaluateJMatrix(mJ); // EvaluateLMatrix(mL); // EvaluateAMatrix(); // Eigen::SparseMatrix<TinyScalar> H2ML = (1.0/(mTimeStep*mTimeStep))*mMassMatrix+mL; // printf("\n############### mL\n"); // for (int i = 0; i < 10; i++) { // for debug testing // printf("(%f) ", mL.coeff(3*i, 3*i)); // } // printf("\n############### mMassMatrix\n"); // for (int i = 0; i < 10; i++) { // for debug testing // printf("(%f) ", mMassMatrix.coeff(3*i, 3*i)); // } // printf("\n############### H2ML\n"); // Eigen::SparseMatrix<TinyScalar> h2 = H2ML*(mTimeStep*mTimeStep); // for (int i = 0; i < 10; i++) { // for debug testing // printf("(%f) ", h2.coeff(3*i, 3*i)); // } // mMh2L = h2; // FactorizeLDLT(H2ML,mDynamicSolver); // FactorizeLDLT(mL,mQuasiStaticSolver); // } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: PreComputation() { EvaluateJMatrix(mJ); EvaluateLMatrix(mL); EvaluateAMatrix(); // mH2ML = (1.0/(mTimeStep*mTimeStep))*mMassMatrix+mL; h2Mf = (1.0/(mTimeStep*mTimeStep))*mMassMatrix; mH2ML = h2Mf + mL; //split Eigen::PermutationMatrix<Eigen::Dynamic,Eigen::Dynamic> perm(3*mNumVertices); Eigen::SparseMatrix<TinyScalar> tmp = mH2ML; auto lmd0 = [](const Eigen::Index& row, const Eigen::Index& col, const auto&){return row==col;}; auto lmd1 = [](const Eigen::Index& row, const Eigen::Index& col, const auto&){return row!=col;}; const int nnon = mnonrigidIdx.size(), nrig = mrigidIdx.size(); Eigen::VectorXi tmpp(3*mNumVertices); for (int i = 0; i < nnon; ++i) tmpp[i] = mnonrigidIdx[i]; for (int i = 0; i < nrig; ++i) tmpp[i + nnon] = mrigidIdx[i]; //column-major p for (int i = 0; i < 3*mNumVertices; ++i) perm.indices()[tmpp[i]] = i; tmp = mH2ML.twistedBy(perm); Qf = tmp.block(0,0,nnon, nnon); Qc_L = tmp.block(nnon, 0,nrig, nnon); Qb_M = tmp.block(nnon, nnon,nrig, nrig); tmp = mH2ML; tmp.prune(lmd1); mC = tmp*1; mMh2L = mH2ML*(mTimeStep*mTimeStep); FactorizeLDLT(Qf,mDynamicSolver); tmp = mH2ML; tmp.prune(lmd0); FactorizeLDLT(tmp,mDynamicSolverM); QbMmQcLQfm1QcLT = Qb_M - Qc_L * mDynamicSolver.solve( Eigen::Matrix<TinyScalar, Eigen::Dynamic, Eigen::Dynamic>(Qc_L.transpose())); // FactorizeLDLT(H2ML,mDynamicSolver); // FactorizeLDLT(mL,mQuasiStaticSolver); mperm = perm; } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: EvaluateJMatrix(Eigen::SparseMatrix<TinyScalar>& J) { J.resize(3*mNumVertices,3*mConstraintDofs); std::vector<Eigen::Triplet<TinyScalar>> J_triplets; int index = 0; for(int i =0;i<mConstraints.size();i++) { mConstraints[i]->EvaluateJMatrix(index,J_triplets); index+=mConstraints[i]->GetDof(); } J.setFromTriplets(J_triplets.cbegin(), J_triplets.cend()); } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: EvaluateAMatrix() { Eigen::SparseMatrix<TinyScalar> tmpB = mL; m_ATA.resize(mNumContactVertices, mNumContactVertices); // m_A.resize(mConstraintDofs, mNumContactVertices); for (int i = 0; i < mNumContactVertices; i++) { for (int j = 0; j < mNumContactVertices; j++) { int id = mContactIdx[i]; int jd = mContactIdx[j]; if (id == jd) continue; // if (id == -1 || jd == -1) continue; if (tmpB.coeff(3*id, 3*jd) == 0) continue; m_ATA.coeffRef(i,j) = tmpB.coeff(3*id, 3*jd); } } } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: EvaluateLMatrix(Eigen::SparseMatrix<TinyScalar>& L) { L.resize(3*mNumVertices,3*mNumVertices); std::vector<Eigen::Triplet<TinyScalar>> L_triplets; for(auto c : mConstraints) c->EvaluateLMatrix(L_triplets); L.setFromTriplets(L_triplets.cbegin(), L_triplets.cend()); } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: EvaluateDVector(const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& x,Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1>& d) { d.resize(mConstraintDofs*3); int n = mConstraints.size(); // #pragma omp parallel for for(int i=0;i<n;i++) { mConstraints[i]->EvaluateDVector(x); } int index = 0; for(auto& c : mConstraints) { c->GetDVector(index,d); } } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: FactorizeLDLT(const Eigen::SparseMatrix<TinyScalar>& A,Eigen::SimplicialLDLT<Eigen::SparseMatrix<TinyScalar>>& ldltSolver) { Eigen::SparseMatrix<TinyScalar> A_prime = A; ldltSolver.analyzePattern(A_prime); ldltSolver.factorize(A_prime); TinyScalar reg = 1E-6; bool success = true; while (ldltSolver.info() != Eigen::Success) { reg *= 10; A_prime = A + reg*mIdentityMatrix; ldltSolver.factorize(A_prime); success = false; } if (!success) std::cout << "factorize failure (damping : " << reg<<" )"<<std::endl; // else // std::cout << "factorize success\n"; } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: SetExternalForce(Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> external_force) { mExternalForces = external_force; } // collision ---------------------------------------------------------------------------------------------------------- #define BLOCK(m, id) ((m).col((id))) #define LVAL(m, id, cmp) ((m)((cmp), (id))) template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: do_solve_friction( Eigen::Matrix<TinyScalar, 3, 1> &p0, TinyScalar m0, Eigen::Matrix<TinyScalar, 3, 1> &r0, std::vector<Eigen::Matrix<TinyScalar, 3, 1>> &ps, std::vector<TinyScalar> &ms, std::vector<Eigen::Matrix<TinyScalar, 3, 1>> &rs, std::vector<bool> &stick, TinyScalar mu) { //compute stick p and m Eigen::Matrix<TinyScalar, 3, 1> pstick = p0; TinyScalar mstick = m0; int n = stick.size(); for (int k = 0; k < n; ++k) if (stick[k]) { pstick += ps[k]; mstick += ms[k]; } //compute slide p and m and fn Eigen::Matrix<TinyScalar, 3, 1> pslide(0.,0.,0.); TinyScalar mslide = 0, fn = 0; for (int k = 0; k < n; ++k) if (!stick[k]) { pslide += ps[k]; mslide += ms[k]; fn += rs[k][0]; } //compute stick force: Eigen::Matrix<TinyScalar, 3, 1> v = pstick / mstick; r0[1] = v[1] * m0 - p0[1]; r0[2] = v[2] * m0 - p0[2]; for (int k = 0; k < n; ++k) if (stick[k]) { rs[k][1] = v[1] * ms[k] - ps[k][1]; rs[k][2] = v[2] * ms[k] - ps[k][2]; } if (mslide > 0) { //compute relative v direction, and normalize Eigen::Matrix<TinyScalar, 3, 1> rel_v = pslide / mslide - pstick / mstick; TinyScalar t_len = sqrt(rel_v[1]*rel_v[1] + rel_v[2]*rel_v[2]); rel_v /= t_len; //apply sliding frictional force to stuck verts TinyScalar mult = mu*fn/(mslide+mstick); r0[1] += rel_v[1] * mult * m0; r0[2] += rel_v[2] * mult * m0; for (int k = 0; k < n; ++k) if (stick[k]) { rs[k][1] += rel_v[1] * mult * ms[k]; rs[k][2] += rel_v[2] * mult * ms[k]; } //apply sliding frictional force to slide verts Eigen::Matrix<TinyScalar, 3, 1> abs_v0 = (p0 + r0) / m0; for (int k = 0; k < n; ++k) if (!stick[k]) { Eigen::Matrix<TinyScalar, 3, 1> rel_v = ps[k] / ms[k] - abs_v0; TinyScalar t_len = sqrt(rel_v[1]*rel_v[1] + rel_v[2]*rel_v[2]); rel_v /= t_len; TinyScalar mult = -mu*rs[k][0] * ms[k] / (ms[k] + mstick); rs[k][1] = mult*rel_v[1]; rs[k][2] = mult*rel_v[2]; } } //sanity check: sum of frictional forces should be one Eigen::Matrix<TinyScalar, 3, 1> rsum = r0; for (int k = 0; k < n; ++k) rsum += rs[k]; assert(rsum.norm() < 1e-8); } template <typename TinyScalar, typename TinyConstants> std::vector<int> World<TinyScalar, TinyConstants>:: CollisionHandling() { const unsigned int nbCollisions = mCollisionDetector->m_collisions_infos.size(); const unsigned int nbSelfCollisions = mCollisionDetector->m_self_collisions_infos.size(); // Abort if there is no collisions // std::cout << nbSelfCollisions << " nbSelfCollisions \n"; // std::cout << nbCollisions << " nbCollisions \n"; if ((nbCollisions == 0) && (!m_handle_self_collision || (nbSelfCollisions == 0))) { // m_rhs.setZero(); return {}; } std::vector<int> ans; TIMER_START(friction); // Reconstruct the forces without any friction force Eigen::Matrix<TinyScalar, 3, Eigen::Dynamic> forces = m_rhs; // m_rhs.setZero(); // const auto v = Eigen::Matrix<TinyScalar, Eigen::Dynamic, Eigen::Dynamic>::Map(mCollision_V_next.data(), 3, mNumContactVertices); // std::cout << mNumContactVertices << " mNumContactVertices\n"; // std::cout << mCollision_V_next.rows() << "!" << mCollision_V_next.cols() << "\n"; // std::cout << v.rows() << " 1 " << v.cols() << "\n"; // std::cout << m_ATA.rows() << " 2 " << m_ATA.cols() << "\n"; // std::cout << forces.rows() << " 3 " << forces.cols() << "\n"; // std::cout << v.block<3,1>(0,0) << " v\n"; // std::cout << mCollision_V_next.block<3,1>(0,0) << " v\n"; // exit(0); // #pragma omp parallel for // for (size_t cmp = 0u; cmp < 3u; ++cmp) // { // forces.row(cmp) -= // // std::pow(m_time_step, 2) * (getATA() * v.row(cmp).transpose()).transpose(); // //// ! better perf ! // std::pow(mTimeStep, 2) * v.row(cmp) * m_ATA; // } // Estimated friction force // #pragma omp parallel for for (unsigned int cId = 0u; cId < nbCollisions; ++cId) { // Data const CollisionInfo<TinyScalar, TinyConstants> & collision_info = mCollisionDetector->m_collisions_infos[cId]; const size_t vId = collision_info.vertex_index; const Eigen::Matrix<TinyScalar, 3, 3>& local_basis = mCollisionDetector->m_local_contact_basis[cId]; const TinyScalar mu = collision_info.friction_coefficient; // Converting the rhs in the local basis // Contact force also sees the previous self collision forces Eigen::Matrix<TinyScalar, 3, 1> forceLoc; if (!m_handle_self_collision) { forceLoc = local_basis.transpose() * (BLOCK(forces, vId));// - getVertexMass(vId) * collision_info.speed); } else { forceLoc = local_basis.transpose() * (BLOCK(forces, vId) + BLOCK(m_self_contact_forces[m_current_index], vId) ); } // Estimating the reaction ans.push_back(vId); if (forceLoc[0] > 0.) { // take-off continue; } Eigen::Matrix<TinyScalar, 3, 1> r(0., 0., 0.); // rN must prevent the penetration r[0] = -forceLoc[0]; // rT try to prevent the sliding // Sticking r[1] = -forceLoc[1]; r[2] = -forceLoc[2]; const TinyScalar rT_norm = sqrt(r[1] * r[1] + r[2] * r[2]); if (rT_norm > mu * r[0]) { // but gets stuck at the border of the cone // Sliding r[1] *= mu * r[0] / rT_norm; r[2] *= mu * r[0] / rT_norm; } // Converting r in the global frame r = local_basis * r; if ((!m_handle_self_collision) || (nbSelfCollisions == 0)) { // Adding it directly to the rhs for (unsigned int cmp = 0u; cmp < 3u; ++cmp) { //#pragma omp atomic update Not needed : max 1 contact per vertex LVAL(m_rhs, vId, cmp) = r[cmp]; } // cmp } if (m_handle_self_collision) { // Storing it for (unsigned int cmp = 0u; cmp < 3u; ++cmp) { LVAL(m_contact_forces[m_next_index], vId, cmp) = r[cmp]; } // cmp } // self } // cId const TinyScalar duration_friction = TIMER_DURATION(friction, microseconds); m_friction_times.push_back(duration_friction); #ifdef TIMER_PRINT std::cout << "# Rhs friction : " << duration_friction << " µs" << std::endl; #endif // TIMER_PRINT if ((m_handle_self_collision) && (nbSelfCollisions > 0)) { TIMER_START(self_friction); // Estimated self friction force // for (size_t level = 0u; level < mCollisionDetector->m_collision_computation_order.size(); ++level) { // const std::vector<size_t>& collisions_level_ids = mCollisionDetector->m_collision_computation_order[level]; std::vector<SelfForceToAdd<TinyScalar, TinyConstants> > forces_to_add; // forces_to_add.resize(collisions_level_ids.size()); forces_to_add.resize(nbSelfCollisions); // #pragma omp parallel for for (unsigned int i = 0u; i < forces_to_add.size(); ++i) // for (unsigned int i = 0u; i < collisions_level_ids.size(); ++i) { // const size_t scId = collisions_level_ids[i]; const size_t scId = i; // Data const SelfCollisionInfo<TinyScalar, TinyConstants>& self_collision_info = mCollisionDetector->m_self_collisions_infos[scId]; const size_t vId = self_collision_info.vertex_index; std::vector<size_t> vId_list_old = self_collision_info.vertex_index_list; const std::array<int, 3> fId = self_collision_info.face_indices; const Eigen::Matrix<TinyScalar, 3, 3>& local_basis = mCollisionDetector->m_local_self_contact_basis[scId]; const Eigen::Matrix<TinyScalar, 3, 1>& alpha = self_collision_info.barycentric_coordinates; TinyScalar mu = mFriction; //self_collision_info.friction_coefficient; //compute p and m and transfer to local basis TinyScalar m0 = getVertexMass(fId[0]) + getVertexMass(fId[1]) + getVertexMass(fId[2]); Eigen::Matrix<TinyScalar, 3, 1> f0(0.,0.,0.), r0(0.,0.,0.); for (int i = 0; i < 3; ++i) { f0 += (BLOCK(forces, fId[i]) + BLOCK(m_contact_forces[m_next_index], fId[i])); } f0 = local_basis.transpose() * f0; std::vector<size_t> vId_list; for (int k : vId_list_old) { Eigen::Matrix<TinyScalar, 3, 1> f = local_basis.transpose() * (BLOCK(forces, k) + BLOCK(m_contact_forces[m_next_index], k)); Eigen::Matrix<TinyScalar, 3, 1> rel_v = f / getVertexMass(k) - f0 / m0; if (rel_v[0] <= 0) vId_list.push_back(k); } std::vector<TinyScalar> ms; std::vector<Eigen::Matrix<TinyScalar, 3, 1>> fs, rs(vId_list.size()); TinyScalar smv = 0., sm = 0.; for (int k : vId_list) { ms.push_back(getVertexMass(k)); sm += ms.back(); fs.push_back(local_basis.transpose() * (BLOCK(forces, k) + BLOCK(m_contact_forces[m_next_index], k))); smv += fs.back()[0]; } //compute fn for (int k = 0; k < vId_list.size(); ++k) { TinyScalar fn = (f0[0] + smv) * ms[k] / (m0 + sm) - fs[k][0]; // Eigen::Matrix<TinyScalar, 3, 1> rs[k].fill(0); rs[k][0] += fn; r0[0] -= fn; } //assume all stick from the beginning and remove invalid ones std::vector<bool> stick; for (int k = 0; k < vId_list.size(); ++k) stick.push_back(true); while (1) { //output r0, rs do_solve_friction(f0, m0, r0, fs, ms, rs, stick, mu); bool changed = false; for (int k = 0; k < vId_list.size(); ++k) if (stick[k] && rs[k][1]*rs[k][1]+rs[k][2]*rs[k][2] > mu*rs[k][0]*rs[k][0]) { changed = true; stick[k] = false; } if (!changed) break; // std::cout << "changed!" << std::endl; } //transfer back to world frame r0 = local_basis * r0; Eigen::Matrix<TinyScalar, 3, 1> v0 = (local_basis* f0 + r0) / m0; // std::cout << "expected " << v0.transpose() << std::endl; for (int i = 0; i < 3; ++i) { m_self_contact_forces[m_next_index].col(fId[i]) += v0 * getVertexMass(fId[i]) - (BLOCK(forces, fId[i]) + BLOCK(m_contact_forces[m_next_index], fId[i])); } for (int k = 0; k < vId_list.size(); ++k) { rs[k] = local_basis * rs[k]; m_self_contact_forces[m_next_index].col(vId_list[k]) += rs[k]; } } // scId // #pragma omp parallel for // for (size_t i = 0u; i < collisions_level_ids.size(); ++i) // { // const size_t scId = collisions_level_ids[i]; // const Eigen::Matrix<TinyScalar, 3, 1> prev_force = mCollisionDetector->m_remember_self_contact_forces.col(scId); // const SelfForceToAdd<TinyScalar, TinyConstants>& new_force = forces_to_add[i]; // for (size_t cmp = 0u; cmp < 3u; ++cmp) // { // // Remove from current // // #pragma omp atomic update // LVAL(m_self_contact_forces[m_current_index], new_force.id_plus, cmp) -= // prev_force[cmp]; // // #pragma omp atomic update // for (int k = 0; k < 3; ++k) // LVAL(m_self_contact_forces[m_current_index], new_force.id_minus[k], cmp) += // prev_force[cmp] * new_force.alpha[k]; // // LVAL(m_self_contact_forces[m_current_index], new_force.id_minus, cmp) += // // prev_force[cmp]; // // #pragma omp atomic update // LVAL(m_self_contact_forces[m_next_index], new_force.id_plus, cmp) += // new_force.force[cmp]; // // #pragma omp atomic update // for (int k = 0; k < 3; ++k) // LVAL(m_self_contact_forces[m_next_index], new_force.id_minus[k], cmp) -= // new_force.force[cmp] * new_force.alpha[k]; // // LVAL(m_self_contact_forces[m_next_index], new_force.id_minus, cmp) -= // // new_force.force[cmp]; // // #pragma omp atomic write // mCollisionDetector->m_remember_self_contact_forces(cmp, scId) = new_force.force[cmp]; // } // cmp // } // scId } // level // Add all the forces to the RHS // std::cout << "???" << m_self_contact_forces[m_next_index].col(86).transpose()<<std::endl; m_rhs += m_contact_forces[m_next_index] + m_self_contact_forces[m_next_index] //+ m_self_contact_repercusion_forces[m_next_index] ; const TinyScalar duration_self_friction = TIMER_DURATION(self_friction, microseconds); m_self_friction_times.push_back(duration_self_friction); #ifdef TIMER_PRINT std::cout << "# Rhs self friction : " << duration_self_friction << " µs" << std::endl; #endif // TIMER_PRINT } // Move on next step if (m_handle_self_collision) { m_current_index = m_next_index; m_next_index = (m_next_index) ? 0u : 1u; m_contact_forces[m_next_index].setZero(); m_self_contact_forces[m_next_index].setZero(); // m_self_contact_repercusion_forces[m_next_index].setZero(); m_alpha[m_next_index].setZero(); } return ans; } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: ComputeSolution(const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &deltar, const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &ori_c, Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &hvf, Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &s) { // TIMER_START(total) //tildaV int curr = 0, curc = 0; Eigen::SparseMatrix<TinyScalar> tildaV(mrigidIdx.size(), mDof); std::vector<Eigen::Triplet<TinyScalar>> trips; for (int i = 0; i < mrigidBodies.size(); ++i) if (mlinks[i]->parent == NULL) mlinks[i]->ComputeTildaV(trips, V0, mInitX); tildaV.setFromTriplets(trips.begin(), trips.end()); Qc = tildaV.transpose() * Qc_L; Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> tmp1(mnonrigidIdx.size()); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> tmp2(mrigidIdx.size()); auto tmp = mperm * ori_c; tmp1 = tmp.template segment(0, mnonrigidIdx.size()); tmp2 = tmp.template segment(mnonrigidIdx.size(), mrigidIdx.size()); // std::cout << "tmp2 size " << tmp2.size() << "\n"; mcf = tmp1 - Qc_L.transpose() * V0 - Qf*mNonrigidX; mcs = tildaV.transpose() * (tmp2 - Qb_M * V0 - Qc_L * mNonrigidX); // std::cout << mJointTorque[0] << " " // << mJointTorque[1] << " " // << mJointTorque[2] << " mJointTorque1\n"; // std::cout << "mJointTorque size " << mJointTorque.size() << "\n"; // std::cout << mcs[6] << " " // << mcs[7] << " " // << mcs[8] << " mcs\n"; for (int i = 0; i < mJointTorque.size(); ++i) { mcs[6+i] += mJointTorque[i]; } // std::cout << mcs[6] << " " // << mcs[7] << " " // << mcs[8] << " mcs2\n"; Eigen::Matrix<TinyScalar, Eigen::Dynamic, Eigen::Dynamic> S = tildaV.transpose() * QbMmQcLQfm1QcLT * tildaV; // Eigen::Matrix<TinyScalar, Eigen::Dynamic, Eigen::Dynamic> Sinv = S.inverse(); // TIMER_START(hvf) if (mrigidIdx.size() > 0) { Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> solve_result = mDynamicSolver.solve(-mcf); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> tmp = mcs + Qc * solve_result; s = S.fullPivLu().solve(tmp); hvf = mDynamicSolver.solve(mcf - Qc.transpose() * s); } else { hvf = mDynamicSolver.solve(mcf); Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> ttt = mcf; ttt.setZero(); ttt = mDynamicSolver.solve(ttt); } for (int i = 0; i < mrigidBodies.size(); ++i) mlinks[i]->UpdateT(s); } template <typename TinyScalar, typename TinyConstants> Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> World<TinyScalar, TinyConstants>:: ComputeOriX(const Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> &x_n1) { Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> ans; ans.resize(3*mNumVertices); for (int i = 0; i < mnonrigidIdx.size(); ++i) ans[mnonrigidIdx[i]] = x_n1[i]; for (int i = 0; i < mrigidIdx.size(); ++i) ans[mrigidIdx[i]] = V0[i]; return ans; } template <typename TinyScalar, typename TinyConstants> void World<TinyScalar, TinyConstants>:: ComputeV0NTr() { V0.resize(mrigidIdx.size()); // // std::cout << T.size() << std::endl; // for (int i = 0; i < T.size(); ++i) { // Eigen::JacobiSVD<Eigen::Matrix<TinyScalar, 3, 3>> svd(T[i].template block<3,3>(0,0), Eigen::ComputeFullU | Eigen::ComputeFullV); // Tr[i].template block<3,3>(0,0) = svd.matrixU()*svd.matrixV().transpose(); // Tr[i].template block<3,1>(0,3) = T[i].template block<3,1>(0,3); // // std::cout << Tr[i] << std::endl; // } // for (int i = 0, j = 0; i < mrigidBodies.size(); ++i) { // auto body = mrigidBodies[i]; // Eigen::Matrix34d &cur_Tr = Tr[i]; // for (int k = 0; k < body.size(); ++k) { // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> V = mInitX.segment<3>(body[k]*3), vh(4); // vh<<V,1; // Eigen::Matrix<TinyScalar, Eigen::Dynamic, 1> v0 = cur_Tr * vh; // V0.segment<3>(j) = v0; // j += 3; // } // } for (int i = 0; i < mrigidBodies.size(); ++i) if (mlinks[i]->parent == NULL) mlinks[i]->ComputeV0NTr(V0, mInitX); } #undef EPS }; #endif
kinFoodWeb_kry_omp.c
/* ----------------------------------------------------------------- * Programmer(s): Ting Yan @ SMU * Based on kinFoodWeb_kry.c and parallelized with OpenMP * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2019, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example (serial): * * This example solves a nonlinear system that arises from a system * of partial differential equations. The PDE system is a food web * population model, with predator-prey interaction and diffusion * on the unit square in two dimensions. The dependent variable * vector is the following: * * 1 2 ns * c = (c , c , ..., c ) (denoted by the variable cc) * * and the PDE's are as follows: * * i i * 0 = d(i)*(c + c ) + f (x,y,c) (i=1,...,ns) * xx yy i * * where * * i ns j * f (x,y,c) = c * (b(i) + sum a(i,j)*c ) * i j=1 * * The number of species is ns = 2 * np, with the first np being * prey and the last np being predators. The number np is both the * number of prey and predator species. The coefficients a(i,j), * b(i), d(i) are: * * a(i,i) = -AA (all i) * a(i,j) = -GG (i <= np , j > np) * a(i,j) = EE (i > np, j <= np) * b(i) = BB * (1 + alpha * x * y) (i <= np) * b(i) =-BB * (1 + alpha * x * y) (i > np) * d(i) = DPREY (i <= np) * d(i) = DPRED ( i > np) * * The various scalar parameters are set using define's or in * routine InitUserData. * * The boundary conditions are: normal derivative = 0, and the * initial guess is constant in x and y, but the final solution * is not. * * The PDEs are discretized by central differencing on an MX by * MY mesh. * * The nonlinear system is solved by KINSOL using the method * specified in the local variable globalstrat. * * The preconditioner matrix is a block-diagonal matrix based on * the partial derivatives of the interaction terms f only. * * Constraints are imposed to make all components of the solution * positive. * * Optionally, we can set the number of threads with an environment * variable or from the command line. To check the current value * for number of threads set by the environment variable: * % echo $OMP_NUM_THREADS * * Execution: * * If the user wants to use the default value or the number of * threads set by the environment variable use * % ./kinFoodWeb_kry_omp * If the user wants to specify the number of threads to use * % ./kinFoodWeb_kry_omp num_threads * where num_threads is the number of threads the user wants to use * * ----------------------------------------------------------------- * References: * * 1. Peter N. Brown and Youcef Saad, * Hybrid Krylov Methods for Nonlinear Systems of Equations * LLNL report UCRL-97645, November 1987. * * 2. Peter N. Brown and Alan C. Hindmarsh, * Reduced Storage Matrix Methods in Stiff ODE systems, * Lawrence Livermore National Laboratory Report UCRL-95088, * Rev. 1, June 1987, and Journal of Applied Mathematics and * Computation, Vol. 31 (May 1989), pp. 40-91. (Presents a * description of the time-dependent version of this test * problem.) * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <kinsol/kinsol.h> /* access to KINSOL func., consts. */ #include <nvector/nvector_openmp.h> /* access to OpenMP N_Vector */ #include <sunlinsol/sunlinsol_spgmr.h> /* access to SPGMR SUNLinearSolver */ #include <sundials/sundials_dense.h> /* use generic dense solver in precond. */ #include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */ #ifdef _OPENMP #include <omp.h> #endif /* helpful macros */ #ifndef MAX #define MAX(A, B) ((A) > (B) ? (A) : (B)) #endif /* Problem Constants */ #define NUM_SPECIES 6 /* must equal 2*(number of prey or predators) number of prey = number of predators */ #define PI RCONST(3.1415926535898) /* pi */ #define MX 8 /* MX = number of x mesh points */ #define MY 8 /* MY = number of y mesh points */ #define NSMX (NUM_SPECIES * MX) #define NEQ (NSMX * MY) /* number of equations in the system */ #define AA RCONST(1.0) /* value of coefficient AA in above eqns */ #define EE RCONST(10000.) /* value of coefficient EE in above eqns */ #define GG RCONST(0.5e-6) /* value of coefficient GG in above eqns */ #define BB RCONST(1.0) /* value of coefficient BB in above eqns */ #define DPREY RCONST(1.0) /* value of coefficient dprey above */ #define DPRED RCONST(0.5) /* value of coefficient dpred above */ #define ALPHA RCONST(1.0) /* value of coefficient alpha above */ #define AX RCONST(1.0) /* total range of x variable */ #define AY RCONST(1.0) /* total range of y variable */ #define FTOL RCONST(1.e-7) /* ftol tolerance */ #define STOL RCONST(1.e-13) /* stol tolerance */ #define THOUSAND RCONST(1000.0) /* one thousand */ #define ZERO RCONST(0.0) /* 0. */ #define ONE RCONST(1.0) /* 1. */ #define TWO RCONST(2.0) /* 2. */ #define PREYIN RCONST(1.0) /* initial guess for prey concentrations. */ #define PREDIN RCONST(30000.0)/* initial guess for predator concs. */ /* User-defined vector access macro: IJ_Vptr */ /* IJ_Vptr is defined in order to translate from the underlying 3D structure of the dependent variable vector to the 1D storage scheme for an N-vector. IJ_Vptr(vv,i,j) returns a pointer to the location in vv corresponding to indices is = 0, jx = i, jy = j. */ #define IJ_Vptr(vv,i,j) (&NV_Ith_OMP(vv, i*NUM_SPECIES + j*NSMX)) /* Type : UserData contains preconditioner blocks, pivot arrays, and problem constants */ typedef struct { realtype **P[MX][MY]; sunindextype *pivot[MX][MY]; realtype **acoef, *bcoef; N_Vector rates; realtype *cox, *coy; realtype ax, ay, dx, dy; realtype uround, sqruround; sunindextype mx, my, ns, np; int nthreads; } *UserData; /* Functions Called by the KINSOL Solver */ static int func(N_Vector cc, N_Vector fval, void *user_data); static int PrecSetupBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, void *user_data); static int PrecSolveBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, N_Vector vv, void *user_data); /* Private Helper Functions */ static UserData AllocUserData(void); static void InitUserData(UserData data); static void FreeUserData(UserData data); static void SetInitialProfiles(N_Vector cc, N_Vector sc); static void PrintHeader(int globalstrategy, int maxl, int maxlrst, realtype fnormtol, realtype scsteptol); static void PrintOutput(N_Vector cc); static void PrintFinalStats(void *kmem); static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data); static realtype DotProd(sunindextype size, realtype *x1, realtype *x2); static int check_flag(void *flagvalue, const char *funcname, int opt); /* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- */ int main(int argc, char *argv[]) { int globalstrategy; realtype fnormtol, scsteptol; N_Vector cc, sc, constraints; UserData data; int flag, maxl, maxlrst; void *kmem; SUNLinearSolver LS; int num_threads; cc = sc = constraints = NULL; kmem = NULL; LS = NULL; data = NULL; /* Allocate memory, and set problem data, initial values, tolerances */ globalstrategy = KIN_NONE; /* Set the number of threads to use */ num_threads = 1; /* default value*/ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* Overwrite with OMP_NUM_THREADS environment variable */ #endif if (argc > 1) /* overwrithe with command line value, if supplied */ num_threads = (int) strtol(argv[1], NULL, 0); data = AllocUserData(); if (check_flag((void *)data, "AllocUserData", 2)) return(1); InitUserData(data); data->nthreads = num_threads; /* Create serial vectors of length NEQ */ cc = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)cc, "N_VNew_OpenMP", 0)) return(1); sc = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)sc, "N_VNew_OpenMP", 0)) return(1); data->rates = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)data->rates, "N_VNew_OpenMP", 0)) return(1); constraints = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)constraints, "N_VNew_OpenMP", 0)) return(1); N_VConst(TWO, constraints); SetInitialProfiles(cc, sc); fnormtol=FTOL; scsteptol=STOL; /* Call KINCreate/KINInit to initialize KINSOL. A pointer to KINSOL problem memory is returned and stored in kmem. */ kmem = KINCreate(); if (check_flag((void *)kmem, "KINCreate", 0)) return(1); /* Vector cc passed as template vector. */ flag = KINInit(kmem, func, cc); if (check_flag(&flag, "KINInit", 1)) return(1); flag = KINSetUserData(kmem, data); if (check_flag(&flag, "KINSetUserData", 1)) return(1); flag = KINSetConstraints(kmem, constraints); if (check_flag(&flag, "KINSetConstraints", 1)) return(1); flag = KINSetFuncNormTol(kmem, fnormtol); if (check_flag(&flag, "KINSetFuncNormTol", 1)) return(1); flag = KINSetScaledStepTol(kmem, scsteptol); if (check_flag(&flag, "KINSetScaledStepTol", 1)) return(1); /* We no longer need the constraints vector since KINSetConstraints creates a private copy for KINSOL to use. */ N_VDestroy(constraints); /* Create SUNLinSol_SPGMR object with right preconditioning and the maximum Krylov dimension maxl */ maxl = 15; LS = SUNLinSol_SPGMR(cc, PREC_RIGHT, maxl); if(check_flag((void *)LS, "SUNLinSol_SPGMR", 0)) return(1); /* Attach the linear solver to KINSOL */ flag = KINSetLinearSolver(kmem, LS, NULL); if (check_flag(&flag, "KINSetLinearSolver", 1)) return 1; /* Set the maximum number of restarts */ maxlrst = 2; flag = SUNLinSol_SPGMRSetMaxRestarts(LS, maxlrst); if (check_flag(&flag, "SUNLinSol_SPGMRSetMaxRestarts", 1)) return(1); /* Specify the preconditioner setup and solve routines */ flag = KINSetPreconditioner(kmem, PrecSetupBD, PrecSolveBD); if (check_flag(&flag, "KINSetPreconditioner", 1)) return(1); /* Print out the problem size, solution parameters, initial guess. */ PrintHeader(globalstrategy, maxl, maxlrst, fnormtol, scsteptol); /* Call KINSol and print output concentration profile */ flag = KINSol(kmem, /* KINSol memory block */ cc, /* initial guess on input; solution vector */ globalstrategy, /* global strategy choice */ sc, /* scaling vector for the variable cc */ sc); /* scaling vector for function values fval */ if (check_flag(&flag, "KINSol", 1)) return(1); printf("\n\nComputed equilibrium species concentrations:\n"); PrintOutput(cc); /* Print final statistics and free memory */ PrintFinalStats(kmem); printf("num_threads = %i\n", num_threads); N_VDestroy(cc); N_VDestroy(sc); KINFree(&kmem); SUNLinSolFree(LS); FreeUserData(data); return(0); } /* Readability definitions used in other routines below */ #define acoef (data->acoef) #define bcoef (data->bcoef) #define cox (data->cox) #define coy (data->coy) /* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY KINSOL *-------------------------------------------------------------------- */ /* * System function for predator-prey system */ static int func(N_Vector cc, N_Vector fval, void *user_data) { realtype xx, yy, delx, dely, *cxy, *rxy, *fxy, dcyli, dcyui, dcxli, dcxri; sunindextype jx, jy, is, idyu, idyl, idxr, idxl; UserData data; data = (UserData)user_data; delx = data->dx; dely = data->dy; /* Loop over all mesh points, evaluating rate array at each point*/ for (jy = 0; jy < MY; jy++) { yy = dely*jy; /* Set lower/upper index shifts, special at boundaries. */ idyl = (jy != 0 ) ? NSMX : -NSMX; idyu = (jy != MY-1) ? NSMX : -NSMX; for (jx = 0; jx < MX; jx++) { xx = delx*jx; /* Set left/right index shifts, special at boundaries. */ idxl = (jx != 0 ) ? NUM_SPECIES : -NUM_SPECIES; idxr = (jx != MX-1) ? NUM_SPECIES : -NUM_SPECIES; cxy = IJ_Vptr(cc,jx,jy); rxy = IJ_Vptr(data->rates,jx,jy); fxy = IJ_Vptr(fval,jx,jy); /* Get species interaction rate array at (xx,yy) */ WebRate(xx, yy, cxy, rxy, user_data); for(is = 0; is < NUM_SPECIES; is++) { /* Differencing in x direction */ dcyli = *(cxy+is) - *(cxy - idyl + is) ; dcyui = *(cxy + idyu + is) - *(cxy+is); /* Differencing in y direction */ dcxli = *(cxy+is) - *(cxy - idxl + is); dcxri = *(cxy + idxr +is) - *(cxy+is); /* Compute the total rate value at (xx,yy) */ fxy[is] = (coy)[is] * (dcyui - dcyli) + (cox)[is] * (dcxri - dcxli) + rxy[is]; } /* end of is loop */ } /* end of jx loop */ } /* end of jy loop */ return(0); } /* * Preconditioner setup routine. Generate and preprocess P. */ static int PrecSetupBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, void *user_data) { realtype r, r0, uround, sqruround, xx, yy, delx, dely, csave, fac; realtype *cxy, *scxy, **Pxy, *ratesxy, *Pxycol, perturb_rates[NUM_SPECIES]; sunindextype i, j, jx, jy, ret; UserData data; data = (UserData) user_data; delx = data->dx; dely = data->dy; uround = data->uround; sqruround = data->sqruround; fac = N_VWL2Norm(fval, fscale); r0 = THOUSAND * uround * fac * NEQ; if(r0 == ZERO) r0 = ONE; /* Loop over spatial points; get size NUM_SPECIES Jacobian block at each */ for (jy = 0; jy < MY; jy++) { yy = jy*dely; for (jx = 0; jx < MX; jx++) { xx = jx*delx; Pxy = (data->P)[jx][jy]; cxy = IJ_Vptr(cc,jx,jy); scxy= IJ_Vptr(cscale,jx,jy); ratesxy = IJ_Vptr((data->rates),jx,jy); /* Compute difference quotients of interaction rate fn. */ for (j = 0; j < NUM_SPECIES; j++) { csave = cxy[j]; /* Save the j,jx,jy element of cc */ r = MAX(sqruround*fabs(csave), r0/scxy[j]); cxy[j] += r; /* Perturb the j,jx,jy element of cc */ fac = ONE/r; WebRate(xx, yy, cxy, perturb_rates, data); /* Restore j,jx,jy element of cc */ cxy[j] = csave; /* Load the j-th column of difference quotients */ Pxycol = Pxy[j]; #pragma omp parallel for default(shared) private(i) for (i = 0; i < NUM_SPECIES; i++) Pxycol[i] = (perturb_rates[i] - ratesxy[i]) * fac; } /* end of j loop */ /* Do LU decomposition of size NUM_SPECIES preconditioner block */ ret = denseGETRF(Pxy, NUM_SPECIES, NUM_SPECIES, (data->pivot)[jx][jy]); if (ret != 0) return(1); } /* end of jx loop */ } /* end of jy loop */ return(0); } /* * Preconditioner solve routine */ static int PrecSolveBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, N_Vector vv, void *user_data) { realtype **Pxy, *vxy; sunindextype *piv, jx, jy; UserData data; data = (UserData)user_data; #pragma omp parallel for collapse(2) default(shared) private(jx, jy, Pxy, piv, vxy) schedule(static) for (jx=0; jx<MX; jx++) { for (jy=0; jy<MY; jy++) { /* For each (jx,jy), solve a linear system of size NUM_SPECIES. vxy is the address of the corresponding portion of the vector vv; Pxy is the address of the corresponding block of the matrix P; piv is the address of the corresponding block of the array pivot. */ vxy = IJ_Vptr(vv,jx,jy); Pxy = (data->P)[jx][jy]; piv = (data->pivot)[jx][jy]; denseGETRS(Pxy, NUM_SPECIES, piv, vxy); } /* end of jy loop */ } /* end of jx loop */ return(0); } /* * Interaction rate function routine */ static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data) { sunindextype i; realtype fac; UserData data; data = (UserData)user_data; for (i = 0; i<NUM_SPECIES; i++) ratesxy[i] = DotProd(NUM_SPECIES, cxy, acoef[i]); fac = ONE + ALPHA * xx * yy; #pragma omp parallel for default(shared) private(i) for (i = 0; i < NUM_SPECIES; i++) ratesxy[i] = cxy[i] * ( bcoef[i] * fac + ratesxy[i] ); } /* * Dot product routine for realtype arrays */ static realtype DotProd(sunindextype size, realtype *x1, realtype *x2) { sunindextype i; realtype *xx1, *xx2, temp = ZERO; xx1 = x1; xx2 = x2; for (i = 0; i < size; i++) temp += (*xx1++) * (*xx2++); return(temp); } /* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- */ /* * Allocate memory for data structure of type UserData */ static UserData AllocUserData(void) { int jx, jy; UserData data; data = (UserData) malloc(sizeof *data); for (jx=0; jx < MX; jx++) { for (jy=0; jy < MY; jy++) { (data->P)[jx][jy] = newDenseMat(NUM_SPECIES, NUM_SPECIES); (data->pivot)[jx][jy] = newIndexArray(NUM_SPECIES); } } acoef = newDenseMat(NUM_SPECIES, NUM_SPECIES); bcoef = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); cox = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); coy = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); return(data); } /* * Load problem constants in data */ static void InitUserData(UserData data) { sunindextype i, j, np; realtype *a1,*a2, *a3, *a4, dx2, dy2; data->mx = MX; data->my = MY; data->ns = NUM_SPECIES; data->np = NUM_SPECIES/2; data->ax = AX; data->ay = AY; data->dx = (data->ax)/(MX-1); data->dy = (data->ay)/(MY-1); data->uround = UNIT_ROUNDOFF; data->sqruround = sqrt(data->uround); /* Set up the coefficients a and b plus others found in the equations */ np = data->np; dx2=(data->dx)*(data->dx); dy2=(data->dy)*(data->dy); for (i = 0; i < np; i++) { a1= &(acoef[i][np]); a2= &(acoef[i+np][0]); a3= &(acoef[i][0]); a4= &(acoef[i+np][np]); /* Fill in the portion of acoef in the four quadrants, row by row */ for (j = 0; j < np; j++) { *a1++ = -GG; *a2++ = EE; *a3++ = ZERO; *a4++ = ZERO; } /* and then change the diagonal elements of acoef to -AA */ acoef[i][i]=-AA; acoef[i+np][i+np] = -AA; bcoef[i] = BB; bcoef[i+np] = -BB; cox[i]=DPREY/dx2; cox[i+np]=DPRED/dx2; coy[i]=DPREY/dy2; coy[i+np]=DPRED/dy2; } } /* * Free data memory */ static void FreeUserData(UserData data) { int jx, jy; for (jx=0; jx < MX; jx++) { for (jy=0; jy < MY; jy++) { destroyMat((data->P)[jx][jy]); destroyArray((data->pivot)[jx][jy]); } } destroyMat(acoef); free(bcoef); free(cox); free(coy); N_VDestroy(data->rates); free(data); } /* * Set initial conditions in cc */ static void SetInitialProfiles(N_Vector cc, N_Vector sc) { int i, jx, jy; realtype *cloc, *sloc; realtype ctemp[NUM_SPECIES], stemp[NUM_SPECIES]; /* Initialize arrays ctemp and stemp used in the loading process */ for (i = 0; i < NUM_SPECIES/2; i++) { ctemp[i] = PREYIN; stemp[i] = ONE; } for (i = NUM_SPECIES/2; i < NUM_SPECIES; i++) { ctemp[i] = PREDIN; stemp[i] = RCONST(0.00001); } /* Load initial profiles into cc and sc vector from ctemp and stemp. */ for (jy = 0; jy < MY; jy++) { for (jx = 0; jx < MX; jx++) { cloc = IJ_Vptr(cc,jx,jy); sloc = IJ_Vptr(sc,jx,jy); for (i = 0; i < NUM_SPECIES; i++) { cloc[i] = ctemp[i]; sloc[i] = stemp[i]; } } } } /* * Print first lines of output (problem description) */ static void PrintHeader(int globalstrategy, int maxl, int maxlrst, realtype fnormtol, realtype scsteptol) { printf("\nPredator-prey test problem -- KINSol (OpenMP version)\n\n"); printf("Mesh dimensions = %d X %d\n", MX, MY); printf("Number of species = %d\n", NUM_SPECIES); printf("Total system size = %d\n\n", NEQ); printf("Flag globalstrategy = %d (0 = None, 1 = Linesearch)\n", globalstrategy); printf("Linear solver is SPGMR with maxl = %d, maxlrst = %d\n", maxl, maxlrst); printf("Preconditioning uses interaction-only block-diagonal matrix\n"); printf("Positivity constraints imposed on all components \n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("Tolerance parameters: fnormtol = %Lg scsteptol = %Lg\n", fnormtol, scsteptol); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #else printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #endif printf("\nInitial profile of concentration\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("At all mesh points: %Lg %Lg %Lg %Lg %Lg %Lg\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #else printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #endif } /* * Print sampled values of current cc */ static void PrintOutput(N_Vector cc) { int is, jx, jy; realtype *ct; jy = 0; jx = 0; ct = IJ_Vptr(cc,jx,jy); printf("\nAt bottom left:"); /* Print out lines with up to 6 values per line */ for (is = 0; is < NUM_SPECIES; is++){ if ((is%6)*6 == is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",ct[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",ct[is]); #else printf(" %g",ct[is]); #endif } jy = MY-1; jx = MX-1; ct = IJ_Vptr(cc,jx,jy); printf("\n\nAt top right:"); /* Print out lines with up to 6 values per line */ for (is = 0; is < NUM_SPECIES; is++) { if ((is%6)*6 == is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",ct[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",ct[is]); #else printf(" %g",ct[is]); #endif } printf("\n\n"); } /* * Print final statistics contained in iopt */ static void PrintFinalStats(void *kmem) { long int nni, nfe, nli, npe, nps, ncfl, nfeSG; int flag; flag = KINGetNumNonlinSolvIters(kmem, &nni); check_flag(&flag, "KINGetNumNonlinSolvIters", 1); flag = KINGetNumFuncEvals(kmem, &nfe); check_flag(&flag, "KINGetNumFuncEvals", 1); flag = KINGetNumLinIters(kmem, &nli); check_flag(&flag, "KINGetNumLinIters", 1); flag = KINGetNumPrecEvals(kmem, &npe); check_flag(&flag, "KINGetNumPrecEvals", 1); flag = KINGetNumPrecSolves(kmem, &nps); check_flag(&flag, "KINGetNumPrecSolves", 1); flag = KINGetNumLinConvFails(kmem, &ncfl); check_flag(&flag, "KINGetNumLinConvFails", 1); flag = KINGetNumLinFuncEvals(kmem, &nfeSG); check_flag(&flag, "KINGetNumLinFuncEvals", 1); printf("Final Statistics.. \n"); printf("nni = %5ld nli = %5ld\n", nni, nli); printf("nfe = %5ld nfeSG = %5ld\n", nfe, nfeSG); printf("nps = %5ld npe = %5ld ncfl = %5ld\n", nps, npe, ncfl); } /* * Check function return value... * opt == 0 means SUNDIALS function allocates memory so check if * returned NULL pointer * opt == 1 means SUNDIALS function returns a flag so check if * flag >= 0 * opt == 2 means function allocates memory so check if returned * NULL pointer */ static int check_flag(void *flagvalue, const char *funcname, int opt) { int *errflag; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && flagvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } /* Check if flag < 0 */ else if (opt == 1) { errflag = (int *) flagvalue; if (*errflag < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n", funcname, *errflag); return(1); } } /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && flagvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } return(0); }
Parallelizer.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_PARALLELIZER_H #define EIGEN_PARALLELIZER_H #if EIGEN_HAS_CXX11_ATOMIC #include <atomic> #endif namespace Eigen { namespace internal { /** \internal */ inline void manage_multi_threading(Action action, int* v) { static int m_maxThreads = -1; EIGEN_UNUSED_VARIABLE(m_maxThreads); if(action==SetAction) { eigen_internal_assert(v!=0); m_maxThreads = *v; } else if(action==GetAction) { eigen_internal_assert(v!=0); #ifdef EIGEN_HAS_OPENMP if(m_maxThreads>0) *v = m_maxThreads; else *v = omp_get_max_threads(); #else *v = 1; #endif } else { eigen_internal_assert(false); } } } /** Must be call first when calling Eigen from multiple threads */ inline void initParallel() { int nbt; internal::manage_multi_threading(GetAction, &nbt); std::ptrdiff_t l1, l2, l3; internal::manage_caching_sizes(GetAction, &l1, &l2, &l3); } /** \returns the max number of threads reserved for Eigen * \sa setNbThreads */ inline int nbThreads() { int ret; internal::manage_multi_threading(GetAction, &ret); return ret; } /** Sets the max number of threads reserved for Eigen * \sa nbThreads */ inline void setNbThreads(int v) { internal::manage_multi_threading(SetAction, &v); } namespace internal { template<typename Index> struct GemmParallelInfo { GemmParallelInfo() : sync(-1), users(0), lhs_start(0), lhs_length(0) {} // volatile is not enough on all architectures (see bug 1572) // to guarantee that when thread A says to thread B that it is // done with packing a block, then all writes have been really // carried out... C++11 memory model+atomic guarantees this. #if EIGEN_HAS_CXX11_ATOMIC std::atomic<Index> sync; std::atomic<int> users; #else Index volatile sync; int volatile users; #endif Index lhs_start; Index lhs_length; }; template<bool Condition, typename Functor, typename Index> void parallelize_gemm(const Functor& func, Index rows, Index cols, Index depth, bool transpose) { // TODO when EIGEN_USE_BLAS is defined, // we should still enable OMP for other scalar types // Without C++11, we have to disable GEMM's parallelization on // non x86 architectures because there volatile is not enough for our purpose. // See bug 1572. #if (! defined(EIGEN_HAS_OPENMP)) || defined(EIGEN_USE_BLAS) || ((!EIGEN_HAS_CXX11_ATOMIC) && !(EIGEN_ARCH_i386_OR_x86_64)) // FIXME the transpose variable is only needed to properly split // the matrix product when multithreading is enabled. This is a temporary // fix to support row-major destination matrices. This whole // parallelizer mechanism has to be redesigned anyway. EIGEN_UNUSED_VARIABLE(depth); EIGEN_UNUSED_VARIABLE(transpose); func(0,rows, 0,cols); #else // Dynamically check whether we should enable or disable OpenMP. // The conditions are: // - the max number of threads we can create is greater than 1 // - we are not already in a parallel code // - the sizes are large enough // compute the maximal number of threads from the size of the product: // This first heuristic takes into account that the product kernel is fully optimized when working with nr columns at once. Index size = transpose ? rows : cols; Index pb_max_threads = std::max<Index>(1,size / Functor::Traits::nr); // compute the maximal number of threads from the total amount of work: double work = static_cast<double>(rows) * static_cast<double>(cols) * static_cast<double>(depth); double kMinTaskSize = 50000; // FIXME improve this heuristic. pb_max_threads = std::max<Index>(1, std::min<Index>(pb_max_threads, work / kMinTaskSize)); // compute the number of threads we are going to use Index threads = std::min<Index>(nbThreads(), pb_max_threads); // if multi-threading is explicitly disabled, not useful, or if we already are in a parallel session, // then abort multi-threading // FIXME omp_get_num_threads()>1 only works for openmp, what if the user does not use openmp? if((!Condition) || (threads==1) || (omp_get_num_threads()>1)) return func(0,rows, 0,cols); Eigen::initParallel(); func.initParallelSession(threads); if(transpose) std::swap(rows,cols); ei_declare_aligned_stack_constructed_variable(GemmParallelInfo<Index>,info,threads,0); #pragma omp parallel num_threads(threads) { Index i = omp_get_thread_num(); // Note that the actual number of threads might be lower than the number of request ones. Index actual_threads = omp_get_num_threads(); Index blockCols = (cols / actual_threads) & ~Index(0x3); Index blockRows = (rows / actual_threads); blockRows = (blockRows/Functor::Traits::mr)*Functor::Traits::mr; Index r0 = i*blockRows; Index actualBlockRows = (i+1==actual_threads) ? rows-r0 : blockRows; Index c0 = i*blockCols; Index actualBlockCols = (i+1==actual_threads) ? cols-c0 : blockCols; info[i].lhs_start = r0; info[i].lhs_length = actualBlockRows; if(transpose) func(c0, actualBlockCols, 0, rows, info); else func(0, rows, c0, actualBlockCols, info); } #endif } } // end namespace internal } // end namespace Eigen #endif // EIGEN_PARALLELIZER_H
syrk.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "syrk.h" /* Array initialization. */ static void init_array(int ni, int nj, DATA_TYPE *alpha, DATA_TYPE *beta, DATA_TYPE POLYBENCH_2D(C,NI,NI,ni,ni), DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { int i __attribute__((annotate("scalar(range(0, " PB_XSTR(NI) ") final)"))); int j __attribute__((annotate("scalar(range(0, " PB_XSTR(NJ) ") final)"))); *alpha = 32412; *beta = 2123; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) A[i][j] = ((DATA_TYPE) i*j) / ni; for (i = 0; i < ni; i++) for (j = 0; j < ni; j++) C[i][j] = ((DATA_TYPE) i*j) / ni; } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, DATA_TYPE POLYBENCH_2D(C,NI,NI,ni,ni)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < ni; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, C[i][j]); if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_syrk(int ni, int nj, DATA_TYPE alpha, DATA_TYPE beta, DATA_TYPE POLYBENCH_2D(C,NI,NI,ni,ni), DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { int i, j, k; #pragma scop #pragma omp parallel { /* C := alpha*A*A' + beta*C */ #pragma omp for private(j) for (i = 0; i < _PB_NI; i++) for (j = 0; j < _PB_NI; j++) C[i][j] *= beta; #pragma omp for private(j,k) for (i = 0; i < _PB_NI; i++) for (j = 0; j < _PB_NI; j++) for (k = 0; k < _PB_NJ; k++) C[i][j] += alpha * A[i][k] * A[j][k]; } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; /* Variable declaration/allocation. */ DATA_TYPE alpha __attribute__((annotate("target('alpha') scalar()"))); DATA_TYPE beta __attribute__((annotate("target('beta') scalar()"))); POLYBENCH_2D_ARRAY_DECL(C,DATA_TYPE __attribute__((annotate("target('C') scalar(range(0, 12000000000000) final)"))),NI,NI,ni,ni); POLYBENCH_2D_ARRAY_DECL(A,DATA_TYPE __attribute__((annotate("target('A') scalar()"))),NI,NJ,ni,nj); /* Initialize array(s). */ init_array (ni, nj, &alpha, &beta, POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(A)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_syrk (ni, nj, alpha, beta, POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(A)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, POLYBENCH_ARRAY(C))); /* Be clean. */ POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(A); return 0; }
parallel_blocked_ldlt_03.h
// // Created by Kazem on 12/31/18. // #ifndef PROJECT_SERIAL_BLOCKED_LDL_03_H #define PROJECT_SERIAL_BLOCKED_LDL_03_H #include <stdlib.h> #include <cmath> #include <cassert> #include "mkl.h" #include "Reach.h" #include "Sym_BLAS.h" namespace nasoq { #undef TIMING #undef TLAST bool ldl_left_sn_parallel_03(int n, const int *c, const int *r, const double *values, const size_t *lC, int *lR, const size_t *Li_ptr, double *lValues, double *D, const int *blockSet, const int supNo, double *timing, #ifndef PRUNE int *aTree, int *cT, int *rT, int *col2Sup, #else int *prunePtr, int *pruneSet, #endif const int nLevels, const int *levelPtr, const int *levelSet, const int nPar, const int *parPtr, const int *partition, const int chunk, const int threads, const int super_max, const int col_max, int &nbpivot, int *perm_piv, double threshold = 1e-13) { /* * For timing using BLAS */ const int incx = 1; int top = 0; int *xi; //= new int[2*supNo](); int *swap_full = new int[n](); std::vector<int> perm_req; //int super_max = 64; //tunig parameter for the max size of supernodes TODO: find it in analysis //int col_max = n; int *map; //= new int[n](); double *contribs; //= new double[super_max*col_max](); double *trn_diag; //= new double[super_max*col_max](); int info; double one[2], zero[2]; one[0] = 1.0; /* ALPHA for *syrk, *herk, *gemm, and *trsm */ one[1] = 0.; zero[0] = 0.; /* BETA for *syrk, *herk, and *gemm */ zero[1] = 0.; int *ipiv; //= new int[n](); std::chrono::time_point<std::chrono::system_clock> start, end, startin, endin; std::chrono::duration<double> elapsed_seconds; double duration4 = 0, duration3 = 0, duration2 = 0, duration1 = 0; #ifdef TIMING start = std::chrono::system_clock::now(); #endif for (int i1 = 0; i1 < nLevels - 1; ++i1) { #pragma omp parallel //shared(lValues)//private(map, contribs) { #pragma omp for schedule(dynamic) private(map, trn_diag, contribs, xi, startin, endin, duration2) for (int j1 = levelPtr[i1]; j1 < levelPtr[i1 + 1]; ++j1) { #ifdef BLASTIMING int threadID = omp_get_thread_num(); std::chrono::time_point<std::chrono::system_clock> startBlas, endBlas; #endif map = new int[n](); contribs = new double[super_max * col_max](); xi = new int[2 * supNo](); trn_diag = new double[super_max * col_max](); //int pls = levelSet[j1]; #ifdef TIMING1 startin = std::chrono::system_clock::now(); #endif //#pragma omp parallel for schedule(static,chunk)private(thth) for (int k1 = parPtr[j1]; k1 < parPtr[j1 + 1]; ++k1) { int s = partition[k1] + 1; int curCol = s != 0 ? blockSet[s - 1] : 0; int nxtCol = blockSet[s]; int supWdt = nxtCol - curCol; int nSupR = Li_ptr[nxtCol] - Li_ptr[curCol];//row size of supernode for (int i = Li_ptr[curCol], cnt = 0; i < Li_ptr[nxtCol]; ++i) { map[lR[i]] = cnt++;//mapping L rows position to actual row idx } for (int m1 = curCol; m1 < nxtCol; ++m1) { perm_piv[m1] = m1;//No orderimg so far //swap_full[m1] = m1; } //copy the columns from A to L for (int i = curCol; i < nxtCol; ++i) {//Copy A to L int pad = i - curCol; for (int j = c[i]; j < c[i + 1]; ++j) { // if(r[j]>=i)//does not need to save upper part. lValues[lC[i] + map[r[j]]] = values[j]; // else // printf("dddd\n"); } } #if DEBUG top = ereach_sn(supNo,c,r,curCol,nxtCol,col2sup, eTree,xi,xi+supNo); if(supNo-top != prunePtr[s]-prunePtr[s-1]) printf("sss"); #endif double *src, *cur = &lValues[lC[curCol]];//pointing to first element of the current supernode //#ifndef PRUNE top = ereach_sn(supNo, cT, rT, curCol, nxtCol, col2Sup, aTree, xi, xi + supNo); assert(top >= 0); //if(s==2){top =2; xi[top] = 0;} for (int i = top; i < supNo; ++i) { int lSN = xi[i]; /*#else for (int i = prunePtr[s - 1]; i < prunePtr[s]; ++i) { int lSN = pruneSet[i]; #endif*/ int nSupRs = 0; #if DEBUG if(xi[top++] != lSN) printf("fail"); #endif int cSN = blockSet[lSN];//first col of current SN int cNSN = blockSet[lSN + 1];//first col of Next SN int Li_ptr_cNSN = Li_ptr[cNSN]; int Li_ptr_cSN = Li_ptr[cSN]; int nSNRCur = Li_ptr_cNSN - Li_ptr_cSN; int supWdts = cNSN - cSN;//The width of current src SN int lb = 0, ub = 0; bool sw = true; int beg_col = cSN, end_col = 0; for (int j = Li_ptr_cSN; j < Li_ptr_cNSN; ++j) { //finding the overlap between curCol and curCol+supWdt in the src col if (lR[j] >= curCol && sw) { //src*transpose(row lR[j]) lb = j - Li_ptr_cSN; sw = false; } if (lR[j] < curCol + supWdt && !sw) { ub = j - Li_ptr_cSN; } } nSupRs = Li_ptr_cNSN - Li_ptr_cSN - lb; int ndrow1 = ub - lb + 1; int ndrow3 = nSupRs - ndrow1; src = &lValues[lC[cSN] + lb];//first element of src supernode starting from row lb double *srcL = &lValues[lC[cSN] + ub + 1]; // multiplying L * D for (int l = 0; l < supWdts; ++l) { double tmp = D[cSN + l]; for (int l1 = 0; l1 < nSupRs; ++l1) { trn_diag[l * nSupRs + l1] = tmp * src[l * nSNRCur + l1]; } } /*dgemm("N", "C", &ndrow3, &ndrow1, &supWdts, one, srcL, &nSNRCur, src, &nSNRCur, zero, &contribs[ndrow1], &nSupRs);*/ dgemm("N", "C", &nSupRs, &ndrow1, &supWdts, one, trn_diag, &nSupRs, src, &nSNRCur, zero, contribs, &nSupRs); //copying contrib to L for (int i = 0; i < ndrow1; ++i) {//Copy contribs to L int col = map[lR[Li_ptr_cSN + i + lb]];//col in the SN //double ddiag = 1.0 ;/// D[col]; for (int j = i; j < nSupRs; ++j) { int cRow = lR[Li_ptr_cSN + j + lb];//corresponding row in SN //lValues[lC[curCol+col]+ map[cRow]] -= contribs[i*nSupRs+j]; cur[col * nSupR + map[cRow]] -= contribs[i * nSupRs + j]; } } } #ifdef MKL //dpotrf("L",&supWdt,cur,&nSupR,&info); sym_sytrf(cur, supWdt, nSupR, &nbpivot, threshold); //LAPACKE_dsytrf(LAPACK_COL_MAJOR,'L',supWdt,cur,nSupR,ipiv); #endif // Making L*D int rowNo = nSupR - supWdt; for (int l = 0; l < supWdt; ++l) { double tmp = cur[l + l * nSupR]; D[curCol + l] = tmp; double *stCol = trn_diag + l * supWdt + l; double *curCol = cur + l * nSupR + l; *stCol = tmp; for (int l1 = 0; l1 < supWdt - l - 1; ++l1) { *(++stCol) = tmp * *(++curCol); } } dtrsm("R", "L", "C", "N", &rowNo, &supWdt, one, trn_diag, &supWdt, &cur[supWdt], &nSupR); for (int k = 0; k < supWdt; ++k) { cur[k * nSupR + k] = 1.0; } //copying 1/Di into D /*for (int l = 0; l < supWdt; ++l) { D[curCol+l] = one[0] / cur[l + l*nSupR]; }*/ /* for (int k = 0; k < nSupR * supWdt; ++k) { std::cout<<cur[k]<<","; } std::cout<<"==== \n";*/ } delete[]contribs; delete[]trn_diag; delete[]xi; delete[]map; } #ifdef TIMING1 endin = std::chrono::system_clock::now(); elapsed_seconds = endin-startin; duration1=elapsed_seconds.count(); int thth2=omp_get_thread_num(); std::cout<<"**"<<thth2<<" : "<<j1<<" "<<duration1<<"\n"; #endif } } #if 1 //LAst iteration MKL_Domain_Set_Num_Threads(threads, MKL_DOMAIN_BLAS); map = new int[n](); contribs = new double[super_max * col_max](); xi = new int[3 * supNo](); trn_diag = new double[super_max * col_max](); int *ws = new int[3 * super_max](); ipiv = new int[super_max](); for (int j1 = levelPtr[nLevels - 1]; j1 < levelPtr[nLevels]; ++j1) { #ifdef TLAST start = std::chrono::system_clock::now(); #endif for (int k1 = parPtr[j1]; k1 < parPtr[j1 + 1]; ++k1) { int s = partition[k1] + 1; int curCol = s != 0 ? blockSet[s - 1] : 0; int nxtCol = blockSet[s]; int supWdt = nxtCol - curCol; int nSupR = Li_ptr[nxtCol] - Li_ptr[curCol];//row size of supernode for (int i = Li_ptr[curCol], cnt = 0; i < Li_ptr[nxtCol]; ++i) { map[lR[i]] = cnt++;//mapping L rows position to actual row idx } //copy the columns from A to L for (int i = curCol; i < nxtCol; ++i) {//Copy A to L int pad = i - curCol; for (int j = c[i]; j < c[i + 1]; ++j) { lValues[lC[i] + map[r[j]]] = values[j]; } } double *src, *cur = &lValues[lC[curCol]];//pointing to first element of the current supernode top = ereach_sn(supNo, cT, rT, curCol, nxtCol, col2Sup, aTree, xi, xi + supNo); assert(top >= 0); //int *lbs = xi+supNo, *ubs = xi + 2*supNo;//To use for row permutation //if(s==2){top =2; xi[top] = 0;} for (int i = top; i < supNo; ++i) { int lSN = xi[i]; int nSupRs = 0; int cSN = blockSet[lSN];//first col of current SN int cNSN = blockSet[lSN + 1];//first col of Next SN int Li_ptr_cNSN = Li_ptr[cNSN]; int Li_ptr_cSN = Li_ptr[cSN]; int nSNRCur = Li_ptr_cNSN - Li_ptr_cSN; int supWdts = cNSN - cSN;//The width of current src SN int lb = 0, ub = 0; bool sw = true; int beg_col = cSN, end_col = 0; for (int j = Li_ptr_cSN; j < Li_ptr_cNSN; ++j) { //finding the overlap between curCol and curCol+supWdt in the src col if (lR[j] >= curCol && sw) { //src*transpose(row lR[j]) lb = j - Li_ptr_cSN; //lbs[i] = lb; sw = false; } if (lR[j] < curCol + supWdt && !sw) { ub = j - Li_ptr_cSN; //ubs[i] = ub; } } nSupRs = Li_ptr_cNSN - Li_ptr_cSN - lb; int ndrow1 = ub - lb + 1; int ndrow3 = nSupRs - ndrow1; src = &lValues[lC[cSN] + lb];//first element of src supernode starting from row lb double *srcL = &lValues[lC[cSN] + ub + 1]; blocked_2by2_mult(supWdts, nSupRs, &D[cSN], src, trn_diag, nSNRCur, n); dgemm("N", "C", &nSupRs, &ndrow1, &supWdts, one, trn_diag, &nSupRs, src, &nSNRCur, zero, contribs, &nSupRs); // } //copying contrib to L for (int i = 0; i < ndrow1; ++i) {//Copy contribs to L int col = map[lR[Li_ptr_cSN + i + lb]];//col in the SN //double ddiag = 1.0 ;/// D[col]; for (int j = i; j < nSupRs; ++j) { int cRow = lR[Li_ptr_cSN + j + lb];//corresponding row in SN //lValues[lC[curCol+col]+ map[cRow]] -= contribs[i*nSupRs+j]; cur[col * nSupR + map[cRow]] -= contribs[i * nSupRs + j]; /* if ( cRow == 78){ std::cout<<"\n====="<<cSN<<"|| "<< cRow<<";;"<<contribs[i*nSupRs+j]<<";;" <<cur[col*nSupR+map[cRow]]<<";;"<<"\n"; }*/ } } } LAPACKE_dsytrf(LAPACK_COL_MAJOR, 'L', supWdt, cur, nSupR, ipiv); int is_perm = reorder_after_sytrf(supWdt, cur, nSupR, ipiv, &perm_piv[curCol], &D[curCol], n, &swap_full[curCol], ws + supWdt); // re-order the columns of the super-node int rowNo = nSupR - supWdt; for (int m = 0; m < supWdt; ++m) { perm_piv[curCol + m]++; } if (is_perm) { LAPACKE_dlapmt(LAPACK_COL_MAJOR, 1, rowNo, supWdt, &cur[supWdt], nSupR, &perm_piv[curCol]); perm_req.push_back(s); } //reordering row for (int k1 = 0; k1 < supWdt; ++k1) { perm_piv[curCol + k1] += (curCol - 1); // perm_piv++; } for (int l = 0; l < supWdt; ++l) { D[curCol + l] = cur[l + l * nSupR]; cur[l + l * nSupR] = 1.0; } dtrsm("R", "L", "C", "U", &rowNo, &supWdt, one, cur, &nSupR, &cur[supWdt], &nSupR); blocked_2by2_solver(supWdt, &D[curCol], &cur[supWdt], rowNo, nSupR, n); } #ifdef TLAST end = std::chrono::system_clock::now(); elapsed_seconds = end-start; duration1=elapsed_seconds.count(); std::cout<<"++ " <<duration1<<"\n"; #endif } for (int k = 0; k < super_max; ++k) { ws[k] = 0; } row_reordering(supNo, lC, Li_ptr, lR, blockSet, aTree, cT, rT, col2Sup, lValues, perm_req, swap_full, xi, map, ws, contribs); delete[]contribs; delete[]trn_diag; delete[]xi; delete[]map; delete[]ws; delete[]ipiv; delete[]swap_full; #endif #if 0 //LAst iteration MKL_Domain_Set_Num_Threads(threads, MKL_DOMAIN_BLAS); map = new int[n](); contribs = new double[super_max * col_max](); xi = new int[2 * supNo](); trn_diag = new double[super_max * col_max](); for (int j1 = levelPtr[nLevels - 1]; j1 < levelPtr[nLevels]; ++j1) { #ifdef TLAST start = std::chrono::system_clock::now(); #endif for (int k1 = parPtr[j1]; k1 < parPtr[j1 + 1]; ++k1) { int s = partition[k1] + 1; int curCol = s != 0 ? blockSet[s - 1] : 0; int nxtCol = blockSet[s]; int supWdt = nxtCol - curCol; int nSupR = Li_ptr[nxtCol] - Li_ptr[curCol];//row size of supernode for (int i = Li_ptr[curCol], cnt = 0; i < Li_ptr[nxtCol]; ++i) { map[lR[i]] = cnt++;//mapping L rows position to actual row idx } //copy the columns from A to L for (int i = curCol; i < nxtCol; ++i) {//Copy A to L int pad = i - curCol; for (int j = c[i]; j < c[i + 1]; ++j) { // if(r[j]>=i)//does not need to save upper part. lValues[lC[i] + map[r[j]]] = values[j]; // else // printf("dddd\n"); } } #if DEBUG top = ereach_sn(supNo,c,r,curCol,nxtCol,col2sup, eTree,xi,xi+supNo); if(supNo-top != prunePtr[s]-prunePtr[s-1]) printf("sss"); #endif double *src, *cur = &lValues[lC[curCol]];//pointing to first element of the current supernode //#ifndef PRUNE top = ereach_sn(supNo, cT, rT, curCol, nxtCol, col2Sup, aTree, xi, xi + supNo); assert(top >= 0); //if(s==2){top =2; xi[top] = 0;} for (int i = top; i < supNo; ++i) { int lSN = xi[i]; /*#else for (int i = prunePtr[s - 1]; i < prunePtr[s]; ++i) { int lSN = pruneSet[i]; #endif*/ int nSupRs = 0; #if DEBUG if(xi[top++] != lSN) printf("fail"); #endif int cSN = blockSet[lSN];//first col of current SN int cNSN = blockSet[lSN + 1];//first col of Next SN int Li_ptr_cNSN = Li_ptr[cNSN]; int Li_ptr_cSN = Li_ptr[cSN]; int nSNRCur = Li_ptr_cNSN - Li_ptr_cSN; int supWdts = cNSN - cSN;//The width of current src SN int lb = 0, ub = 0; bool sw = true; int beg_col = cSN, end_col = 0; for (int j = Li_ptr_cSN; j < Li_ptr_cNSN; ++j) { //finding the overlap between curCol and curCol+supWdt in the src col if (lR[j] >= curCol && sw) { //src*transpose(row lR[j]) lb = j - Li_ptr_cSN; sw = false; } if (lR[j] < curCol + supWdt && !sw) { ub = j - Li_ptr_cSN; } } nSupRs = Li_ptr_cNSN - Li_ptr_cSN - lb; int ndrow1 = ub - lb + 1; int ndrow3 = nSupRs - ndrow1; src = &lValues[lC[cSN] + lb];//first element of src supernode starting from row lb double *srcL = &lValues[lC[cSN] + ub + 1]; // multiplying L * D for (int l = 0; l < supWdts; ++l) { double tmp = D[cSN + l]; /* double *dst_tmp = &rn_diag[l * nSupRs]; double *src_tmp = &src[l * nSNRCur]; dscal(nSupRs, )*/ for (int l1 = 0; l1 < nSupRs; ++l1) { trn_diag[l * nSupRs + l1] = tmp * src[l * nSNRCur + l1]; } } /*dgemm("N", "C", &ndrow3, &ndrow1, &supWdts, one, srcL, &nSNRCur, src, &nSNRCur, zero, &contribs[ndrow1], &nSupRs);*/ dgemm("N", "C", &nSupRs, &ndrow1, &supWdts, one, trn_diag, &nSupRs, src, &nSNRCur, zero, contribs, &nSupRs); //copying contrib to L for (int i = 0; i < ndrow1; ++i) {//Copy contribs to L int col = map[lR[Li_ptr_cSN + i + lb]];//col in the SN //double ddiag = 1.0 ;/// D[col]; for (int j = i; j < nSupRs; ++j) { int cRow = lR[Li_ptr_cSN + j + lb];//corresponding row in SN //lValues[lC[curCol+col]+ map[cRow]] -= contribs[i*nSupRs+j]; cur[col * nSupR + map[cRow]] -= contribs[i * nSupRs + j]; } } } #ifdef MKL //dpotrf("L",&supWdt,cur,&nSupR,&info); /* for (int m = 0; m < supWdt; ++m) { for (int i = m; i < supWdt; ++i) { contribs[m*su] } } dspff*/ start = std::chrono::system_clock::now(); sym_sytrf(cur, supWdt, nSupR, &nbpivot, threshold); //LAPACKE_dsytrf(LAPACK_COL_MAJOR,'L',supWdt,cur,nSupR,ipiv); //dsytrf("L",) #endif // Making L*D int rowNo = nSupR - supWdt; for (int l = 0; l < supWdt; ++l) { double tmp = cur[l + l * nSupR]; D[curCol + l] = tmp; double *stCol = trn_diag + l * supWdt + l; double *curCol = cur + l * nSupR + l; *stCol = tmp; for (int l1 = 0; l1 < supWdt - l - 1; ++l1) { *(++stCol) = tmp * *(++curCol); } } dtrsm("R", "L", "C", "N", &rowNo, &supWdt, one, trn_diag, &supWdt, &cur[supWdt], &nSupR); for (int k = 0; k < supWdt; ++k) { cur[k * nSupR + k] = 1.0; } //copying 1/Di into D /*for (int l = 0; l < supWdt; ++l) { D[curCol+l] = one[0] / cur[l + l*nSupR]; }*/ /* for (int k = 0; k < nSupR * supWdt; ++k) { std::cout<<cur[k]<<","; } std::cout<<"==== \n";*/ } #ifdef TLAST end = std::chrono::system_clock::now(); elapsed_seconds = end-start; duration1=elapsed_seconds.count(); std::cout<<"++ " <<duration1<<"\n"; #endif } #endif return true; } } #endif //PROJECT_SERIAL_BLOCKED_LDL_03_H
arrays.c
/** * module with tools for manipulating arrays * Julien Lesgourgues, 18.04.2010 */ #include "arrays.h" /** * Called by thermodynamics_init(); perturb_sources(). */ int array_derive( double * array, int n_columns, int n_lines, int index_x, /** from 0 to (n_columns-1) */ int index_y, int index_dydx, ErrorMsg errmsg) { int i; double dx1,dx2,dy1,dy2,weight1,weight2; class_test((index_dydx == index_x) || (index_dydx == index_y), errmsg, "output column %d must differ from input columns %d and %d",index_dydx,index_x,index_y); dx2=array[1*n_columns+index_x]-array[0*n_columns+index_x]; dy2=array[1*n_columns+index_y]-array[0*n_columns+index_y]; for (i=1; i<n_lines-1; i++) { dx1 = dx2; dy1 = dy2; dx2 = array[(i+1)*n_columns+index_x]-array[i*n_columns+index_x]; dy2 = array[(i+1)*n_columns+index_y]-array[i*n_columns+index_y]; class_test((dx1 == 0) || (dx2 == 0), errmsg, "stop to avoid division by zero"); weight1 = dx2*dx2; weight2 = dx1*dx1; array[i*n_columns+index_dydx] = (weight1*dy1+weight2*dy2) / (weight1*dx1+weight2*dx2); if (i == 1) array[(i-1)*n_columns+index_dydx] = 2.*dy1/dx1 - array[i*n_columns+index_dydx]; if (i == n_lines-2) array[(i+1)*n_columns+index_dydx] = 2.*dy2/dx2 - array[i*n_columns+index_dydx]; } return _SUCCESS_; } int array_derive_spline( double * x_array, int n_lines, double * array, double * array_splined, int n_columns, int index_y, int index_dydx, ErrorMsg errmsg) { int i; double h; class_test(index_dydx == index_y, errmsg, "Output column %d must differ from input columns %d", index_dydx, index_y); class_test(n_lines<2, errmsg, "no possible derivation with less than two lines"); for (i=0; i<n_lines-1; i++) { h = x_array[i+1] - x_array[i]; if (h == 0) { sprintf(errmsg,"%s(L:%d) h=0, stop to avoid division by zero",__func__,__LINE__); return _FAILURE_; } array[i*n_columns+index_dydx] = (array[(i+1)*n_columns+index_y] - array[i*n_columns+index_y])/h - h / 6. * (array_splined[(i+1)*n_columns+index_y] + 2. * array_splined[i*n_columns+index_y]); } h = x_array[n_lines-1] - x_array[n_lines-2]; array[(n_lines-1)*n_columns+index_dydx] = (array[(n_lines-1)*n_columns+index_y] - array[(n_lines-2)*n_columns+index_y])/h + h / 6. * (2. * array_splined[(n_lines-1)*n_columns+index_y] + array_splined[(n_lines-2)*n_columns+index_y]); return _SUCCESS_; } int array_derive_spline_table_line_to_line( double * x_array, int n_lines, double * array, int n_columns, int index_y, int index_ddy, int index_dy, ErrorMsg errmsg) { int i; double h; class_test(index_ddy == index_y, errmsg, "Output column %d must differ from input columns %d", index_ddy, index_y); class_test(index_ddy == index_dy, errmsg, "Output column %d must differ from input columns %d", index_ddy, index_dy); class_test(n_lines<2, errmsg, "no possible derivation with less than two lines"); for (i=0; i<n_lines-1; i++) { h = x_array[i+1] - x_array[i]; if (h == 0) { sprintf(errmsg,"%s(L:%d) h=0, stop to avoid division by zero",__func__,__LINE__); return _FAILURE_; } array[i*n_columns+index_dy] = (array[(i+1)*n_columns+index_y] - array[i*n_columns+index_y])/h - h / 6. * (array[(i+1)*n_columns+index_ddy] + 2. * array[i*n_columns+index_ddy]); } h = x_array[n_lines-1] - x_array[n_lines-2]; array[(n_lines-1)*n_columns+index_dy] = (array[(n_lines-1)*n_columns+index_y] - array[(n_lines-2)*n_columns+index_y])/h + h / 6. * (2. * array[(n_lines-1)*n_columns+index_ddy] + array[(n_lines-2)*n_columns+index_ddy]); return _SUCCESS_; } int array_derive1_order2_table_line_to_line( double * x_array, int n_lines, double * array, int n_columns, int index_y, int index_dy, ErrorMsg errmsg) { int i=1; double dxp,dxm,dyp,dym; if (n_lines < 2) { sprintf(errmsg,"%s(L:%d) routine called with n_lines=%d, should be at least 2",__func__,__LINE__,n_lines); return _FAILURE_; } dxp = x_array[2] - x_array[1]; dxm = x_array[0] - x_array[1]; dyp = *(array+2*n_columns+index_y) - *(array+1*n_columns+index_y); dym = *(array+0*n_columns+index_y) - *(array+1*n_columns+index_y); if ((dxp*dxm*(dxm-dxp)) == 0.) { sprintf(errmsg,"%s(L:%d) stop to avoid division by zero",__func__,__LINE__); return _FAILURE_; } *(array+1*n_columns+index_dy) = (dyp*dxm*dxm-dym*dxp*dxp)/(dxp*dxm*(dxm-dxp)); *(array+0*n_columns+index_dy) = *(array+1*n_columns+index_dy) - (x_array[1] - x_array[0]) * 2.*(dyp*dxm-dym*dxp)/(dxp*dxm*(dxp-dxm)); for (i=2; i<n_lines-1; i++) { dxp = x_array[i+1] - x_array[i]; dxm = x_array[i-1] - x_array[i]; dyp = *(array+(i+1)*n_columns+index_y) - *(array+i*n_columns+index_y); dym = *(array+(i-1)*n_columns+index_y) - *(array+i*n_columns+index_y); if ((dxp*dxm*(dxm-dxp)) == 0.) { sprintf(errmsg,"%s(L:%d) stop to avoid division by zero",__func__,__LINE__); return _FAILURE_; } *(array+i*n_columns+index_dy) = (dyp*dxm*dxm-dym*dxp*dxp)/(dxp*dxm*(dxm-dxp)); } *(array+(n_lines-1)*n_columns+index_dy) = *(array+(n_lines-2)*n_columns+index_dy) + (x_array[n_lines-1] - x_array[n_lines-2]) * 2.*(dyp*dxm-dym*dxp)/(dxp*dxm*(dxp-dxm)); return _SUCCESS_; } int array_derive2_order2_table_line_to_line( double * x_array, int n_lines, double * array, int n_columns, int index_y, int index_dy, int index_ddy, ErrorMsg errmsg) { int i; double dxp,dxm,dyp,dym; for (i=1; i<n_lines-1; i++) { dxp = x_array[i+1] - x_array[i]; dxm = x_array[i-1] - x_array[i]; dyp = *(array+(i+1)*n_columns+index_y) - *(array+i*n_columns+index_y); dym = *(array+(i-1)*n_columns+index_y) - *(array+i*n_columns+index_y); if ((dxp*dxm*(dxm-dxp)) == 0.) { sprintf(errmsg,"%s(L:%d) stop to avoid division by zero",__func__,__LINE__); return _FAILURE_; } *(array+i*n_columns+index_dy) = (dyp*dxm*dxm-dym*dxp*dxp)/(dxp*dxm*(dxm-dxp)); *(array+i*n_columns+index_ddy) = 2.*(dyp*dxm-dym*dxp)/(dxp*dxm*(dxp-dxm)); } *(array+0*n_columns+index_dy) = *(array+1*n_columns+index_dy) - (x_array[1] - x_array[0]) * *(array+1*n_columns+index_ddy); *(array+0*n_columns+index_ddy) = *(array+1*n_columns+index_ddy); *(array+(n_lines-1)*n_columns+index_dy) = *(array+(n_lines-2)*n_columns+index_dy) + (x_array[n_lines-1] - x_array[n_lines-2]) * *(array+(n_lines-2)*n_columns+index_ddy); *(array+(n_lines-1)*n_columns+index_ddy) = *(array+(n_lines-2)*n_columns+index_ddy); return _SUCCESS_; } int array_integrate_spline_table_line_to_line( double * x_array, int n_lines, double * array, int n_columns, int index_y, int index_ddy, int index_inty, ErrorMsg errmsg) { int i; double h; *(array+0*n_columns+index_inty) = 0.; for (i=0; i < n_lines-1; i++) { h = (x_array[i+1]-x_array[i]); *(array+(i+1)*n_columns+index_inty) = *(array+i*n_columns+index_inty) + (array[i*n_columns+index_y]+array[(i+1)*n_columns+index_y])*h/2.+ (array[i*n_columns+index_ddy]+array[(i+1)*n_columns+index_ddy])*h*h*h/24.; } return _SUCCESS_; } /** * Not called. */ int array_derive_two( double * array, int n_columns, int n_lines, int index_x, /** from 0 to (n_columns-1) */ int index_y, int index_dydx, int index_ddydxdx, ErrorMsg errmsg) { int i; double dx1,dx2,dy1,dy2,weight1,weight2; if ((index_dydx == index_x) || (index_dydx == index_y)) { sprintf(errmsg,"%s(L:%d) : Output column %d must differ from input columns %d and %d",__func__,__LINE__,index_dydx,index_x,index_y); return _FAILURE_; } dx2=*(array+1*n_columns+index_x)-*(array+0*n_columns+index_x); dy2=*(array+1*n_columns+index_y)-*(array+0*n_columns+index_y); for (i=1; i<n_lines-1; i++) { dx1 = dx2; dy1 = dy2; dx2 = *(array+(i+1)*n_columns+index_x)-*(array+i*n_columns+index_x); dy2 = *(array+(i+1)*n_columns+index_y)-*(array+i*n_columns+index_y); weight1 = dx2*dx2; weight2 = dx1*dx1; if ((dx1 == 0.) && (dx2 == 0.)) { sprintf(errmsg,"%s(L:%d) stop to avoid division by zero",__func__,__LINE__); return _FAILURE_; } *(array+i*n_columns+index_dydx) = (weight1*dy1+weight2*dy2) / (weight1*dx1+weight2*dx2); *(array+i*n_columns+index_ddydxdx) = (dx2*dy1-dx1*dy2) / (weight1*dx1+weight2*dx2); if (i == 1) { *(array+(i-1)*n_columns+index_dydx) = 2.*dy1/dx1 - *(array+i*n_columns+index_dydx); *(array+(i-1)*n_columns+index_ddydxdx) = *(array+i*n_columns+index_ddydxdx); } if (i == n_lines-2) { *(array+(i+1)*n_columns+index_dydx) = 2.*dy2/dx2 - *(array+i*n_columns+index_dydx); *(array+(i+1)*n_columns+index_dydx) = *(array+i*n_columns+index_ddydxdx); } } return _SUCCESS_; } int array_spline( double * array, int n_columns, int n_lines, int index_x, /** from 0 to (n_columns-1) */ int index_y, int index_ddydx2, short spline_mode, ErrorMsg errmsg) { int i,k; double p,qn,sig,un; double * u; double dy_first; double dy_last; if (n_lines < 3) { sprintf(errmsg,"%s(L:%d) n_lines=%d, while routine needs n_lines >= 3",__func__,__LINE__,n_lines); return _FAILURE_; } u = malloc((n_lines-1) * sizeof(double)); if (u == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate u",__func__,__LINE__); return _FAILURE_; } if (spline_mode == _SPLINE_NATURAL_) { *(array+0*n_columns+index_ddydx2) = u[0] = 0.0; } else { if (spline_mode == _SPLINE_EST_DERIV_) { dy_first = ((*(array+2*n_columns+index_x)-*(array+0*n_columns+index_x))* (*(array+2*n_columns+index_x)-*(array+0*n_columns+index_x))* (*(array+1*n_columns+index_y)-*(array+0*n_columns+index_y))- (*(array+1*n_columns+index_x)-*(array+0*n_columns+index_x))* (*(array+1*n_columns+index_x)-*(array+0*n_columns+index_x))* (*(array+2*n_columns+index_y)-*(array+0*n_columns+index_y)))/ ((*(array+2*n_columns+index_x)-*(array+0*n_columns+index_x))* (*(array+1*n_columns+index_x)-*(array+0*n_columns+index_x))* (*(array+2*n_columns+index_x)-*(array+1*n_columns+index_x))); *(array+0*n_columns+index_ddydx2) = -0.5; u[0] = (3./(*(array+1*n_columns+index_x) - *(array+0*n_columns+index_x)))* ((*(array+1*n_columns+index_y) - *(array+0*n_columns+index_y))/ (*(array+1*n_columns+index_x) - *(array+0*n_columns+index_x)) -dy_first); } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } for (i=1; i < n_lines-1; i++) { sig = (*(array+i*n_columns+index_x) - *(array+(i-1)*n_columns+index_x)) / (*(array+(i+1)*n_columns+index_x) - *(array+(i-1)*n_columns+index_x)); p = sig * *(array+(i-1)*n_columns+index_ddydx2) + 2.0; *(array+i*n_columns+index_ddydx2) = (sig-1.0)/p; u[i] = (*(array+(i+1)*n_columns+index_y) - *(array+i*n_columns+index_y)) / (*(array+(i+1)*n_columns+index_x) - *(array+i*n_columns+index_x)) - (*(array+i*n_columns+index_y) - *(array+(i-1)*n_columns+index_y)) / (*(array+i*n_columns+index_x) - *(array+(i-1)*n_columns+index_x)); u[i]= (6.0 * u[i] / (*(array+(i+1)*n_columns+index_x) - *(array+(i-1)*n_columns+index_x)) - sig * u[i-1]) / p; } if (spline_mode == _SPLINE_NATURAL_) { qn=0.; un=0.; } else { if (spline_mode == _SPLINE_EST_DERIV_) { dy_last = ((*(array+(n_lines-3)*n_columns+index_x)-*(array+(n_lines-1)*n_columns+index_x))* (*(array+(n_lines-3)*n_columns+index_x)-*(array+(n_lines-1)*n_columns+index_x))* (*(array+(n_lines-2)*n_columns+index_y)-*(array+(n_lines-1)*n_columns+index_y))- (*(array+(n_lines-2)*n_columns+index_x)-*(array+(n_lines-1)*n_columns+index_x))* (*(array+(n_lines-2)*n_columns+index_x)-*(array+(n_lines-1)*n_columns+index_x))* (*(array+(n_lines-3)*n_columns+index_y)-*(array+(n_lines-1)*n_columns+index_y)))/ ((*(array+(n_lines-3)*n_columns+index_x)-*(array+(n_lines-1)*n_columns+index_x))* (*(array+(n_lines-2)*n_columns+index_x)-*(array+(n_lines-1)*n_columns+index_x))* (*(array+(n_lines-3)*n_columns+index_x)-*(array+(n_lines-2)*n_columns+index_x))); qn=0.5; un = (3./(*(array+(n_lines-1)*n_columns+index_x) - *(array+(n_lines-2)*n_columns+index_x)))* (dy_last-(*(array+(n_lines-1)*n_columns+index_y) - *(array+(n_lines-2)*n_columns+index_y))/ (*(array+(n_lines-1)*n_columns+index_x) - *(array+(n_lines-2)*n_columns+index_x))); } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } *(array+(n_lines-1)*n_columns+index_ddydx2) = (un-qn*u[n_lines-2])/(qn* *(array+(n_lines-2)*n_columns+index_ddydx2)+1.0); for (k=n_lines-2; k>=0; k--) *(array+k*n_columns+index_ddydx2) = *(array+k*n_columns+index_ddydx2) * *(array+(k+1)*n_columns+index_ddydx2) + u[k]; free(u); return _SUCCESS_; } int array_spline_table_line_to_line( double * x, /* vector of size x_size */ int n_lines, double * array, int n_columns, int index_y, int index_ddydx2, short spline_mode, ErrorMsg errmsg) { int i,k; double p,qn,sig,un; double * u; double dy_first; double dy_last; u = malloc((n_lines-1) * sizeof(double)); if (u == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate u",__func__,__LINE__); return _FAILURE_; } if (spline_mode == _SPLINE_NATURAL_) { *(array+0*n_columns+index_ddydx2) = u[0] = 0.0; } else { if (spline_mode == _SPLINE_EST_DERIV_) { dy_first = ((x[2]-x[0])*(x[2]-x[0])* (*(array+1*n_columns+index_y)-*(array+0*n_columns+index_y))- (x[1]-x[0])*(x[1]-x[0])* (*(array+2*n_columns+index_y)-*(array+0*n_columns+index_y)))/ ((x[2]-x[0])*(x[1]-x[0])*(x[2]-x[1])); *(array+0*n_columns+index_ddydx2) = -0.5; u[0] = (3./(x[1] - x[0]))* ((*(array+1*n_columns+index_y) - *(array+0*n_columns+index_y))/ (x[1] - x[0])-dy_first); } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } for (i=1; i < n_lines-1; i++) { sig = (x[i] - x[i-1]) / (x[i+1] - x[i-1]); p = sig * *(array+(i-1)*n_columns+index_ddydx2) + 2.0; *(array+i*n_columns+index_ddydx2) = (sig-1.0)/p; u[i] = (*(array+(i+1)*n_columns+index_y) - *(array+i*n_columns+index_y)) / (x[i+1] - x[i]) - (*(array+i*n_columns+index_y) - *(array+(i-1)*n_columns+index_y)) / (x[i] - x[i-1]); u[i]= (6.0 * u[i] / (x[i+1] - x[i-1]) - sig * u[i-1]) / p; } if (spline_mode == _SPLINE_NATURAL_) { qn=0.; un=0.; } else { if (spline_mode == _SPLINE_EST_DERIV_) { dy_last = ((x[n_lines-3]-x[n_lines-1])*(x[n_lines-3]-x[n_lines-1])* (*(array+(n_lines-2)*n_columns+index_y)-*(array+(n_lines-1)*n_columns+index_y))- (x[n_lines-2]-x[n_lines-1])*(x[n_lines-2]-x[n_lines-1])* (*(array+(n_lines-3)*n_columns+index_y)-*(array+(n_lines-1)*n_columns+index_y)))/ ((x[n_lines-3]-x[n_lines-1])*(x[n_lines-2]-x[n_lines-1])*(x[n_lines-3]-x[n_lines-2])); qn=0.5; un = (3./(x[n_lines-1] - x[n_lines-2]))* (dy_last-(*(array+(n_lines-1)*n_columns+index_y) - *(array+(n_lines-2)*n_columns+index_y))/ (x[n_lines-1] - x[n_lines-2])); } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } *(array+(n_lines-1)*n_columns+index_ddydx2) = (un-qn*u[n_lines-2])/(qn* *(array+(n_lines-2)*n_columns+index_ddydx2)+1.0); for (k=n_lines-2; k>=0; k--) *(array+k*n_columns+index_ddydx2) = *(array+k*n_columns+index_ddydx2) * *(array+(k+1)*n_columns+index_ddydx2) + u[k]; free(u); return _SUCCESS_; } int array_spline_table_lines( double * x, /* vector of size x_size */ int x_size, double * y_array, /* array of size x_size*y_size with elements y_array[index_x*y_size+index_y] */ int y_size, double * ddy_array, /* array of size x_size*y_size */ short spline_mode, ErrorMsg errmsg ) { double * p; double * qn; double * un; double * u; double sig; int index_x; int index_y; double dy_first; double dy_last; u = malloc((x_size-1) * y_size * sizeof(double)); p = malloc(y_size * sizeof(double)); qn = malloc(y_size * sizeof(double)); un = malloc(y_size * sizeof(double)); if (u == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate u",__func__,__LINE__); return _FAILURE_; } if (p == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate p",__func__,__LINE__); return _FAILURE_; } if (qn == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate qn",__func__,__LINE__); return _FAILURE_; } if (un == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate un",__func__,__LINE__); return _FAILURE_; } index_x=0; if (spline_mode == _SPLINE_NATURAL_) { for (index_y=0; index_y < y_size; index_y++) { ddy_array[index_x*y_size+index_y] = u[index_x*y_size+index_y] = 0.0; } } else { if (spline_mode == _SPLINE_EST_DERIV_) { for (index_y=0; index_y < y_size; index_y++) { dy_first = ((x[2]-x[0])*(x[2]-x[0])* (y_array[1*y_size+index_y]-y_array[0*y_size+index_y])- (x[1]-x[0])*(x[1]-x[0])* (y_array[2*y_size+index_y]-y_array[0*y_size+index_y]))/ ((x[2]-x[0])*(x[1]-x[0])*(x[2]-x[1])); ddy_array[index_x*y_size+index_y] = -0.5; u[index_x*y_size+index_y] = (3./(x[1] - x[0]))* ((y_array[1*y_size+index_y]-y_array[0*y_size+index_y])/ (x[1] - x[0])-dy_first); } } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } for (index_x=1; index_x < x_size-1; index_x++) { sig = (x[index_x] - x[index_x-1])/(x[index_x+1] - x[index_x-1]); for (index_y=0; index_y < y_size; index_y++) { p[index_y] = sig * ddy_array[(index_x-1)*y_size+index_y] + 2.0; ddy_array[index_x*y_size+index_y] = (sig-1.0)/p[index_y]; u[index_x*y_size+index_y] = (y_array[(index_x+1)*y_size+index_y] - y_array[index_x*y_size+index_y]) / (x[index_x+1] - x[index_x]) - (y_array[index_x*y_size+index_y] - y_array[(index_x-1)*y_size+index_y]) / (x[index_x] - x[index_x-1]); u[index_x*y_size+index_y] = (6.0 * u[index_x*y_size+index_y] / (x[index_x+1] - x[index_x-1]) - sig * u[(index_x-1)*y_size+index_y]) / p[index_y]; } } if (spline_mode == _SPLINE_NATURAL_) { for (index_y=0; index_y < y_size; index_y++) { qn[index_y]=un[index_y]=0.0; } } else { if (spline_mode == _SPLINE_EST_DERIV_) { for (index_y=0; index_y < y_size; index_y++) { dy_last = ((x[x_size-3]-x[x_size-1])*(x[x_size-3]-x[x_size-1])* (y_array[(x_size-2)*y_size+index_y]-y_array[(x_size-1)*y_size+index_y])- (x[x_size-2]-x[x_size-1])*(x[x_size-2]-x[x_size-1])* (y_array[(x_size-3)*y_size+index_y]-y_array[(x_size-1)*y_size+index_y]))/ ((x[x_size-3]-x[x_size-1])*(x[x_size-2]-x[x_size-1])*(x[x_size-3]-x[x_size-2])); qn[index_y]=0.5; un[index_y]= (3./(x[x_size-1] - x[x_size-2]))* (dy_last-(y_array[(x_size-1)*y_size+index_y] - y_array[(x_size-2)*y_size+index_y])/ (x[x_size-1] - x[x_size-2])); } } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } index_x=x_size-1; for (index_y=0; index_y < y_size; index_y++) { ddy_array[index_x*y_size+index_y] = (un[index_y] - qn[index_y] * u[(index_x-1)*y_size+index_y]) / (qn[index_y] * ddy_array[(index_x-1)*y_size+index_y] + 1.0); } for (index_x=x_size-2; index_x >= 0; index_x--) { for (index_y=0; index_y < y_size; index_y++) { ddy_array[index_x*y_size+index_y] = ddy_array[index_x*y_size+index_y] * ddy_array[(index_x+1)*y_size+index_y] + u[index_x*y_size+index_y]; } } free(qn); free(un); free(p); free(u); return _SUCCESS_; } int array_logspline_table_lines( double * x, /* vector of size x_size */ int x_size, double * y_array, /* array of size x_size*y_size with elements y_array[index_x*y_size+index_y] */ int y_size, double * ddlny_array, /* array of size x_size*y_size */ short spline_mode, ErrorMsg errmsg ) { double * p; double * qn; double * un; double * u; double sig; int index_x; int index_y; double dy_first; double dy_last; u = malloc((x_size-1) * y_size * sizeof(double)); p = malloc(y_size * sizeof(double)); qn = malloc(y_size * sizeof(double)); un = malloc(y_size * sizeof(double)); if (u == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate u",__func__,__LINE__); return _FAILURE_; } if (p == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate p",__func__,__LINE__); return _FAILURE_; } if (qn == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate qn",__func__,__LINE__); return _FAILURE_; } if (un == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate un",__func__,__LINE__); return _FAILURE_; } index_x=0; if (spline_mode == _SPLINE_NATURAL_) { for (index_y=0; index_y < y_size; index_y++) { ddlny_array[index_x*y_size+index_y] = u[index_x*y_size+index_y] = 0.0; } } else { if (spline_mode == _SPLINE_EST_DERIV_) { for (index_y=0; index_y < y_size; index_y++) { dy_first = ((log(x[2])-log(x[0]))*(log(x[2])-log(x[0]))* (log(y_array[1*y_size+index_y])-log(y_array[0*y_size+index_y]))- (log(x[1])-log(x[0]))*(log(x[1])-log(x[0]))* (log(y_array[2*y_size+index_y])-log(y_array[0*y_size+index_y])))/ ((log(x[2])-log(x[0]))*(log(x[1])-log(x[0]))*(log(x[2])-log(x[1]))); ddlny_array[index_x*y_size+index_y] = -0.5; u[index_x*y_size+index_y] = (3./(log(x[1]) - log(x[0])))* ((log(y_array[1*y_size+index_y])-log(y_array[0*y_size+index_y]))/ (log(x[1]) - log(x[0]))-dy_first); } } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } for (index_x=1; index_x < x_size-1; index_x++) { sig = (log(x[index_x]) - log(x[index_x-1]))/(log(x[index_x+1]) - log(x[index_x-1])); for (index_y=0; index_y < y_size; index_y++) { p[index_y] = sig * ddlny_array[(index_x-1)*y_size+index_y] + 2.0; ddlny_array[index_x*y_size+index_y] = (sig-1.0)/p[index_y]; u[index_x*y_size+index_y] = (log(y_array[(index_x+1)*y_size+index_y]) - log(y_array[index_x*y_size+index_y])) / (log(x[index_x+1]) - log(x[index_x])) - (log(y_array[index_x*y_size+index_y]) - log(y_array[(index_x-1)*y_size+index_y])) / (log(x[index_x]) - log(x[index_x-1])); u[index_x*y_size+index_y] = (6.0 * u[index_x*y_size+index_y] / (log(x[index_x+1]) - log(x[index_x-1])) - sig * u[(index_x-1)*y_size+index_y]) / p[index_y]; } } if (spline_mode == _SPLINE_NATURAL_) { for (index_y=0; index_y < y_size; index_y++) { qn[index_y]=un[index_y]=0.0; } } else { if (spline_mode == _SPLINE_EST_DERIV_) { for (index_y=0; index_y < y_size; index_y++) { dy_last = ((log(x[x_size-3])-log(x[x_size-1]))*(log(x[x_size-3])-log(x[x_size-1]))* (log(y_array[(x_size-2)*y_size+index_y])-log(y_array[(x_size-1)*y_size+index_y]))- (log(x[x_size-2])-log(x[x_size-1]))*(log(x[x_size-2])-log(x[x_size-1]))* (log(y_array[(x_size-3)*y_size+index_y])-log(y_array[(x_size-1)*y_size+index_y])))/ ((log(x[x_size-3])-log(x[x_size-1]))*(log(x[x_size-2])-log(x[x_size-1]))*(log(x[x_size-3])-log(x[x_size-2]))); qn[index_y]=0.5; un[index_y]= (3./(log(x[x_size-1]) - log(x[x_size-2])))* (dy_last-(log(y_array[(x_size-1)*y_size+index_y]) - log(y_array[(x_size-2)*y_size+index_y]))/ (log(x[x_size-1]) - log(x[x_size-2]))); } } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } index_x=x_size-1; for (index_y=0; index_y < y_size; index_y++) { ddlny_array[index_x*y_size+index_y] = (un[index_y] - qn[index_y] * u[(index_x-1)*y_size+index_y]) / (qn[index_y] * ddlny_array[(index_x-1)*y_size+index_y] + 1.0); } for (index_x=x_size-2; index_x >= 0; index_x--) { for (index_y=0; index_y < y_size; index_y++) { ddlny_array[index_x*y_size+index_y] = ddlny_array[index_x*y_size+index_y] * ddlny_array[(index_x+1)*y_size+index_y] + u[index_x*y_size+index_y]; } } free(qn); free(un); free(p); free(u); return _SUCCESS_; } int array_spline_table_columns( double * x, /* vector of size x_size */ int x_size, double * y_array, /* array of size x_size*y_size with elements y_array[index_y*x_size+index_x] */ int y_size, double * ddy_array, /* array of size x_size*y_size */ short spline_mode, ErrorMsg errmsg ) { double * p; double * qn; double * un; double * u; double sig; int index_x; int index_y; double dy_first; double dy_last; u = malloc((x_size-1) * y_size * sizeof(double)); p = malloc(y_size * sizeof(double)); qn = malloc(y_size * sizeof(double)); un = malloc(y_size * sizeof(double)); if (u == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate u",__func__,__LINE__); return _FAILURE_; } if (p == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate p",__func__,__LINE__); return _FAILURE_; } if (qn == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate qn",__func__,__LINE__); return _FAILURE_; } if (un == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate un",__func__,__LINE__); return _FAILURE_; } index_x=0; if (spline_mode == _SPLINE_NATURAL_) { for (index_y=0; index_y < y_size; index_y++) { ddy_array[index_y*x_size+index_x] = 0.0; u[index_x*y_size+index_y] = 0.0; } } else { if (spline_mode == _SPLINE_EST_DERIV_) { class_test(x[2]-x[0]==0., errmsg, "x[2]=%g, x[0]=%g, stop to avoid seg fault",x[2],x[0]); class_test(x[1]-x[0]==0., errmsg, "x[1]=%g, x[0]=%g, stop to avoid seg fault",x[1],x[0]); class_test(x[2]-x[1]==0., errmsg, "x[2]=%g, x[1]=%g, stop to avoid seg fault",x[2],x[1]); for (index_y=0; index_y < y_size; index_y++) { dy_first = ((x[2]-x[0])*(x[2]-x[0])* (y_array[index_y*x_size+1]-y_array[index_y*x_size+0])- (x[1]-x[0])*(x[1]-x[0])* (y_array[index_y*x_size+2]-y_array[index_y*x_size+0]))/ ((x[2]-x[0])*(x[1]-x[0])*(x[2]-x[1])); ddy_array[index_y*x_size+index_x] = -0.5; u[index_x*y_size+index_y] = (3./(x[1] - x[0]))* ((y_array[index_y*x_size+1]-y_array[index_y*x_size+0])/ (x[1] - x[0])-dy_first); } } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } for (index_x=1; index_x < x_size-1; index_x++) { sig = (x[index_x] - x[index_x-1])/(x[index_x+1] - x[index_x-1]); for (index_y=0; index_y < y_size; index_y++) { p[index_y] = sig * ddy_array[index_y*x_size+(index_x-1)] + 2.0; ddy_array[index_y*x_size+index_x] = (sig-1.0)/p[index_y]; u[index_x*y_size+index_y] = (y_array[index_y*x_size+(index_x+1)] - y_array[index_y*x_size+index_x]) / (x[index_x+1] - x[index_x]) - (y_array[index_y*x_size+index_x] - y_array[index_y*x_size+(index_x-1)]) / (x[index_x] - x[index_x-1]); u[index_x*y_size+index_y] = (6.0 * u[index_x*y_size+index_y] / (x[index_x+1] - x[index_x-1]) - sig * u[(index_x-1)*y_size+index_y]) / p[index_y]; } } if (spline_mode == _SPLINE_NATURAL_) { for (index_y=0; index_y < y_size; index_y++) { qn[index_y]=un[index_y]=0.0; } } else { if (spline_mode == _SPLINE_EST_DERIV_) { for (index_y=0; index_y < y_size; index_y++) { dy_last = ((x[x_size-3]-x[x_size-1])*(x[x_size-3]-x[x_size-1])* (y_array[index_y*x_size+(x_size-2)]-y_array[index_y*x_size+(x_size-1)])- (x[x_size-2]-x[x_size-1])*(x[x_size-2]-x[x_size-1])* (y_array[index_y*x_size+(x_size-3)]-y_array[index_y*x_size+(x_size-1)]))/ ((x[x_size-3]-x[x_size-1])*(x[x_size-2]-x[x_size-1])*(x[x_size-3]-x[x_size-2])); qn[index_y]=0.5; un[index_y]= (3./(x[x_size-1] - x[x_size-2]))* (dy_last-(y_array[index_y*x_size+(x_size-1)] - y_array[index_y*x_size+(x_size-2)])/ (x[x_size-1] - x[x_size-2])); } } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } index_x=x_size-1; for (index_y=0; index_y < y_size; index_y++) { ddy_array[index_y*x_size+index_x] = (un[index_y] - qn[index_y] * u[(index_x-1)*y_size+index_y]) / (qn[index_y] * ddy_array[index_y*x_size+(index_x-1)] + 1.0); } for (index_x=x_size-2; index_x >= 0; index_x--) { for (index_y=0; index_y < y_size; index_y++) { ddy_array[index_y*x_size+index_x] = ddy_array[index_y*x_size+index_x] * ddy_array[index_y*x_size+(index_x+1)] + u[index_x*y_size+index_y]; } } free(qn); free(p); free(u); free(un); return _SUCCESS_; } int array_spline_table_columns2( double * x, /* vector of size x_size */ int x_size, double * y_array, /* array of size x_size*y_size with elements y_array[index_y*x_size+index_x] */ int y_size, double * ddy_array, /* array of size x_size*y_size */ short spline_mode, ErrorMsg errmsg ) { double * p; double * qn; double * un; double * u; double sig; int index_x; int index_y; double dy_first; double dy_last; u = malloc((x_size-1) * y_size * sizeof(double)); p = malloc(y_size * sizeof(double)); qn = malloc(y_size * sizeof(double)); un = malloc(y_size * sizeof(double)); if (u == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate u",__func__,__LINE__); return _FAILURE_; } if (p == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate p",__func__,__LINE__); return _FAILURE_; } if (qn == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate qn",__func__,__LINE__); return _FAILURE_; } if (un == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate un",__func__,__LINE__); return _FAILURE_; } #pragma omp parallel \ shared(x,x_size,y_array,y_size,ddy_array,spline_mode,p,qn,un,u) \ private(index_y,index_x,sig,dy_first,dy_last) { #pragma omp for schedule (dynamic) for (index_y=0; index_y < y_size; index_y++) { if (spline_mode == _SPLINE_NATURAL_) { ddy_array[index_y*x_size+0] = 0.0; u[0*y_size+index_y] = 0.0; } else { dy_first = ((x[2]-x[0])*(x[2]-x[0])* (y_array[index_y*x_size+1]-y_array[index_y*x_size+0])- (x[1]-x[0])*(x[1]-x[0])* (y_array[index_y*x_size+2]-y_array[index_y*x_size+0]))/ ((x[2]-x[0])*(x[1]-x[0])*(x[2]-x[1])); ddy_array[index_y*x_size+0] = -0.5; u[0*y_size+index_y] = (3./(x[1] - x[0]))* ((y_array[index_y*x_size+1]-y_array[index_y*x_size+0])/ (x[1] - x[0])-dy_first); } for (index_x=1; index_x < x_size-1; index_x++) { sig = (x[index_x] - x[index_x-1])/(x[index_x+1] - x[index_x-1]); p[index_y] = sig * ddy_array[index_y*x_size+(index_x-1)] + 2.0; ddy_array[index_y*x_size+index_x] = (sig-1.0)/p[index_y]; u[index_x*y_size+index_y] = (y_array[index_y*x_size+(index_x+1)] - y_array[index_y*x_size+index_x]) / (x[index_x+1] - x[index_x]) - (y_array[index_y*x_size+index_x] - y_array[index_y*x_size+(index_x-1)]) / (x[index_x] - x[index_x-1]); u[index_x*y_size+index_y] = (6.0 * u[index_x*y_size+index_y] / (x[index_x+1] - x[index_x-1]) - sig * u[(index_x-1)*y_size+index_y]) / p[index_y]; } if (spline_mode == _SPLINE_NATURAL_) { qn[index_y]=un[index_y]=0.0; } else { dy_last = ((x[x_size-3]-x[x_size-1])*(x[x_size-3]-x[x_size-1])* (y_array[index_y*x_size+(x_size-2)]-y_array[index_y*x_size+(x_size-1)])- (x[x_size-2]-x[x_size-1])*(x[x_size-2]-x[x_size-1])* (y_array[index_y*x_size+(x_size-3)]-y_array[index_y*x_size+(x_size-1)]))/ ((x[x_size-3]-x[x_size-1])*(x[x_size-2]-x[x_size-1])*(x[x_size-3]-x[x_size-2])); qn[index_y]=0.5; un[index_y]= (3./(x[x_size-1] - x[x_size-2]))* (dy_last-(y_array[index_y*x_size+(x_size-1)] - y_array[index_y*x_size+(x_size-2)])/ (x[x_size-1] - x[x_size-2])); } index_x=x_size-1; ddy_array[index_y*x_size+index_x] = (un[index_y] - qn[index_y] * u[(index_x-1)*y_size+index_y]) / (qn[index_y] * ddy_array[index_y*x_size+(index_x-1)] + 1.0); for (index_x=x_size-2; index_x >= 0; index_x--) { ddy_array[index_y*x_size+index_x] = ddy_array[index_y*x_size+index_x] * ddy_array[index_y*x_size+(index_x+1)] + u[index_x*y_size+index_y]; } } } free(qn); free(p); free(u); free(un); return _SUCCESS_; } int array_spline_table_one_column( double * x, /* vector of size x_size */ int x_size, double * y_array, /* array of size x_size*y_size with elements y_array[index_y*x_size+index_x] */ int y_size, int index_y, double * ddy_array, /* array of size x_size*y_size */ short spline_mode, ErrorMsg errmsg ) { double p; double qn; double un; double * u; double sig; int index_x; double dy_first; double dy_last; u = malloc((x_size-1) * sizeof(double)); if (u == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate u",__func__,__LINE__); return _FAILURE_; } /************************************************/ index_x=0; if (spline_mode == _SPLINE_NATURAL_) { ddy_array[index_y*x_size+index_x] = 0.0; u[index_x] = 0.0; } else { if (spline_mode == _SPLINE_EST_DERIV_) { dy_first = ((x[2]-x[0])*(x[2]-x[0])* (y_array[index_y*x_size+1]-y_array[index_y*x_size+0])- (x[1]-x[0])*(x[1]-x[0])* (y_array[index_y*x_size+2]-y_array[index_y*x_size+0]))/ ((x[2]-x[0])*(x[1]-x[0])*(x[2]-x[1])); ddy_array[index_y*x_size+index_x] = -0.5; u[index_x] = (3./(x[1] - x[0]))* ((y_array[index_y*x_size+1]-y_array[index_y*x_size+0])/ (x[1] - x[0])-dy_first); } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } /************************************************/ for (index_x=1; index_x < x_size-1; index_x++) { sig = (x[index_x] - x[index_x-1])/(x[index_x+1] - x[index_x-1]); p = sig * ddy_array[index_y*x_size+(index_x-1)] + 2.0; ddy_array[index_y*x_size+index_x] = (sig-1.0)/p; u[index_x] = (y_array[index_y*x_size+(index_x+1)] - y_array[index_y*x_size+index_x]) / (x[index_x+1] - x[index_x]) - (y_array[index_y*x_size+index_x] - y_array[index_y*x_size+(index_x-1)]) / (x[index_x] - x[index_x-1]); u[index_x] = (6.0 * u[index_x] / (x[index_x+1] - x[index_x-1]) - sig * u[index_x-1]) / p; } /************************************************/ if (spline_mode == _SPLINE_NATURAL_) { qn=un=0.0; } else { if (spline_mode == _SPLINE_EST_DERIV_) { dy_last = ((x[x_size-3]-x[x_size-1])*(x[x_size-3]-x[x_size-1])* (y_array[index_y*x_size+(x_size-2)]-y_array[index_y*x_size+(x_size-1)])- (x[x_size-2]-x[x_size-1])*(x[x_size-2]-x[x_size-1])* (y_array[index_y*x_size+(x_size-3)]-y_array[index_y*x_size+(x_size-1)]))/ ((x[x_size-3]-x[x_size-1])*(x[x_size-2]-x[x_size-1])*(x[x_size-3]-x[x_size-2])); qn=0.5; un= (3./(x[x_size-1] - x[x_size-2]))* (dy_last-(y_array[index_y*x_size+(x_size-1)] - y_array[index_y*x_size+(x_size-2)])/ (x[x_size-1] - x[x_size-2])); } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } /************************************************/ index_x=x_size-1; ddy_array[index_y*x_size+index_x] = (un - qn * u[index_x-1]) / (qn * ddy_array[index_y*x_size+(index_x-1)] + 1.0); for (index_x=x_size-2; index_x >= 0; index_x--) { ddy_array[index_y*x_size+index_x] = ddy_array[index_y*x_size+index_x] * ddy_array[index_y*x_size+(index_x+1)] + u[index_x]; } free(u); return _SUCCESS_; } int array_logspline_table_one_column( double * x, /* vector of size x_size */ int x_size, int x_stop, double * y_array, /* array of size x_size*y_size with elements y_array[index_y*x_size+index_x] */ int y_size, int index_y, double * ddlogy_array, /* array of size x_size*y_size */ short spline_mode, ErrorMsg errmsg ) { double p; double qn; double un; double * u; double sig; int index_x; double dy_first; double dy_last; u = malloc((x_stop-1) * sizeof(double)); if (u == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate u",__func__,__LINE__); return _FAILURE_; } /************************************************/ index_x=0; if (spline_mode == _SPLINE_NATURAL_) { ddlogy_array[index_y*x_size+index_x] = 0.0; u[index_x] = 0.0; } else { if (spline_mode == _SPLINE_EST_DERIV_) { dy_first = ((log(x[2])-log(x[0]))*(log(x[2])-log(x[0]))* (log(y_array[index_y*x_size+1])-log(y_array[index_y*x_size+0]))- (log(x[1])-log(x[0]))*(log(x[1])-log(x[0]))* (log(y_array[index_y*x_size+2])-log(y_array[index_y*x_size+0])))/ ((log(x[2])-log(x[0]))*(log(x[1])-log(x[0]))*(log(x[2])-log(x[1]))); ddlogy_array[index_y*x_size+index_x] = -0.5; u[index_x] = (3./(log(x[1]) - log(x[0])))* ((log(y_array[index_y*x_size+1])-log(y_array[index_y*x_size+0]))/ (log(x[1]) - log(x[0]))-dy_first); } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } /************************************************/ for (index_x=1; index_x < x_stop-1; index_x++) { sig = (log(x[index_x]) - log(x[index_x-1]))/(log(x[index_x+1]) - log(x[index_x-1])); p = sig * ddlogy_array[index_y*x_size+(index_x-1)] + 2.0; ddlogy_array[index_y*x_size+index_x] = (sig-1.0)/p; u[index_x] = (log(y_array[index_y*x_size+(index_x+1)]) - log(y_array[index_y*x_size+index_x])) / (log(x[index_x+1]) - log(x[index_x])) - (log(y_array[index_y*x_size+index_x]) - log(y_array[index_y*x_size+(index_x-1)])) / (log(x[index_x]) - log(x[index_x-1])); u[index_x] = (6.0 * u[index_x] / (log(x[index_x+1]) - log(x[index_x-1])) - sig * u[index_x-1]) / p; } /************************************************/ if (spline_mode == _SPLINE_NATURAL_) { qn=un=0.0; } else { if (spline_mode == _SPLINE_EST_DERIV_) { dy_last = ((log(x[x_stop-3])-log(x[x_stop-1]))*(log(x[x_stop-3])-log(x[x_stop-1]))* (log(y_array[index_y*x_size+(x_stop-2)])-log(y_array[index_y*x_size+(x_stop-1)]))- (log(x[x_stop-2])-log(x[x_stop-1]))*(log(x[x_stop-2])-log(x[x_stop-1]))* (log(y_array[index_y*x_size+(x_stop-3)])-log(y_array[index_y*x_size+(x_stop-1)])))/ ((log(x[x_stop-3])-log(x[x_stop-1]))*(log(x[x_stop-2])-log(x[x_stop-1]))* (log(x[x_stop-3])-log(x[x_stop-2]))); qn=0.5; un= (3./(log(x[x_stop-1]) - log(x[x_stop-2])))* (dy_last-(log(y_array[index_y*x_size+(x_stop-1)]) - log(y_array[index_y*x_size+(x_stop-2)]))/ (log(x[x_stop-1]) - log(x[x_stop-2]))); } else { sprintf(errmsg,"%s(L:%d) Spline mode not identified: %d",__func__,__LINE__,spline_mode); return _FAILURE_; } } /************************************************/ index_x=x_stop-1; ddlogy_array[index_y*x_size+index_x] = (un - qn * u[index_x-1]) / (qn * ddlogy_array[index_y*x_size+(index_x-1)] + 1.0); for (index_x=x_stop-2; index_x >= 0; index_x--) { ddlogy_array[index_y*x_size+index_x] = ddlogy_array[index_y*x_size+index_x] * ddlogy_array[index_y*x_size+(index_x+1)] + u[index_x]; } free(u); return _SUCCESS_; } int array_integrate_all_spline( double * array, int n_columns, int n_lines, int index_x, /** from 0 to (n_columns-1) */ int index_y, int index_ddy, double * result, ErrorMsg errmsg) { int i; double h; *result = 0; for (i=0; i < n_lines-1; i++) { h = (array[(i+1)*n_columns+index_x]-array[i*n_columns+index_x]); *result += (array[i*n_columns+index_y]+array[(i+1)*n_columns+index_y])*h/2.+ (array[i*n_columns+index_ddy]+array[(i+1)*n_columns+index_ddy])*h*h*h/24.; } return _SUCCESS_; } int array_integrate_all_trapzd_or_spline( double * array, int n_columns, int n_lines, int index_start_spline, int index_x, /** from 0 to (n_columns-1) */ int index_y, int index_ddy, double * result, ErrorMsg errmsg) { int i; double h; if ((index_start_spline<0) || (index_start_spline>=n_lines)) { sprintf(errmsg,"%s(L:%d) index_start_spline outside of range",__func__,__LINE__); return _FAILURE_; } *result = 0; /* trapezoidal integration till given index */ for (i=0; i < index_start_spline; i++) { h = (array[(i+1)*n_columns+index_x]-array[i*n_columns+index_x]); *result += (array[i*n_columns+index_y]+array[(i+1)*n_columns+index_y])*h/2.; } /* then, spline integration */ for (i=index_start_spline; i < n_lines-1; i++) { h = (array[(i+1)*n_columns+index_x]-array[i*n_columns+index_x]); *result += (array[i*n_columns+index_y]+array[(i+1)*n_columns+index_y])*h/2.+ (array[i*n_columns+index_ddy]+array[(i+1)*n_columns+index_ddy])*h*h*h/24.; } return _SUCCESS_; } /** * Not called. */ int array_integrate( double * array, int n_columns, int n_lines, int index_x, /** from 0 to (n_columns-1) */ int index_y, int index_int_y_dx, ErrorMsg errmsg) { int i; double sum; if ((index_int_y_dx == index_x) || (index_int_y_dx == index_y)) { sprintf(errmsg,"%s(L:%d) : Output column %d must differ from input columns %d and %d",__func__,__LINE__,index_int_y_dx,index_x,index_y); return _FAILURE_; } sum=0.; *(array+0*n_columns+index_int_y_dx)=sum; for (i=1; i<n_lines; i++) { sum += 0.5 * (*(array+i*n_columns+index_y) + *(array+(i-1)*n_columns+index_y)) * (*(array+i*n_columns+index_x) - *(array+(i-1)*n_columns+index_x)); *(array+i*n_columns+index_int_y_dx)=sum; } return _SUCCESS_; } /** * Called by thermodynamics_init(). */ int array_integrate_ratio( double * array, int n_columns, int n_lines, int index_x, /** from 0 to (n_columns-1) */ int index_y1, int index_y2, int index_int_y1_over_y2_dx, ErrorMsg errmsg) { int i; double sum; if ((index_int_y1_over_y2_dx == index_x) || (index_int_y1_over_y2_dx == index_y1) || (index_int_y1_over_y2_dx == index_y2)) { sprintf(errmsg,"%s(L:%d) : Output column %d must differ from input columns %d, %d and %d",__func__,__LINE__,index_int_y1_over_y2_dx,index_x,index_y1,index_y2); return _FAILURE_; } sum=0.; *(array+0*n_columns+index_int_y1_over_y2_dx)=sum; for (i=1; i<n_lines; i++) { sum += 0.5 * (*(array+i*n_columns+index_y1) / *(array+i*n_columns+index_y2) + *(array+(i-1)*n_columns+index_y1) / *(array+(i-1)*n_columns+index_y2)) * (*(array+i*n_columns+index_x) - *(array+(i-1)*n_columns+index_x)); *(array+i*n_columns+index_int_y1_over_y2_dx)=sum; } return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are all columns of the same array * * Called by background_at_eta(); background_eta_of_z(); background_solve(); thermodynamics_at_z(). */ int array_interpolate( double * array, int n_columns, int n_lines, int index_x, /** from 0 to (n_columns-1) */ double x, int * last_index, double * result, int result_size, /** from 1 to n_columns */ ErrorMsg errmsg) { int inf,sup,mid,i; double weight; inf=0; sup=n_lines-1; if (*(array+inf*n_columns+index_x) < *(array+sup*n_columns+index_x)){ if (x < *(array+inf*n_columns+index_x)) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,*(array+inf*n_columns+index_x)); return _FAILURE_; } if (x > *(array+sup*n_columns+index_x)) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,*(array+sup*n_columns+index_x)); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < *(array+mid*n_columns+index_x)) {sup=mid;} else {inf=mid;} } } else { if (x < *(array+sup*n_columns+index_x)) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,*(array+sup*n_columns+index_x)); return _FAILURE_; } if (x > *(array+inf*n_columns+index_x)) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,*(array+inf*n_columns+index_x)); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > *(array+mid*n_columns+index_x)) {sup=mid;} else {inf=mid;} } } *last_index = inf; weight=(x-*(array+inf*n_columns+index_x))/(*(array+sup*n_columns+index_x)-*(array+inf*n_columns+index_x)); for (i=0; i<result_size; i++) *(result+i) = *(array+inf*n_columns+i) * (1.-weight) + weight * *(array+sup*n_columns+i); *(result+index_x) = x; return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are in different arrays * * Called by background_at_eta(); background_eta_of_z(); background_solve(); thermodynamics_at_z(). */ int array_interpolate_spline( double * __restrict__ x_array, int n_lines, double * __restrict__ array, double * __restrict__ array_splined, int n_columns, double x, int * __restrict__ last_index, double * __restrict__ result, int result_size, /** from 1 to n_columns */ ErrorMsg errmsg) { int inf,sup,mid,i; double h,a,b; inf=0; sup=n_lines-1; if (x_array[inf] < x_array[sup]){ if (x < x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } if (x > x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < x_array[mid]) {sup=mid;} else {inf=mid;} } } else { if (x < x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } if (x > x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > x_array[mid]) {sup=mid;} else {inf=mid;} } } *last_index = inf; h = x_array[sup] - x_array[inf]; b = (x-x_array[inf])/h; a = 1-b; for (i=0; i<result_size; i++) *(result+i) = a * *(array+inf*n_columns+i) + b * *(array+sup*n_columns+i) + ((a*a*a-a)* *(array_splined+inf*n_columns+i) + (b*b*b-b)* *(array_splined+sup*n_columns+i))*h*h/6.; return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are in different arrays * * Called by background_at_eta(); background_eta_of_z(); background_solve(); thermodynamics_at_z(). */ int array_interpolate_linear( double * x_array, int n_lines, double * array, int n_columns, double x, int * last_index, double * result, int result_size, /** from 1 to n_columns */ ErrorMsg errmsg) { int inf,sup,mid,i; double h,a,b; inf=0; sup=n_lines-1; if (x_array[inf] < x_array[sup]){ if (x < x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } if (x > x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < x_array[mid]) {sup=mid;} else {inf=mid;} } } else { if (x < x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } if (x > x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > x_array[mid]) {sup=mid;} else {inf=mid;} } } *last_index = inf; h = x_array[sup] - x_array[inf]; b = (x-x_array[inf])/h; a = 1-b; for (i=0; i<result_size; i++) *(result+i) = a * *(array+inf*n_columns+i) + b * *(array+sup*n_columns+i); return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are in different arrays * * Called by background_at_eta(); background_eta_of_z(); background_solve(); thermodynamics_at_z(). */ int array_interpolate_logspline( double * x_array, int n_lines, double * array, double * array_logsplined, int n_columns, double x, int * last_index, double * result, int result_size, /** from 1 to n_columns */ ErrorMsg errmsg) { int inf,sup,mid,i; double h,a,b; inf=0; sup=n_lines-1; if (x_array[inf] < x_array[sup]){ if (x < x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } if (x > x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < x_array[mid]) {sup=mid;} else {inf=mid;} } } else { if (x < x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } if (x > x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > x_array[mid]) {sup=mid;} else {inf=mid;} } } *last_index = inf; h = log(x_array[sup]) - log(x_array[inf]); b = (log(x)-log(x_array[inf]))/h; a = 1-b; for (i=0; i<result_size; i++) *(result+i) = exp( a * log(array[inf*n_columns+i]) + b * log(array[sup*n_columns+i]) + ((a*a*a-a)* array_logsplined[inf*n_columns+i] + (b*b*b-b)* array_logsplined[sup*n_columns+i])*h*h/6.); return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are in different arrays * * */ int array_interpolate_spline_one_column( double * x_array, int x_size, double * y_array, /* array of size x_size*y_size with elements y_array[index_y*x_size+index_x] */ int y_size, int index_y, double * ddy_array, /* array of size x_size*y_size */ double x, /* input */ double * y, /* output */ ErrorMsg errmsg ) { int inf,sup,mid; double h,a,b; inf=0; sup=x_size-1; if (x_array[inf] < x_array[sup]){ if (x < x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } if (x > x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < x_array[mid]) {sup=mid;} else {inf=mid;} } } else { if (x < x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } if (x > x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > x_array[mid]) {sup=mid;} else {inf=mid;} } } h = x_array[sup] - x_array[inf]; b = (x-x_array[inf])/h; a = 1-b; *y = a * y_array[index_y * x_size + inf] + b * y_array[index_y * x_size + sup] + ((a*a*a-a)* ddy_array[index_y * x_size + inf] + (b*b*b-b)* ddy_array[index_y * x_size + sup])*h*h/6.; return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are in different arrays * * */ int array_interpolate_extrapolate_spline_one_column( double * x_array, int x_size, double * y_array, /* array of size x_size*y_size with elements y_array[index_y*x_size+index_x] */ int y_size, int index_y, double * ddy_array, /* array of size x_size*y_size */ double x, /* input */ double * y, /* output */ ErrorMsg errmsg ) { int inf,sup,mid; double h,a,b; if (x > x_array[x_size-2] || x < x_array[0]) { /*interpolate/extrapolate linearly y as a function of x*/ h = x_array[x_size-1] - x_array[x_size-2]; b = (x-x_array[x_size-2])/h; a = 1-b; *y = a * y_array[index_y * x_size + (x_size-2)] + b * y_array[index_y * x_size + (x_size-1)]; } else { /*interpolate y as a function of x with a spline*/ inf=0; sup=x_size-1; if (x_array[inf] < x_array[sup]){ if (x < x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } if (x > x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < x_array[mid]) {sup=mid;} else {inf=mid;} } } else { if (x < x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } if (x > x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > x_array[mid]) {sup=mid;} else {inf=mid;} } } h = x_array[sup] - x_array[inf]; b = (x-x_array[inf])/h; a = 1-b; *y = a * y_array[index_y * x_size + inf] + b * y_array[index_y * x_size + sup] + ((a*a*a-a)* ddy_array[index_y * x_size + inf] + (b*b*b-b)* ddy_array[index_y * x_size + sup])*h*h/6.; } return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are in different arrays * * */ int array_interpolate_extrapolate_logspline_loglinear_one_column( double * x_array, int x_size, int x_stop, double * y_array, /* array of size x_size*y_size with elements y_array[index_y*x_size+index_x] */ int y_size, int index_y, double * ddlogy_array, /* array of size x_size*y_size */ double x, /* input */ double * y, /* output */ ErrorMsg errmsg ) { int inf,sup,mid; double h,a,b; if (x > x_array[x_stop-1]) { /*interpolate/extrapolate linearly ln(y) as a function of ln(x)*/ h = log(x_array[x_stop-1]) - log(x_array[x_stop-2]); b = (log(x)-log(x_array[x_stop-2]))/h; a = 1-b; /* *y = exp(a * log(y_array[index_y * x_size + (x_stop-2)]) + */ /* b * log(y_array[index_y * x_size + (x_stop-1)])); */ *y = exp(log(y_array[index_y * x_size + (x_stop-1)]) +(log(x)-log(x_array[x_stop-1])) *((log(y_array[index_y * x_size + (x_stop-1)])-log(y_array[index_y * x_size + (x_stop-2)]))/h +h/6.*(ddlogy_array[index_y * x_size + (x_stop-2)]+2.*ddlogy_array[index_y * x_size + (x_stop-1)]))); } else { /*interpolate ln(y) as a function of ln(x) with a spline*/ inf=0; sup=x_stop-1; if (x_array[inf] < x_array[sup]){ if (x < x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } if (x > x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < x_array[mid]) {sup=mid;} else {inf=mid;} } } else { if (x < x_array[sup]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,x_array[sup]); return _FAILURE_; } if (x > x_array[inf]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,x_array[inf]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > x_array[mid]) {sup=mid;} else {inf=mid;} } } h = log(x_array[sup]) - log(x_array[inf]); b = (log(x)-log(x_array[inf]))/h; a = 1-b; *y = exp(a * log(y_array[index_y * x_size + inf]) + b * log(y_array[index_y * x_size + sup]) + ((a*a*a-a)* ddlogy_array[index_y * x_size + inf] + (b*b*b-b)* ddlogy_array[index_y * x_size + sup])*h*h/6.); } return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are all columns of the same array, x is arranged in growing order, and the point x is presumably close to the previous point x from the last call of this function. * * Called by background_at_eta(); background_eta_of_z(); background_solve(); thermodynamics_at_z(). */ int array_interpolate_growing_closeby( double * array, int n_columns, int n_lines, int index_x, /** from 0 to (n_columns-1) */ double x, int * last_index, double * result, int result_size, /** from 1 to n_columns */ ErrorMsg errmsg) { int inf,sup,i; double weight; inf = *last_index; sup = *last_index+1; while (x < *(array+inf*n_columns+index_x)) { inf--; if (inf < 0) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__, x,array[index_x]); return _FAILURE_; } } sup = inf+1; while (x > *(array+sup*n_columns+index_x)) { sup++; if (sup > (n_lines-1)) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__, x,array[(n_lines-1)*n_columns+index_x]); return _FAILURE_; } } inf = sup-1; *last_index = inf; weight=(x-*(array+inf*n_columns+index_x))/(*(array+sup*n_columns+index_x)-*(array+inf*n_columns+index_x)); for (i=0; i<result_size; i++) *(result+i) = *(array+inf*n_columns+i) * (1.-weight) + weight * *(array+sup*n_columns+i); *(result+index_x) = x; return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are all columns of the same array, x is arranged in growing order, and the point x is presumably very close to the previous point x from the last call of this function. * * Called by background_at_eta(); background_eta_of_z(); background_solve(); thermodynamics_at_z(). */ int array_interpolate_spline_growing_closeby( double * x_array, int n_lines, double * array, double * array_splined, int n_columns, double x, int * last_index, double * result, int result_size, /** from 1 to n_columns */ ErrorMsg errmsg) { int inf,sup,i; double h,a,b; inf = *last_index; class_test(inf<0 || inf>(n_lines-1), errmsg, "*lastindex=%d out of range [0:%d]\n",inf,n_lines-1); while (x < x_array[inf]) { inf--; if (inf < 0) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__, x,x_array[0]); return _FAILURE_; } } sup = inf+1; while (x > x_array[sup]) { sup++; if (sup > (n_lines-1)) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__, x,x_array[n_lines-1]); return _FAILURE_; } } inf = sup-1; *last_index = inf; h = x_array[sup] - x_array[inf]; b = (x-x_array[inf])/h; a = 1-b; for (i=0; i<result_size; i++) *(result+i) = a * *(array+inf*n_columns+i) + b * *(array+sup*n_columns+i) + ((a*a*a-a)* *(array_splined+inf*n_columns+i) + (b*b*b-b)* *(array_splined+sup*n_columns+i))*h*h/6.; return _SUCCESS_; } /** * interpolate to get y_i(x), when x and y_i are all columns of the same array, x is arranged in growing order, and the point x is presumably close (but maybe not so close) to the previous point x from the last call of this function. * * Called by background_at_eta(); background_eta_of_z(); background_solve(); thermodynamics_at_z(). */ int array_interpolate_spline_growing_hunt( double * x_array, int n_lines, double * array, double * array_splined, int n_columns, double x, int * last_index, double * result, int result_size, /** from 1 to n_columns */ ErrorMsg errmsg) { int inf,sup,mid,i,inc; double h,a,b; inc=1; if (x >= x_array[*last_index]) { if (x > x_array[n_lines-1]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__, x,x_array[n_lines-1]); return _FAILURE_; } /* try closest neighboor upward */ inf = *last_index; sup = inf + inc; if (x > x_array[sup]) { /* hunt upward */ while (x > x_array[sup]) { inf = sup; inc += 1; sup += inc; if (sup > n_lines-1) { sup = n_lines-1; } } /* bisect */ while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < x_array[mid]) {sup=mid;} else {inf=mid;} } } } else { if (x < x_array[0]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__, x,x_array[0]); return _FAILURE_; } /* try closest neighboor downward */ sup = *last_index; inf = sup - inc; if (x < x_array[inf]) { /* hunt downward */ while (x < x_array[inf]) { sup = inf; inc += 1; inf -= inc; if (inf < 0) { inf = 0; } } /* bisect */ while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < x_array[mid]) {sup=mid;} else {inf=mid;} } } } *last_index = inf; h = x_array[sup] - x_array[inf]; b = (x-x_array[inf])/h; a = 1-b; for (i=0; i<result_size; i++) *(result+i) = a * *(array+inf*n_columns+i) + b * *(array+sup*n_columns+i) + ((a*a*a-a)* *(array_splined+inf*n_columns+i) + (b*b*b-b)* *(array_splined+sup*n_columns+i))*h*h/6.; return _SUCCESS_; } /** * interpolate linearily to get y_i(x), when x and y_i are in two different arrays * * Called by transfer_interpolate_sources(); transfer_functions_at_k(); perturb_sources_at_eta(). */ int array_interpolate_two( double * array_x, int n_columns_x, int index_x, /** from 0 to (n_columns_x-1) */ double * array_y, int n_columns_y, int n_lines, /** must be the same for array_x and array_y */ double x, double * result, int result_size, /** from 1 to n_columns_y */ ErrorMsg errmsg) { int inf,sup,mid,i; double weight; inf=0; sup=n_lines-1; if (array_x[inf*n_columns_x+index_x] < array_x[sup*n_columns_x+index_x]){ if (x < array_x[inf*n_columns_x+index_x]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,array_x[inf*n_columns_x+index_x]); return _FAILURE_; } if (x > array_x[sup*n_columns_x+index_x]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,array_x[sup*n_columns_x+index_x]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < array_x[mid*n_columns_x+index_x]) {sup=mid;} else {inf=mid;} } } else { if (x < *(array_x+sup*n_columns_x+index_x)) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,*(array_x+sup*n_columns_x+index_x)); return _FAILURE_; } if (x > *(array_x+inf*n_columns_x+index_x)) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,*(array_x+inf*n_columns_x+index_x)); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > *(array_x+mid*n_columns_x+index_x)) {sup=mid;} else {inf=mid;} } } weight=(x-*(array_x+inf*n_columns_x+index_x))/(*(array_x+sup*n_columns_x+index_x)-*(array_x+inf*n_columns_x+index_x)); for (i=0; i<result_size; i++) *(result+i) = *(array_y+i*n_lines+inf) * (1.-weight) + weight * *(array_y+i*n_lines+sup) ; return _SUCCESS_; } /** * Same as array_interpolate_two, but with order of indices exchanged in array_y */ int array_interpolate_two_bis( double * array_x, int n_columns_x, int index_x, /** from 0 to (n_columns_x-1) */ double * array_y, int n_columns_y, int n_lines, /** must be the same for array_x and array_y */ double x, double * result, int result_size, /** from 1 to n_columns_y */ ErrorMsg errmsg) { int inf,sup,mid,i; double weight; inf=0; sup=n_lines-1; if (array_x[inf*n_columns_x+index_x] < array_x[sup*n_columns_x+index_x]){ if (x < array_x[inf*n_columns_x+index_x]) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,array_x[inf*n_columns_x+index_x]); return _FAILURE_; } if (x > array_x[sup*n_columns_x+index_x]) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,array_x[sup*n_columns_x+index_x]); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < array_x[mid*n_columns_x+index_x]) {sup=mid;} else {inf=mid;} } } else { if (x < *(array_x+sup*n_columns_x+index_x)) { sprintf(errmsg,"%s(L:%d) : x=%e < x_min=%e",__func__,__LINE__,x,*(array_x+sup*n_columns_x+index_x)); return _FAILURE_; } if (x > *(array_x+inf*n_columns_x+index_x)) { sprintf(errmsg,"%s(L:%d) : x=%e > x_max=%e",__func__,__LINE__,x,*(array_x+inf*n_columns_x+index_x)); return _FAILURE_; } while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > *(array_x+mid*n_columns_x+index_x)) {sup=mid;} else {inf=mid;} } } weight=(x-*(array_x+inf*n_columns_x+index_x))/(*(array_x+sup*n_columns_x+index_x)-*(array_x+inf*n_columns_x+index_x)); for (i=0; i<result_size; i++) *(result+i) = *(array_y+inf*n_columns_y+i) * (1.-weight) + weight * *(array_y+sup*n_columns_y+i) ; return _SUCCESS_; } /** * interpolate linearily to get y_i(x), when x and y_i are in two different arrays * * Called by transfer_interpolate_sources(); transfer_functions_at_k(); perturb_sources_at_eta(). */ int array_interpolate_two_arrays_one_column( double * array_x, /* assumed to be a vector (i.e. one column array) */ double * array_y, int n_columns_y, int index_y, /* between 0 and (n_columns_y-1) */ int n_lines, /** must be the same for array_x and array_y */ double x, double * result, ErrorMsg errmsg) { int inf,sup,mid; double weight; inf=0; sup=n_lines-1; if (array_x[inf] < array_x[sup]){ class_test(x < array_x[inf], errmsg, "x=%e < x_min=%e",x,array_x[inf]); class_test(x > array_x[sup], errmsg, "x=%e > x_max=%e",x,array_x[sup]); while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x < array_x[mid]) {sup=mid;} else {inf=mid;} } } else { class_test(x < array_x[sup], errmsg, "x=%e < x_min=%e",x,array_x[sup]); class_test(x > array_x[inf], errmsg, "x=%e > x_max=%e",x,array_x[inf]); while (sup-inf > 1) { mid=(int)(0.5*(inf+sup)); if (x > array_x[mid]) {sup=mid;} else {inf=mid;} } } weight=(x-array_x[inf])/(array_x[sup]-array_x[inf]); *result = array_y[index_y*n_lines+inf] * (1.-weight) + weight * array_y[index_y*n_lines+sup]; return _SUCCESS_; } /** * Called by transfer_solve(). */ int array_interpolate_equal( double * array, int n_columns, int n_lines, double x, double x_min, double x_max, double * result, ErrorMsg errmsg) { int index_minus,i; double x_step,x_minus,weight; if (x < x_min) { sprintf(errmsg,"%s(L:%d) : x out of bounds: x=%e,x_min=%e",__func__,__LINE__,x,x_min); return _FAILURE_; } if (x > x_max) { sprintf(errmsg,"%s(L:%d) : x out of bounds: x=%e,x_max=%e",__func__,__LINE__,x,x_max); return _FAILURE_; } x_step = (x_max-x_min)/(n_lines-1); index_minus = (int)((x-x_min)/x_step); x_minus = index_minus * x_step; weight = (x-x_minus) / x_step; for (i=0; i<n_columns; i++) result[i] = *(array+n_columns*index_minus+i)*(1.-weight) + *(array+n_columns*(index_minus+1)+i)*weight; return _SUCCESS_; } /** * cubic interpolation of array with equally space abscisses */ int array_interpolate_cubic_equal( double x0, double dx, double *yarray, int Nx, double x, double * result, ErrorMsg errmsg) { int i; double frac; class_test((dx > 0 && (x<x0 || x>x0+dx*(Nx-1))), errmsg, "x=%e out of range [%e %e]",x,x0,x0+dx*(Nx-1)); class_test((dx < 0 && (x>x0 || x<x0+dx*(Nx-1))), errmsg, "x=%e out of range [%e %e]",x,x0+dx*(Nx-1),x0); i = (int)floor((x-x0)/dx); if (i<1) i=1; if (i>Nx-3) i=Nx-3; frac = (x-x0)/dx-i; yarray += i-1; *result=-yarray[0]*frac*(1.-frac)*(2.-frac)/6. +yarray[1]*(1.+frac)*(1.-frac)*(2.-frac)/2. +yarray[2]*(1.+frac)*frac*(2.-frac)/2. +yarray[3]*(1.+frac)*frac*(frac-1.)/6.; return _SUCCESS_; } int array_interpolate_parabola(double x1, double x2, double x3, double x, double y1, double y2, double y3, double * y, double * dy, double * ddy, ErrorMsg errmsg) { double a,b,c; /* a x_i**2 + b x_i + c = y_i a (x1**2-x2**2) + b (x1-x2) = y1-y2 a (x3**2-x2**2) + b (x3-x2) = y3-y2 a (x1**2-x2**2)(x3**2-x2**2) + b (x1-x2)(x3**2-x2**2) = (y1-y2)(x3**2-x2**2) a (x3**2-x2**2)(x1**2-x2**2) + b (x3-x2)(x1**2-x2**2) = (y3-y2)(x1**2-x2**2) b = [(y1-y2)(x3**2-x2**2) - (y3-y2)(x1**2-x2**2)]/(x1-x2)(x3-x2)(x3-x1) */ b = ((y1-y2)*(x3-x2)*(x3+x2) - (y3-y2)*(x1-x2)*(x1+x2))/(x1-x2)/(x3-x2)/(x3-x1); a = (y1-y2-b*(x1-x2))/(x1-x2)/(x1+x2); c = y2 - b*x2 - a*x2*x2; *y = a*x*x + b*x + c; *dy = 2.*a*x + b; *ddy = 2.*a; return _SUCCESS_; } /** * Called by transfer_solve(). */ int array_integrate_all( double * array, int n_columns, int n_lines, int index_x, /** from 0 to (n_columns-1) */ int index_y, double *result) { int i; double sum; sum=0.; for (i=1; i<n_lines; i++) { sum += 0.5 * (*(array+i*n_columns+index_y) + *(array+(i-1)*n_columns+index_y)) * (*(array+i*n_columns+index_x) - *(array+(i-1)*n_columns+index_x)); } *result = sum; return _SUCCESS_; } int array_smooth_trg(double * array, int k_size, int starting_k, int eta_size, int index_eta, int radius, /*3, 5 or 7 */ ErrorMsg errmsg) { double * smooth; int i,j,jmin,jmax; double weigth; double *coeff; smooth=malloc(k_size*sizeof(double)); if (smooth == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate smooth",__func__,__LINE__); return _FAILURE_; } class_calloc(coeff,2*radius+1,sizeof(double),errmsg); switch(radius){ case 3: weigth = 21; coeff[0] = -2; coeff[1] = 3; coeff[2] = 6; coeff[3] = 7; coeff[4] = 6; coeff[5] = 3; coeff[6] = -2; break; case 4: weigth = 231; coeff[0] = -21; coeff[1] = 14; coeff[2] = 39; coeff[3] = 54; coeff[4] = 59; coeff[5] = 54; coeff[6] = 39; coeff[7] = 14; coeff[8] = -21; break; case 5: weigth = 429; coeff[0] = -36; coeff[1] = 9; coeff[2] = 44; coeff[3] = 69; coeff[4] = 84; coeff[5] = 89; coeff[6] = 84; coeff[7] = 69; coeff[8] = 44; coeff[9] = 9; coeff[10] = -36; break; case 6: weigth = 143; coeff[0] = -11; coeff[1] = 0; coeff[2] = 9; coeff[3] = 16; coeff[4] = 21; coeff[5] = 24; coeff[6] = 25; coeff[7] = 24; coeff[8] = 21; coeff[9] = 16; coeff[10] = 9; coeff[11] = 0; coeff[12] = -11; break; case 7: weigth = 1105; coeff[0] = -78; coeff[1] = -13; coeff[2] = 42; coeff[3] = 87; coeff[4] = 122; coeff[5] = 147; coeff[6] = 162; coeff[7] = 167; coeff[8] = 162; coeff[9] = 147; coeff[10] = 122; coeff[11] = 87; coeff[12] = 42; coeff[13] = -13; coeff[14] = -78; break; /* case 8: */ default: class_stop(errmsg,"Non valid radius %d: please chose between 3 4 5 or 6\n",radius); weigth=0; break; } for (i=starting_k; i<k_size-radius; i++) { smooth[i]=0.; jmin = MAX(i-radius,0); jmax = MIN(i+radius,k_size-1); for (j=jmin; j <= jmax; j++) { smooth[i] += coeff[j-jmin]*array[j+k_size*index_eta]; } smooth[i] /= weigth; } for (i=starting_k; i<k_size-radius; i++) array[i+k_size*index_eta] = smooth[i]; free(smooth); free(coeff); return _SUCCESS_; } int array_smooth(double * array, int n_columns, int n_lines, int index, /** from 0 to (n_columns-1) */ int radius, ErrorMsg errmsg) { double * smooth; int i,j,jmin,jmax; double weigth; smooth=malloc(n_lines*sizeof(double)); if (smooth == NULL) { sprintf(errmsg,"%s(L:%d) Cannot allocate smooth",__func__,__LINE__); return _FAILURE_; } for (i=0; i<n_lines; i++) { smooth[i]=0.; weigth=0.; jmin = MAX(i-radius,0); jmax = MIN(i+radius,n_lines-1); for (j=jmin; j <= jmax; j++) { smooth[i] += array[j*n_columns+index]; weigth += 1.; } smooth[i] /= weigth; } for (i=0; i<n_lines; i++) array[i*n_columns+index] = smooth[i]; free(smooth); return _SUCCESS_; } /** * Compute quadrature weights for the trapezoidal integration method, xhen x is in gorwing order. * * @param x Input: Grid points on which f() is known. * @param n Input: number of grid points. * @param w_trapz Output: Weights of the trapezoidal method. * @return the error status */ int array_trapezoidal_weights( double * __restrict__ x, int n, double * __restrict__ w_trapz, ErrorMsg errmsg ) { int i; /* Case with just one point, w would normally be 0. */ if (n==1){ w_trapz[0] = 0.0; } else if (n>1){ //Set edgeweights: w_trapz[0] = 0.5*(x[1]-x[0]); w_trapz[n-1] = 0.5*(x[n-1]-x[n-2]); //Set inner weights: for (i=1; i<(n-1); i++){ w_trapz[i] = 0.5*(x[i+1]-x[i-1]); } } return _SUCCESS_; } /** * Compute quadrature weights for the trapezoidal integration method, when x is in decreasing order. * * @param x Input: Grid points on which f() is known. * @param n Input: number of grid points. * @param w_trapz Output: Weights of the trapezoidal method. * @return the error status */ int array_trapezoidal_mweights( double * __restrict__ x, int n, double * __restrict__ w_trapz, ErrorMsg errmsg ) { int i; /* Case with just one point. */ if (n==1){ w_trapz[0] = 1.0; } else if (n>1){ //Set edgeweights: w_trapz[0] = 0.5*(x[0]-x[1]); w_trapz[n-1] = 0.5*(x[n-2]-x[n-1]); //Set inner weights: for (i=1; i<(n-1); i++){ w_trapz[i] = 0.5*(x[i-1]-x[i+1]); } } return _SUCCESS_; } /** * Compute integral of function using trapezoidal method. * * @param integrand Input: The function we are integrating. * @param n Input: Compute integral on grid [0;n-1]. * @param w_trapz Input: Weights of the trapezoidal method. * @param I Output: The integral. * @return the error status */ int array_trapezoidal_integral( double * __restrict__ integrand, int n, double * __restrict__ w_trapz, double * __restrict__ I, ErrorMsg errmsg ) { int i; double res=0.0; for (i=0; i<n; i++){ res += integrand[i]*w_trapz[i]; } *I = res; return _SUCCESS_; } /** * Compute convolution integral of product of two functions using trapezoidal method. * * @param integrand1 Input: Function 1. * @param integrand2 Input: Function 2. * @param n Input: Compute integral on grid [0;n-1]. * @param w_trapz Input: Weights of the trapezoidal method. * @param I Output: The integral. * @return the error status */ int array_trapezoidal_convolution( double * __restrict__ integrand1, double * __restrict__ integrand2, int n, double * __restrict__ w_trapz, double * __restrict__ I, ErrorMsg errmsg ) { int i; double res=0.0; for (i=0; i<n; i++){ res += integrand1[i]*integrand2[i]*w_trapz[i]; } *I = res; return _SUCCESS_; }
morphology.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M OOO RRRR PPPP H H OOO L OOO GGGG Y Y % % MM MM O O R R P P H H O O L O O G Y Y % % M M M O O RRRR PPPP HHHHH O O L O O G GGG Y % % M M O O R R P H H O O L O O G G Y % % M M OOO R R P H H OOO LLLLL OOO GGG Y % % % % % % MagickCore Morphology Methods % % % % Software Design % % Anthony Thyssen % % January 2010 % % % % % % Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Morpology is the the application of various kernels, of any size and even % shape, to a image in various ways (typically binary, but not always). % % Convolution (weighted sum or average) is just one specific type of % morphology. Just one that is very common for image bluring and sharpening % effects. Not only 2D Gaussian blurring, but also 2-pass 1D Blurring. % % This module provides not only a general morphology function, and the ability % to apply more advanced or iterative morphologies, but also functions for the % generation of many different types of kernel arrays from user supplied % arguments. Prehaps even the generation of a kernel from a small image. */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/cache-view.h" #include "magick/color-private.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/hashmap.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor-private.h" #include "magick/morphology.h" #include "magick/morphology-private.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/prepress.h" #include "magick/quantize.h" #include "magick/registry.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/token.h" #include "magick/utility.h" /* ** The following test is for special floating point numbers of value NaN (not ** a number), that may be used within a Kernel Definition. NaN's are defined ** as part of the IEEE standard for floating point number representation. ** ** These are used as a Kernel value to mean that this kernel position is not ** part of the kernel neighbourhood for convolution or morphology processing, ** and thus should be ignored. This allows the use of 'shaped' kernels. ** ** The special properity that two NaN's are never equal, even if they are from ** the same variable allow you to test if a value is special NaN value. ** ** This macro IsNaN() is thus is only true if the value given is NaN. */ #define IsNan(a) ((a)!=(a)) /* Other global definitions used by module. */ static inline double MagickMin(const double x,const double y) { return( x < y ? x : y); } static inline double MagickMax(const double x,const double y) { return( x > y ? x : y); } #define Minimize(assign,value) assign=MagickMin(assign,value) #define Maximize(assign,value) assign=MagickMax(assign,value) /* Currently these are only internal to this module */ static void CalcKernelMetaData(KernelInfo *), ExpandMirrorKernelInfo(KernelInfo *), ExpandRotateKernelInfo(KernelInfo *, const double), RotateKernelInfo(KernelInfo *, double); /* Quick function to find last kernel in a kernel list */ static inline KernelInfo *LastKernelInfo(KernelInfo *kernel) { while (kernel->next != (KernelInfo *) NULL) kernel = kernel->next; return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireKernelInfo() takes the given string (generally supplied by the % user) and converts it into a Morphology/Convolution Kernel. This allows % users to specify a kernel from a number of pre-defined kernels, or to fully % specify their own kernel for a specific Convolution or Morphology % Operation. % % The kernel so generated can be any rectangular array of floating point % values (doubles) with the 'control point' or 'pixel being affected' % anywhere within that array of values. % % Previously IM was restricted to a square of odd size using the exact % center as origin, this is no longer the case, and any rectangular kernel % with any value being declared the origin. This in turn allows the use of % highly asymmetrical kernels. % % The floating point values in the kernel can also include a special value % known as 'nan' or 'not a number' to indicate that this value is not part % of the kernel array. This allows you to shaped the kernel within its % rectangular area. That is 'nan' values provide a 'mask' for the kernel % shape. However at least one non-nan value must be provided for correct % working of a kernel. % % The returned kernel should be freed using the DestroyKernelInfo() when you % are finished with it. Do not free this memory yourself. % % Input kernel defintion strings can consist of any of three types. % % "name:args[[@><]" % Select from one of the built in kernels, using the name and % geometry arguments supplied. See AcquireKernelBuiltIn() % % "WxH[+X+Y][@><]:num, num, num ..." % a kernel of size W by H, with W*H floating point numbers following. % the 'center' can be optionally be defined at +X+Y (such that +0+0 % is top left corner). If not defined the pixel in the center, for % odd sizes, or to the immediate top or left of center for even sizes % is automatically selected. % % "num, num, num, num, ..." % list of floating point numbers defining an 'old style' odd sized % square kernel. At least 9 values should be provided for a 3x3 % square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc. % Values can be space or comma separated. This is not recommended. % % You can define a 'list of kernels' which can be used by some morphology % operators A list is defined as a semi-colon separated list kernels. % % " kernel ; kernel ; kernel ; " % % Any extra ';' characters, at start, end or between kernel defintions are % simply ignored. % % The special flags will expand a single kernel, into a list of rotated % kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree % cyclic rotations, while a '>' will generate a list of 90-degree rotations. % The '<' also exands using 90-degree rotates, but giving a 180-degree % reflected kernel before the +/- 90-degree rotations, which can be important % for Thinning operations. % % Note that 'name' kernels will start with an alphabetic character while the % new kernel specification has a ':' character in its specification string. % If neither is the case, it is assumed an old style of a simple list of % numbers generating a odd-sized square kernel has been given. % % The format of the AcquireKernal method is: % % KernelInfo *AcquireKernelInfo(const char *kernel_string) % % A description of each parameter follows: % % o kernel_string: the Morphology/Convolution kernel wanted. % */ /* This was separated so that it could be used as a separate ** array input handling function, such as for -color-matrix */ static KernelInfo *ParseKernelArray(const char *kernel_string) { KernelInfo *kernel; char token[MaxTextExtent]; const char *p, *end; register ssize_t i; double nan = sqrt((double)-1.0); /* Special Value : Not A Number */ MagickStatusType flags; GeometryInfo args; kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (kernel == (KernelInfo *)NULL) return(kernel); (void) ResetMagickMemory(kernel,0,sizeof(*kernel)); kernel->minimum = kernel->maximum = kernel->angle = 0.0; kernel->negative_range = kernel->positive_range = 0.0; kernel->type = UserDefinedKernel; kernel->next = (KernelInfo *) NULL; kernel->signature = MagickSignature; if (kernel_string == (const char *) NULL) return(kernel); /* find end of this specific kernel definition string */ end = strchr(kernel_string, ';'); if ( end == (char *) NULL ) end = strchr(kernel_string, '\0'); /* clear flags - for Expanding kernel lists thorugh rotations */ flags = NoValue; /* Has a ':' in argument - New user kernel specification */ p = strchr(kernel_string, ':'); if ( p != (char *) NULL && p < end) { /* ParseGeometry() needs the geometry separated! -- Arrgghh */ memcpy(token, kernel_string, (size_t) (p-kernel_string)); token[p-kernel_string] = '\0'; SetGeometryInfo(&args); flags = ParseGeometry(token, &args); /* Size handling and checks of geometry settings */ if ( (flags & WidthValue) == 0 ) /* if no width then */ args.rho = args.sigma; /* then width = height */ if ( args.rho < 1.0 ) /* if width too small */ args.rho = 1.0; /* then width = 1 */ if ( args.sigma < 1.0 ) /* if height too small */ args.sigma = args.rho; /* then height = width */ kernel->width = (size_t)args.rho; kernel->height = (size_t)args.sigma; /* Offset Handling and Checks */ if ( args.xi < 0.0 || args.psi < 0.0 ) return(DestroyKernelInfo(kernel)); kernel->x = ((flags & XValue)!=0) ? (ssize_t)args.xi : (ssize_t) (kernel->width-1)/2; kernel->y = ((flags & YValue)!=0) ? (ssize_t)args.psi : (ssize_t) (kernel->height-1)/2; if ( kernel->x >= (ssize_t) kernel->width || kernel->y >= (ssize_t) kernel->height ) return(DestroyKernelInfo(kernel)); p++; /* advance beyond the ':' */ } else { /* ELSE - Old old specification, forming odd-square kernel */ /* count up number of values given */ p=(const char *) kernel_string; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\'')) p++; /* ignore "'" chars for convolve filter usage - Cristy */ for (i=0; p < end; i++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); } /* set the size of the kernel - old sized square */ kernel->width = kernel->height= (size_t) sqrt((double) i+1.0); kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; p=(const char *) kernel_string; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\'')) p++; /* ignore "'" chars for convolve filter usage - Cristy */ } /* Read in the kernel values from rest of input string argument */ kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); kernel->minimum = +MagickHuge; kernel->maximum = -MagickHuge; kernel->negative_range = kernel->positive_range = 0.0; for (i=0; (i < (ssize_t) (kernel->width*kernel->height)) && (p < end); i++) { GetMagickToken(p,&p,token); if (*token == ',') GetMagickToken(p,&p,token); if ( LocaleCompare("nan",token) == 0 || LocaleCompare("-",token) == 0 ) { kernel->values[i] = nan; /* do not include this value in kernel */ } else { kernel->values[i] = StringToDouble(token,(char **) NULL); ( kernel->values[i] < 0) ? ( kernel->negative_range += kernel->values[i] ) : ( kernel->positive_range += kernel->values[i] ); Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); } } /* sanity check -- no more values in kernel definition */ GetMagickToken(p,&p,token); if ( *token != '\0' && *token != ';' && *token != '\'' ) return(DestroyKernelInfo(kernel)); #if 0 /* this was the old method of handling a incomplete kernel */ if ( i < (ssize_t) (kernel->width*kernel->height) ) { Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); for ( ; i < (ssize_t) (kernel->width*kernel->height); i++) kernel->values[i]=0.0; } #else /* Number of values for kernel was not enough - Report Error */ if ( i < (ssize_t) (kernel->width*kernel->height) ) return(DestroyKernelInfo(kernel)); #endif /* check that we recieved at least one real (non-nan) value! */ if ( kernel->minimum == MagickHuge ) return(DestroyKernelInfo(kernel)); if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */ ExpandRotateKernelInfo(kernel, 45.0); /* cyclic rotate 3x3 kernels */ else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 90.0); /* 90 degree rotate of kernel */ else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */ ExpandMirrorKernelInfo(kernel); /* 90 degree mirror rotate */ return(kernel); } static KernelInfo *ParseKernelName(const char *kernel_string) { char token[MaxTextExtent]; const char *p, *end; GeometryInfo args; KernelInfo *kernel; MagickStatusType flags; ssize_t type; /* Parse special 'named' kernel */ GetMagickToken(kernel_string,&p,token); type=ParseCommandOption(MagickKernelOptions,MagickFalse,token); if ( type < 0 || type == UserDefinedKernel ) return((KernelInfo *)NULL); /* not a valid named kernel */ while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';')) p++; end = strchr(p, ';'); /* end of this kernel defintion */ if ( end == (char *) NULL ) end = strchr(p, '\0'); /* ParseGeometry() needs the geometry separated! -- Arrgghh */ memcpy(token, p, (size_t) (end-p)); token[end-p] = '\0'; SetGeometryInfo(&args); flags = ParseGeometry(token, &args); #if 0 /* For Debugging Geometry Input */ (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n", flags, args.rho, args.sigma, args.xi, args.psi ); #endif /* special handling of missing values in input string */ switch( type ) { /* Shape Kernel Defaults */ case UnityKernel: if ( (flags & WidthValue) == 0 ) args.rho = 1.0; /* Default scale = 1.0, zero is valid */ break; case SquareKernel: case DiamondKernel: case OctagonKernel: case DiskKernel: case PlusKernel: case CrossKernel: if ( (flags & HeightValue) == 0 ) args.sigma = 1.0; /* Default scale = 1.0, zero is valid */ break; case RingKernel: if ( (flags & XValue) == 0 ) args.xi = 1.0; /* Default scale = 1.0, zero is valid */ break; case RectangleKernel: /* Rectangle - set size defaults */ if ( (flags & WidthValue) == 0 ) /* if no width then */ args.rho = args.sigma; /* then width = height */ if ( args.rho < 1.0 ) /* if width too small */ args.rho = 3; /* then width = 3 */ if ( args.sigma < 1.0 ) /* if height too small */ args.sigma = args.rho; /* then height = width */ if ( (flags & XValue) == 0 ) /* center offset if not defined */ args.xi = (double)(((ssize_t)args.rho-1)/2); if ( (flags & YValue) == 0 ) args.psi = (double)(((ssize_t)args.sigma-1)/2); break; /* Distance Kernel Defaults */ case ChebyshevKernel: case ManhattanKernel: case OctagonalKernel: case EuclideanKernel: if ( (flags & HeightValue) == 0 ) /* no distance scale */ args.sigma = 100.0; /* default distance scaling */ else if ( (flags & AspectValue ) != 0 ) /* '!' flag */ args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */ else if ( (flags & PercentValue ) != 0 ) /* '%' flag */ args.sigma *= QuantumRange/100.0; /* percentage of color range */ break; default: break; } kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args); if ( kernel == (KernelInfo *) NULL ) return(kernel); /* global expand to rotated kernel list - only for single kernels */ if ( kernel->next == (KernelInfo *) NULL ) { if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 45.0); else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */ ExpandRotateKernelInfo(kernel, 90.0); else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */ ExpandMirrorKernelInfo(kernel); } return(kernel); } MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string) { KernelInfo *kernel, *new_kernel; char token[MaxTextExtent]; const char *p; size_t kernel_number; if (kernel_string == (const char *) NULL) return(ParseKernelArray(kernel_string)); p = kernel_string; kernel = NULL; kernel_number = 0; while ( GetMagickToken(p,NULL,token), *token != '\0' ) { /* ignore extra or multiple ';' kernel separators */ if ( *token != ';' ) { /* tokens starting with alpha is a Named kernel */ if (isalpha((int) *token) != 0) new_kernel = ParseKernelName(p); else /* otherwise a user defined kernel array */ new_kernel = ParseKernelArray(p); /* Error handling -- this is not proper error handling! */ if ( new_kernel == (KernelInfo *) NULL ) { (void) FormatLocaleFile(stderr, "Failed to parse kernel number #%.20g\n", (double) kernel_number); if ( kernel != (KernelInfo *) NULL ) kernel=DestroyKernelInfo(kernel); return((KernelInfo *) NULL); } /* initialise or append the kernel list */ if ( kernel == (KernelInfo *) NULL ) kernel = new_kernel; else LastKernelInfo(kernel)->next = new_kernel; } /* look for the next kernel in list */ p = strchr(p, ';'); if ( p == (char *) NULL ) break; p++; } return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e K e r n e l B u i l t I n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireKernelBuiltIn() returned one of the 'named' built-in types of % kernels used for special purposes such as gaussian blurring, skeleton % pruning, and edge distance determination. % % They take a KernelType, and a set of geometry style arguments, which were % typically decoded from a user supplied string, or from a more complex % Morphology Method that was requested. % % The format of the AcquireKernalBuiltIn method is: % % KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type, % const GeometryInfo args) % % A description of each parameter follows: % % o type: the pre-defined type of kernel wanted % % o args: arguments defining or modifying the kernel % % Convolution Kernels % % Unity % The a No-Op or Scaling single element kernel. % % Gaussian:{radius},{sigma} % Generate a two-dimensional gaussian kernel, as used by -gaussian. % The sigma for the curve is required. The resulting kernel is % normalized, % % If 'sigma' is zero, you get a single pixel on a field of zeros. % % NOTE: that the 'radius' is optional, but if provided can limit (clip) % the final size of the resulting kernel to a square 2*radius+1 in size. % The radius should be at least 2 times that of the sigma value, or % sever clipping and aliasing may result. If not given or set to 0 the % radius will be determined so as to produce the best minimal error % result, which is usally much larger than is normally needed. % % LoG:{radius},{sigma} % "Laplacian of a Gaussian" or "Mexician Hat" Kernel. % The supposed ideal edge detection, zero-summing kernel. % % An alturnative to this kernel is to use a "DoG" with a sigma ratio of % approx 1.6 (according to wikipedia). % % DoG:{radius},{sigma1},{sigma2} % "Difference of Gaussians" Kernel. % As "Gaussian" but with a gaussian produced by 'sigma2' subtracted % from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1. % The result is a zero-summing kernel. % % Blur:{radius},{sigma}[,{angle}] % Generates a 1 dimensional or linear gaussian blur, at the angle given % (current restricted to orthogonal angles). If a 'radius' is given the % kernel is clipped to a width of 2*radius+1. Kernel can be rotated % by a 90 degree angle. % % If 'sigma' is zero, you get a single pixel on a field of zeros. % % Note that two convolutions with two "Blur" kernels perpendicular to % each other, is equivalent to a far larger "Gaussian" kernel with the % same sigma value, However it is much faster to apply. This is how the % "-blur" operator actually works. % % Comet:{width},{sigma},{angle} % Blur in one direction only, much like how a bright object leaves % a comet like trail. The Kernel is actually half a gaussian curve, % Adding two such blurs in opposite directions produces a Blur Kernel. % Angle can be rotated in multiples of 90 degrees. % % Note that the first argument is the width of the kernel and not the % radius of the kernel. % % # Still to be implemented... % # % # Filter2D % # Filter1D % # Set kernel values using a resize filter, and given scale (sigma) % # Cylindrical or Linear. Is this possible with an image? % # % % Named Constant Convolution Kernels % % All these are unscaled, zero-summing kernels by default. As such for % non-HDRI version of ImageMagick some form of normalization, user scaling, % and biasing the results is recommended, to prevent the resulting image % being 'clipped'. % % The 3x3 kernels (most of these) can be circularly rotated in multiples of % 45 degrees to generate the 8 angled varients of each of the kernels. % % Laplacian:{type} % Discrete Lapacian Kernels, (without normalization) % Type 0 : 3x3 with center:8 surounded by -1 (8 neighbourhood) % Type 1 : 3x3 with center:4 edge:-1 corner:0 (4 neighbourhood) % Type 2 : 3x3 with center:4 edge:1 corner:-2 % Type 3 : 3x3 with center:4 edge:-2 corner:1 % Type 5 : 5x5 laplacian % Type 7 : 7x7 laplacian % Type 15 : 5x5 LoG (sigma approx 1.4) % Type 19 : 9x9 LoG (sigma approx 1.4) % % Sobel:{angle} % Sobel 'Edge' convolution kernel (3x3) % | -1, 0, 1 | % | -2, 0,-2 | % | -1, 0, 1 | % % Roberts:{angle} % Roberts convolution kernel (3x3) % | 0, 0, 0 | % | -1, 1, 0 | % | 0, 0, 0 | % % Prewitt:{angle} % Prewitt Edge convolution kernel (3x3) % | -1, 0, 1 | % | -1, 0, 1 | % | -1, 0, 1 | % % Compass:{angle} % Prewitt's "Compass" convolution kernel (3x3) % | -1, 1, 1 | % | -1,-2, 1 | % | -1, 1, 1 | % % Kirsch:{angle} % Kirsch's "Compass" convolution kernel (3x3) % | -3,-3, 5 | % | -3, 0, 5 | % | -3,-3, 5 | % % FreiChen:{angle} % Frei-Chen Edge Detector is based on a kernel that is similar to % the Sobel Kernel, but is designed to be isotropic. That is it takes % into account the distance of the diagonal in the kernel. % % | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | % | 1, 0, -1 | % % FreiChen:{type},{angle} % % Frei-Chen Pre-weighted kernels... % % Type 0: default un-nomalized version shown above. % % Type 1: Orthogonal Kernel (same as type 11 below) % | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 1, 0, -1 | % % Type 2: Diagonal form of Kernel... % | 1, sqrt(2), 0 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 0, -sqrt(2) -1 | % % However this kernel is als at the heart of the FreiChen Edge Detection % Process which uses a set of 9 specially weighted kernel. These 9 % kernels not be normalized, but directly applied to the image. The % results is then added together, to produce the intensity of an edge in % a specific direction. The square root of the pixel value can then be % taken as the cosine of the edge, and at least 2 such runs at 90 degrees % from each other, both the direction and the strength of the edge can be % determined. % % Type 10: All 9 of the following pre-weighted kernels... % % Type 11: | 1, 0, -1 | % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2) % | 1, 0, -1 | % % Type 12: | 1, sqrt(2), 1 | % | 0, 0, 0 | / 2*sqrt(2) % | 1, sqrt(2), 1 | % % Type 13: | sqrt(2), -1, 0 | % | -1, 0, 1 | / 2*sqrt(2) % | 0, 1, -sqrt(2) | % % Type 14: | 0, 1, -sqrt(2) | % | -1, 0, 1 | / 2*sqrt(2) % | sqrt(2), -1, 0 | % % Type 15: | 0, -1, 0 | % | 1, 0, 1 | / 2 % | 0, -1, 0 | % % Type 16: | 1, 0, -1 | % | 0, 0, 0 | / 2 % | -1, 0, 1 | % % Type 17: | 1, -2, 1 | % | -2, 4, -2 | / 6 % | -1, -2, 1 | % % Type 18: | -2, 1, -2 | % | 1, 4, 1 | / 6 % | -2, 1, -2 | % % Type 19: | 1, 1, 1 | % | 1, 1, 1 | / 3 % | 1, 1, 1 | % % The first 4 are for edge detection, the next 4 are for line detection % and the last is to add a average component to the results. % % Using a special type of '-1' will return all 9 pre-weighted kernels % as a multi-kernel list, so that you can use them directly (without % normalization) with the special "-set option:morphology:compose Plus" % setting to apply the full FreiChen Edge Detection Technique. % % If 'type' is large it will be taken to be an actual rotation angle for % the default FreiChen (type 0) kernel. As such FreiChen:45 will look % like a Sobel:45 but with 'sqrt(2)' instead of '2' values. % % WARNING: The above was layed out as per % http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf % But rotated 90 degrees so direction is from left rather than the top. % I have yet to find any secondary confirmation of the above. The only % other source found was actual source code at % http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf % Neigher paper defineds the kernels in a way that looks locical or % correct when taken as a whole. % % Boolean Kernels % % Diamond:[{radius}[,{scale}]] % Generate a diamond shaped kernel with given radius to the points. % Kernel size will again be radius*2+1 square and defaults to radius 1, % generating a 3x3 kernel that is slightly larger than a square. % % Square:[{radius}[,{scale}]] % Generate a square shaped kernel of size radius*2+1, and defaulting % to a 3x3 (radius 1). % % Octagon:[{radius}[,{scale}]] % Generate octagonal shaped kernel of given radius and constant scale. % Default radius is 3 producing a 7x7 kernel. A radius of 1 will result % in "Diamond" kernel. % % Disk:[{radius}[,{scale}]] % Generate a binary disk, thresholded at the radius given, the radius % may be a float-point value. Final Kernel size is floor(radius)*2+1 % square. A radius of 5.3 is the default. % % NOTE: That a low radii Disk kernels produce the same results as % many of the previously defined kernels, but differ greatly at larger % radii. Here is a table of equivalences... % "Disk:1" => "Diamond", "Octagon:1", or "Cross:1" % "Disk:1.5" => "Square" % "Disk:2" => "Diamond:2" % "Disk:2.5" => "Octagon" % "Disk:2.9" => "Square:2" % "Disk:3.5" => "Octagon:3" % "Disk:4.5" => "Octagon:4" % "Disk:5.4" => "Octagon:5" % "Disk:6.4" => "Octagon:6" % All other Disk shapes are unique to this kernel, but because a "Disk" % is more circular when using a larger radius, using a larger radius is % preferred over iterating the morphological operation. % % Rectangle:{geometry} % Simply generate a rectangle of 1's with the size given. You can also % specify the location of the 'control point', otherwise the closest % pixel to the center of the rectangle is selected. % % Properly centered and odd sized rectangles work the best. % % Symbol Dilation Kernels % % These kernel is not a good general morphological kernel, but is used % more for highlighting and marking any single pixels in an image using, % a "Dilate" method as appropriate. % % For the same reasons iterating these kernels does not produce the % same result as using a larger radius for the symbol. % % Plus:[{radius}[,{scale}]] % Cross:[{radius}[,{scale}]] % Generate a kernel in the shape of a 'plus' or a 'cross' with % a each arm the length of the given radius (default 2). % % NOTE: "plus:1" is equivalent to a "Diamond" kernel. % % Ring:{radius1},{radius2}[,{scale}] % A ring of the values given that falls between the two radii. % Defaults to a ring of approximataly 3 radius in a 7x7 kernel. % This is the 'edge' pixels of the default "Disk" kernel, % More specifically, "Ring" -> "Ring:2.5,3.5,1.0" % % Hit and Miss Kernels % % Peak:radius1,radius2 % Find any peak larger than the pixels the fall between the two radii. % The default ring of pixels is as per "Ring". % Edges % Find flat orthogonal edges of a binary shape % Corners % Find 90 degree corners of a binary shape % Diagonals:type % A special kernel to thin the 'outside' of diagonals % LineEnds:type % Find end points of lines (for pruning a skeletion) % Two types of lines ends (default to both) can be searched for % Type 0: All line ends % Type 1: single kernel for 4-conneected line ends % Type 2: single kernel for simple line ends % LineJunctions % Find three line junctions (within a skeletion) % Type 0: all line junctions % Type 1: Y Junction kernel % Type 2: Diagonal T Junction kernel % Type 3: Orthogonal T Junction kernel % Type 4: Diagonal X Junction kernel % Type 5: Orthogonal + Junction kernel % Ridges:type % Find single pixel ridges or thin lines % Type 1: Fine single pixel thick lines and ridges % Type 2: Find two pixel thick lines and ridges % ConvexHull % Octagonal Thickening Kernel, to generate convex hulls of 45 degrees % Skeleton:type % Traditional skeleton generating kernels. % Type 1: Tradional Skeleton kernel (4 connected skeleton) % Type 2: HIPR2 Skeleton kernel (8 connected skeleton) % Type 3: Thinning skeleton based on a ressearch paper by % Dan S. Bloomberg (Default Type) % ThinSE:type % A huge variety of Thinning Kernels designed to preserve conectivity. % many other kernel sets use these kernels as source definitions. % Type numbers are 41-49, 81-89, 481, and 482 which are based on % the super and sub notations used in the source research paper. % % Distance Measuring Kernels % % Different types of distance measuring methods, which are used with the % a 'Distance' morphology method for generating a gradient based on % distance from an edge of a binary shape, though there is a technique % for handling a anti-aliased shape. % % See the 'Distance' Morphological Method, for information of how it is % applied. % % Chebyshev:[{radius}][x{scale}[%!]] % Chebyshev Distance (also known as Tchebychev or Chessboard distance) % is a value of one to any neighbour, orthogonal or diagonal. One why % of thinking of it is the number of squares a 'King' or 'Queen' in % chess needs to traverse reach any other position on a chess board. % It results in a 'square' like distance function, but one where % diagonals are given a value that is closer than expected. % % Manhattan:[{radius}][x{scale}[%!]] % Manhattan Distance (also known as Rectilinear, City Block, or the Taxi % Cab distance metric), it is the distance needed when you can only % travel in horizontal or vertical directions only. It is the % distance a 'Rook' in chess would have to travel, and results in a % diamond like distances, where diagonals are further than expected. % % Octagonal:[{radius}][x{scale}[%!]] % An interleving of Manhatten and Chebyshev metrics producing an % increasing octagonally shaped distance. Distances matches those of % the "Octagon" shaped kernel of the same radius. The minimum radius % and default is 2, producing a 5x5 kernel. % % Euclidean:[{radius}][x{scale}[%!]] % Euclidean distance is the 'direct' or 'as the crow flys' distance. % However by default the kernel size only has a radius of 1, which % limits the distance to 'Knight' like moves, with only orthogonal and % diagonal measurements being correct. As such for the default kernel % you will get octagonal like distance function. % % However using a larger radius such as "Euclidean:4" you will get a % much smoother distance gradient from the edge of the shape. Especially % if the image is pre-processed to include any anti-aliasing pixels. % Of course a larger kernel is slower to use, and not always needed. % % The first three Distance Measuring Kernels will only generate distances % of exact multiples of {scale} in binary images. As such you can use a % scale of 1 without loosing any information. However you also need some % scaling when handling non-binary anti-aliased shapes. % % The "Euclidean" Distance Kernel however does generate a non-integer % fractional results, and as such scaling is vital even for binary shapes. % */ MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type, const GeometryInfo *args) { KernelInfo *kernel; register ssize_t i; register ssize_t u, v; double nan = sqrt((double)-1.0); /* Special Value : Not A Number */ /* Generate a new empty kernel if needed */ kernel=(KernelInfo *) NULL; switch(type) { case UndefinedKernel: /* These should not call this function */ case UserDefinedKernel: assert("Should not call this function" != (char *)NULL); break; case LaplacianKernel: /* Named Descrete Convolution Kernels */ case SobelKernel: /* these are defined using other kernels */ case RobertsKernel: case PrewittKernel: case CompassKernel: case KirschKernel: case FreiChenKernel: case EdgesKernel: /* Hit and Miss kernels */ case CornersKernel: case DiagonalsKernel: case LineEndsKernel: case LineJunctionsKernel: case RidgesKernel: case ConvexHullKernel: case SkeletonKernel: case ThinSEKernel: break; /* A pre-generated kernel is not needed */ #if 0 /* set to 1 to do a compile-time check that we haven't missed anything */ case UnityKernel: case GaussianKernel: case DoGKernel: case LoGKernel: case BlurKernel: case CometKernel: case DiamondKernel: case SquareKernel: case RectangleKernel: case OctagonKernel: case DiskKernel: case PlusKernel: case CrossKernel: case RingKernel: case PeaksKernel: case ChebyshevKernel: case ManhattanKernel: case OctangonalKernel: case EuclideanKernel: #else default: #endif /* Generate the base Kernel Structure */ kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (kernel == (KernelInfo *) NULL) return(kernel); (void) ResetMagickMemory(kernel,0,sizeof(*kernel)); kernel->minimum = kernel->maximum = kernel->angle = 0.0; kernel->negative_range = kernel->positive_range = 0.0; kernel->type = type; kernel->next = (KernelInfo *) NULL; kernel->signature = MagickSignature; break; } switch(type) { /* Convolution Kernels */ case UnityKernel: { kernel->height = kernel->width = (size_t) 1; kernel->x = kernel->y = (ssize_t) 0; kernel->values=(double *) AcquireAlignedMemory(1, sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); kernel->maximum = kernel->values[0] = args->rho; break; } break; case GaussianKernel: case DoGKernel: case LoGKernel: { double sigma = fabs(args->sigma), sigma2 = fabs(args->xi), A, B, R; if ( args->rho >= 1.0 ) kernel->width = (size_t)args->rho*2+1; else if ( (type != DoGKernel) || (sigma >= sigma2) ) kernel->width = GetOptimalKernelWidth2D(args->rho,sigma); else kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2); kernel->height = kernel->width; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* WARNING: The following generates a 'sampled gaussian' kernel. * What we really want is a 'discrete gaussian' kernel. * * How to do this is I don't know, but appears to be basied on the * Error Function 'erf()' (intergral of a gaussian) */ if ( type == GaussianKernel || type == DoGKernel ) { /* Calculate a Gaussian, OR positive half of a DoG */ if ( sigma > MagickEpsilon ) { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ B = (double) (1.0/(Magick2PI*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B; } else /* limiting case - a unity (normalized Dirac) kernel */ { (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(double)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } } if ( type == DoGKernel ) { /* Subtract a Negative Gaussian for "Difference of Gaussian" */ if ( sigma2 > MagickEpsilon ) { sigma = sigma2; /* simplify loop expressions */ A = 1.0/(2.0*sigma*sigma); B = (double) (1.0/(Magick2PI*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B; } else /* limiting case - a unity (normalized Dirac) kernel */ kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0; } if ( type == LoGKernel ) { /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */ if ( sigma > MagickEpsilon ) { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ B = (double) (1.0/(MagickPI*sigma*sigma*sigma*sigma)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { R = ((double)(u*u+v*v))*A; kernel->values[i] = (1-R)*exp(-R)*B; } } else /* special case - generate a unity kernel */ { (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(double)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } } /* Note the above kernels may have been 'clipped' by a user defined ** radius, producing a smaller (darker) kernel. Also for very small ** sigma's (> 0.1) the central value becomes larger than one, and thus ** producing a very bright kernel. ** ** Normalization will still be needed. */ /* Normalize the 2D Gaussian Kernel ** ** NB: a CorrelateNormalize performs a normal Normalize if ** there are no negative values. */ CalcKernelMetaData(kernel); /* the other kernel meta-data */ ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue); break; } case BlurKernel: { double sigma = fabs(args->sigma), alpha, beta; if ( args->rho >= 1.0 ) kernel->width = (size_t)args->rho*2+1; else kernel->width = GetOptimalKernelWidth1D(args->rho,sigma); kernel->height = 1; kernel->x = (ssize_t) (kernel->width-1)/2; kernel->y = 0; kernel->negative_range = kernel->positive_range = 0.0; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); #if 1 #define KernelRank 3 /* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix). ** It generates a gaussian 3 times the width, and compresses it into ** the expected range. This produces a closer normalization of the ** resulting kernel, especially for very low sigma values. ** As such while wierd it is prefered. ** ** I am told this method originally came from Photoshop. ** ** A properly normalized curve is generated (apart from edge clipping) ** even though we later normalize the result (for edge clipping) ** to allow the correct generation of a "Difference of Blurs". */ /* initialize */ v = (ssize_t) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */ (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(double)); /* Calculate a Positive 1D Gaussian */ if ( sigma > MagickEpsilon ) { sigma *= KernelRank; /* simplify loop expressions */ alpha = 1.0/(2.0*sigma*sigma); beta= (double) (1.0/(MagickSQ2PI*sigma )); for ( u=-v; u <= v; u++) { kernel->values[(u+v)/KernelRank] += exp(-((double)(u*u))*alpha)*beta; } } else /* special case - generate a unity kernel */ kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; #else /* Direct calculation without curve averaging */ /* Calculate a Positive Gaussian */ if ( sigma > MagickEpsilon ) { alpha = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */ beta = 1.0/(MagickSQ2PI*sigma); for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = exp(-((double)(u*u))*alpha)*beta; } else /* special case - generate a unity kernel */ { (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(double)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; } #endif /* Note the above kernel may have been 'clipped' by a user defined ** radius, producing a smaller (darker) kernel. Also for very small ** sigma's (> 0.1) the central value becomes larger than one, and thus ** producing a very bright kernel. ** ** Normalization will still be needed. */ /* Normalize the 1D Gaussian Kernel ** ** NB: a CorrelateNormalize performs a normal Normalize if ** there are no negative values. */ CalcKernelMetaData(kernel); /* the other kernel meta-data */ ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue); /* rotate the 1D kernel by given angle */ RotateKernelInfo(kernel, args->xi ); break; } case CometKernel: { double sigma = fabs(args->sigma), A; if ( args->rho < 1.0 ) kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1; else kernel->width = (size_t)args->rho; kernel->x = kernel->y = 0; kernel->height = 1; kernel->negative_range = kernel->positive_range = 0.0; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* A comet blur is half a 1D gaussian curve, so that the object is ** blurred in one direction only. This may not be quite the right ** curve to use so may change in the future. The function must be ** normalised after generation, which also resolves any clipping. ** ** As we are normalizing and not subtracting gaussians, ** there is no need for a divisor in the gaussian formula ** ** It is less comples */ if ( sigma > MagickEpsilon ) { #if 1 #define KernelRank 3 v = (ssize_t) kernel->width*KernelRank; /* start/end points */ (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*sizeof(double)); sigma *= KernelRank; /* simplify the loop expression */ A = 1.0/(2.0*sigma*sigma); /* B = 1.0/(MagickSQ2PI*sigma); */ for ( u=0; u < v; u++) { kernel->values[u/KernelRank] += exp(-((double)(u*u))*A); /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */ } for (i=0; i < (ssize_t) kernel->width; i++) kernel->positive_range += kernel->values[i]; #else A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */ /* B = 1.0/(MagickSQ2PI*sigma); */ for ( i=0; i < (ssize_t) kernel->width; i++) kernel->positive_range += kernel->values[i] = exp(-((double)(i*i))*A); /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */ #endif } else /* special case - generate a unity kernel */ { (void) ResetMagickMemory(kernel->values,0, (size_t) kernel->width*kernel->height*sizeof(double)); kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; kernel->positive_range = 1.0; } kernel->minimum = 0.0; kernel->maximum = kernel->values[0]; kernel->negative_range = 0.0; ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */ RotateKernelInfo(kernel, args->xi); /* Rotate by angle */ break; } /* Convolution Kernels - Well Known Named Constant Kernels */ case LaplacianKernel: { switch ( (int) args->rho ) { case 0: default: /* laplacian square filter -- default */ kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1"); break; case 1: /* laplacian diamond filter */ kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0"); break; case 2: kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2"); break; case 3: kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1"); break; case 5: /* a 5x5 laplacian */ kernel=ParseKernelArray( "5: -4,-1,0,-1,-4 -1,2,3,2,-1 0,3,4,3,0 -1,2,3,2,-1 -4,-1,0,-1,-4"); break; case 7: /* a 7x7 laplacian */ kernel=ParseKernelArray( "7:-10,-5,-2,-1,-2,-5,-10 -5,0,3,4,3,0,-5 -2,3,6,7,6,3,-2 -1,4,7,8,7,4,-1 -2,3,6,7,6,3,-2 -5,0,3,4,3,0,-5 -10,-5,-2,-1,-2,-5,-10" ); break; case 15: /* a 5x5 LoG (sigma approx 1.4) */ kernel=ParseKernelArray( "5: 0,0,-1,0,0 0,-1,-2,-1,0 -1,-2,16,-2,-1 0,-1,-2,-1,0 0,0,-1,0,0"); break; case 19: /* a 9x9 LoG (sigma approx 1.4) */ /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */ kernel=ParseKernelArray( "9: 0,-1,-1,-2,-2,-2,-1,-1,0 -1,-2,-4,-5,-5,-5,-4,-2,-1 -1,-4,-5,-3,-0,-3,-5,-4,-1 -2,-5,-3,12,24,12,-3,-5,-2 -2,-5,-0,24,40,24,-0,-5,-2 -2,-5,-3,12,24,12,-3,-5,-2 -1,-4,-5,-3,-0,-3,-5,-4,-1 -1,-2,-4,-5,-5,-5,-4,-2,-1 0,-1,-1,-2,-2,-2,-1,-1,0"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; break; } case SobelKernel: { /* Simple Sobel Kernel */ kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case RobertsKernel: { kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case PrewittKernel: { kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case CompassKernel: { kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case KirschKernel: { kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->rho); break; } case FreiChenKernel: /* Direction is set to be left to right positive */ /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */ /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */ { switch ( (int) args->rho ) { default: case 0: kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[3] = +MagickSQ2; kernel->values[5] = -MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ break; case 2: kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[1] = kernel->values[3] = +MagickSQ2; kernel->values[5] = kernel->values[7] = -MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 10: kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19"); if (kernel == (KernelInfo *) NULL) return(kernel); break; case 1: case 11: kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[3] = +MagickSQ2; kernel->values[5] = -MagickSQ2; CalcKernelMetaData(kernel); /* recalculate meta-data */ ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 12: kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[1] = +MagickSQ2; kernel->values[7] = +MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 13: kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[0] = +MagickSQ2; kernel->values[8] = -MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 14: kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->values[2] = -MagickSQ2; kernel->values[6] = +MagickSQ2; CalcKernelMetaData(kernel); ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue); break; case 15: kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/2.0, NoValue); break; case 16: kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/2.0, NoValue); break; case 17: kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/6.0, NoValue); break; case 18: kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/6.0, NoValue); break; case 19: kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ScaleKernelInfo(kernel, 1.0/3.0, NoValue); break; } if ( fabs(args->sigma) > MagickEpsilon ) /* Rotate by correctly supplied 'angle' */ RotateKernelInfo(kernel, args->sigma); else if ( args->rho > 30.0 || args->rho < -30.0 ) /* Rotate by out of bounds 'type' */ RotateKernelInfo(kernel, args->rho); break; } /* Boolean or Shaped Kernels */ case DiamondKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values within diamond area to scale given */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case SquareKernel: case RectangleKernel: { double scale; if ( type == SquareKernel ) { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = (size_t) (2*args->rho+1); kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; scale = args->sigma; } else { /* NOTE: user defaults set in "AcquireKernelInfo()" */ if ( args->rho < 1.0 || args->sigma < 1.0 ) return(DestroyKernelInfo(kernel)); /* invalid args given */ kernel->width = (size_t)args->rho; kernel->height = (size_t)args->sigma; if ( args->xi < 0.0 || args->xi > (double)kernel->width || args->psi < 0.0 || args->psi > (double)kernel->height ) return(DestroyKernelInfo(kernel)); /* invalid args given */ kernel->x = (ssize_t) args->xi; kernel->y = (ssize_t) args->psi; scale = 1.0; } kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values to scale given */ u=(ssize_t) (kernel->width*kernel->height); for ( i=0; i < u; i++) kernel->values[i] = scale; kernel->minimum = kernel->maximum = scale; /* a flat shape */ kernel->positive_range = scale*u; break; } case OctagonKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius = 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ( (labs((long) u)+labs((long) v)) <= ((long)kernel->x + (long)(kernel->x/2)) ) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case DiskKernel: { ssize_t limit = (ssize_t)(args->rho*args->rho); if (args->rho < 0.4) /* default radius approx 4.3 */ kernel->width = kernel->height = 9L, limit = 18L; else kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) if ((u*u+v*v) <= limit) kernel->positive_range += kernel->values[i] = args->sigma; else kernel->values[i] = nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ break; } case PlusKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values along axises to given scale */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0); break; } case CrossKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 5; /* default radius 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set all kernel values along axises to given scale */ for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->values[i] = (u == v || u == -v) ? args->sigma : nan; kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */ kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0); break; } /* HitAndMiss Kernels */ case RingKernel: case PeaksKernel: { ssize_t limit1, limit2, scale; if (args->rho < args->sigma) { kernel->width = ((size_t)args->sigma)*2+1; limit1 = (ssize_t)(args->rho*args->rho); limit2 = (ssize_t)(args->sigma*args->sigma); } else { kernel->width = ((size_t)args->rho)*2+1; limit1 = (ssize_t)(args->sigma*args->sigma); limit2 = (ssize_t)(args->rho*args->rho); } if ( limit2 <= 0 ) kernel->width = 7L, limit1 = 7L, limit2 = 11L; kernel->height = kernel->width; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */ scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi); for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { ssize_t radius=u*u+v*v; if (limit1 < radius && radius <= limit2) kernel->positive_range += kernel->values[i] = (double) scale; else kernel->values[i] = nan; } kernel->minimum = kernel->maximum = (double) scale; if ( type == PeaksKernel ) { /* set the central point in the middle */ kernel->values[kernel->x+kernel->y*kernel->width] = 1.0; kernel->positive_range = 1.0; kernel->maximum = 1.0; } break; } case EdgesKernel: { kernel=AcquireKernelInfo("ThinSE:482"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandMirrorKernelInfo(kernel); /* mirror expansion of kernels */ break; } case CornersKernel: { kernel=AcquireKernelInfo("ThinSE:87"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */ break; } case DiagonalsKernel: { switch ( (int) args->rho ) { case 0: default: { KernelInfo *new_kernel; kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; new_kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; ExpandMirrorKernelInfo(kernel); return(kernel); } case 1: kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-"); break; case 2: kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case LineEndsKernel: { /* Kernels for finding the end of thin lines */ switch ( (int) args->rho ) { case 0: default: /* set of kernels to find all end of lines */ return(AcquireKernelInfo("LineEnds:1>;LineEnds:2>")); case 1: /* kernel for 4-connected line ends - no rotation */ kernel=ParseKernelArray("3: 0,0,- 0,1,1 0,0,-"); break; case 2: /* kernel to add for 8-connected lines - no rotation */ kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1"); break; case 3: /* kernel to add for orthogonal line ends - does not find corners */ kernel=ParseKernelArray("3: 0,0,0 0,1,1 0,0,0"); break; case 4: /* traditional line end - fails on last T end */ kernel=ParseKernelArray("3: 0,0,0 0,1,- 0,0,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case LineJunctionsKernel: { /* kernels for finding the junctions of multiple lines */ switch ( (int) args->rho ) { case 0: default: /* set of kernels to find all line junctions */ return(AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>")); case 1: /* Y Junction */ kernel=ParseKernelArray("3: 1,-,1 -,1,- -,1,-"); break; case 2: /* Diagonal T Junctions */ kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1"); break; case 3: /* Orthogonal T Junctions */ kernel=ParseKernelArray("3: -,-,- 1,1,1 -,1,-"); break; case 4: /* Diagonal X Junctions */ kernel=ParseKernelArray("3: 1,-,1 -,1,- 1,-,1"); break; case 5: /* Orthogonal X Junctions - minimal diamond kernel */ kernel=ParseKernelArray("3: -,1,- 1,1,1 -,1,-"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } case RidgesKernel: { /* Ridges - Ridge finding kernels */ KernelInfo *new_kernel; switch ( (int) args->rho ) { case 1: default: kernel=ParseKernelArray("3x1:0,1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */ break; case 2: kernel=ParseKernelArray("4x1:0,1,1,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */ /* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */ /* Unfortunatally we can not yet rotate a non-square kernel */ /* But then we can't flip a non-symetrical kernel either */ new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; LastKernelInfo(kernel)->next = new_kernel; break; } break; } case ConvexHullKernel: { KernelInfo *new_kernel; /* first set of 8 kernels */ kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* append the mirror versions too - no flip function yet */ new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0"); if (new_kernel == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); new_kernel->type = type; ExpandRotateKernelInfo(new_kernel, 90.0); LastKernelInfo(kernel)->next = new_kernel; break; } case SkeletonKernel: { switch ( (int) args->rho ) { case 1: default: /* Traditional Skeleton... ** A cyclically rotated single kernel */ kernel=AcquireKernelInfo("ThinSE:482"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */ break; case 2: /* HIPR Variation of the cyclic skeleton ** Corners of the traditional method made more forgiving, ** but the retain the same cyclic order. */ kernel=AcquireKernelInfo("ThinSE:482; ThinSE:87x90;"); if (kernel == (KernelInfo *) NULL) return(kernel); if (kernel->next == (KernelInfo *) NULL) return(DestroyKernelInfo(kernel)); kernel->type = type; kernel->next->type = type; ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */ break; case 3: /* Dan Bloomberg Skeleton, from his paper on 3x3 thinning SE's ** "Connectivity-Preserving Morphological Image Thransformations" ** by Dan S. Bloomberg, available on Leptonica, Selected Papers, ** http://www.leptonica.com/papers/conn.pdf */ kernel=AcquireKernelInfo( "ThinSE:41; ThinSE:42; ThinSE:43"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; kernel->next->type = type; kernel->next->next->type = type; ExpandMirrorKernelInfo(kernel); /* 12 kernels total */ break; } break; } case ThinSEKernel: { /* Special kernels for general thinning, while preserving connections ** "Connectivity-Preserving Morphological Image Thransformations" ** by Dan S. Bloomberg, available on Leptonica, Selected Papers, ** http://www.leptonica.com/papers/conn.pdf ** And ** http://tpgit.github.com/Leptonica/ccthin_8c_source.html ** ** Note kernels do not specify the origin pixel, allowing them ** to be used for both thickening and thinning operations. */ switch ( (int) args->rho ) { /* SE for 4-connected thinning */ case 41: /* SE_4_1 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 -,-,1"); break; case 42: /* SE_4_2 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 -,0,-"); break; case 43: /* SE_4_3 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,-,1"); break; case 44: /* SE_4_4 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,-"); break; case 45: /* SE_4_5 */ kernel=ParseKernelArray("3: -,0,1 0,-,1 -,0,-"); break; case 46: /* SE_4_6 */ kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,1"); break; case 47: /* SE_4_7 */ kernel=ParseKernelArray("3: -,1,1 0,-,1 -,0,-"); break; case 48: /* SE_4_8 */ kernel=ParseKernelArray("3: -,-,1 0,-,1 0,-,1"); break; case 49: /* SE_4_9 */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 -,-,1"); break; /* SE for 8-connected thinning - negatives of the above */ case 81: /* SE_8_0 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 -,1,-"); break; case 82: /* SE_8_2 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,-,-"); break; case 83: /* SE_8_3 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 -,1,-"); break; case 84: /* SE_8_4 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,-"); break; case 85: /* SE_8_5 */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,-"); break; case 86: /* SE_8_6 */ kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,1"); break; case 87: /* SE_8_7 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,0,-"); break; case 88: /* SE_8_8 */ kernel=ParseKernelArray("3: -,1,- 0,-,1 0,1,-"); break; case 89: /* SE_8_9 */ kernel=ParseKernelArray("3: 0,1,- 0,-,1 -,1,-"); break; /* Special combined SE kernels */ case 423: /* SE_4_2 , SE_4_3 Combined Kernel */ kernel=ParseKernelArray("3: -,-,1 0,-,- -,0,-"); break; case 823: /* SE_8_2 , SE_8_3 Combined Kernel */ kernel=ParseKernelArray("3: -,1,- -,-,1 0,-,-"); break; case 481: /* SE_48_1 - General Connected Corner Kernel */ kernel=ParseKernelArray("3: -,1,1 0,-,1 0,0,-"); break; default: case 482: /* SE_48_2 - General Edge Kernel */ kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,1"); break; } if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = type; RotateKernelInfo(kernel, args->sigma); break; } /* Distance Measuring Kernels */ case ChebyshevKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*MagickMax(fabs((double)u),fabs((double)v)) ); kernel->maximum = kernel->values[0]; break; } case ManhattanKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*(labs((long) u)+labs((long) v)) ); kernel->maximum = kernel->values[0]; break; } case OctagonalKernel: { if (args->rho < 2.0) kernel->width = kernel->height = 5; /* default/minimum radius = 2 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) { double r1 = MagickMax(fabs((double)u),fabs((double)v)), r2 = floor((double)(labs((long)u)+labs((long)v)+1)/1.5); kernel->positive_range += kernel->values[i] = args->sigma*MagickMax(r1,r2); } kernel->maximum = kernel->values[0]; break; } case EuclideanKernel: { if (args->rho < 1.0) kernel->width = kernel->height = 3; /* default radius = 1 */ else kernel->width = kernel->height = ((size_t)args->rho)*2+1; kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2; kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (kernel->values == (double *) NULL) return(DestroyKernelInfo(kernel)); for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++) for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++) kernel->positive_range += ( kernel->values[i] = args->sigma*sqrt((double)(u*u+v*v)) ); kernel->maximum = kernel->values[0]; break; } default: { /* No-Op Kernel - Basically just a single pixel on its own */ kernel=ParseKernelArray("1:1"); if (kernel == (KernelInfo *) NULL) return(kernel); kernel->type = UndefinedKernel; break; } break; } return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneKernelInfo() creates a new clone of the given Kernel List so that its % can be modified without effecting the original. The cloned kernel should % be destroyed using DestoryKernelInfo() when no longer needed. % % The format of the CloneKernelInfo method is: % % KernelInfo *CloneKernelInfo(const KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to be cloned % */ MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel) { register ssize_t i; KernelInfo *new_kernel; assert(kernel != (KernelInfo *) NULL); new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel)); if (new_kernel == (KernelInfo *) NULL) return(new_kernel); *new_kernel=(*kernel); /* copy values in structure */ /* replace the values with a copy of the values */ new_kernel->values=(double *) AcquireAlignedMemory(kernel->width, kernel->height*sizeof(*kernel->values)); if (new_kernel->values == (double *) NULL) return(DestroyKernelInfo(new_kernel)); for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++) new_kernel->values[i]=kernel->values[i]; /* Also clone the next kernel in the kernel list */ if ( kernel->next != (KernelInfo *) NULL ) { new_kernel->next = CloneKernelInfo(kernel->next); if ( new_kernel->next == (KernelInfo *) NULL ) return(DestroyKernelInfo(new_kernel)); } return(new_kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyKernelInfo() frees the memory used by a Convolution/Morphology % kernel. % % The format of the DestroyKernelInfo method is: % % KernelInfo *DestroyKernelInfo(KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to be destroyed % */ MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel) { assert(kernel != (KernelInfo *) NULL); if ( kernel->next != (KernelInfo *) NULL ) kernel->next=DestroyKernelInfo(kernel->next); kernel->values=(double *)RelinquishAlignedMemory(kernel->values); kernel=(KernelInfo *) RelinquishMagickMemory(kernel); return(kernel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d M i r r o r K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandMirrorKernelInfo() takes a single kernel, and expands it into a % sequence of 90-degree rotated kernels but providing a reflected 180 % rotatation, before the -/+ 90-degree rotations. % % This special rotation order produces a better, more symetrical thinning of % objects. % % The format of the ExpandMirrorKernelInfo method is: % % void ExpandMirrorKernelInfo(KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % This function is only internel to this module, as it is not finalized, % especially with regard to non-orthogonal angles, and rotation of larger % 2D kernels. */ #if 0 static void FlopKernelInfo(KernelInfo *kernel) { /* Do a Flop by reversing each row. */ size_t y; register ssize_t x,r; register double *k,t; for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width) for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--) t=k[x], k[x]=k[r], k[r]=t; kernel->x = kernel->width - kernel->x - 1; angle = fmod(angle+180.0, 360.0); } #endif static void ExpandMirrorKernelInfo(KernelInfo *kernel) { KernelInfo *clone, *last; last = kernel; clone = CloneKernelInfo(last); RotateKernelInfo(clone, 180); /* flip */ LastKernelInfo(last)->next = clone; last = clone; clone = CloneKernelInfo(last); RotateKernelInfo(clone, 90); /* transpose */ LastKernelInfo(last)->next = clone; last = clone; clone = CloneKernelInfo(last); RotateKernelInfo(clone, 180); /* flop */ LastKernelInfo(last)->next = clone; return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d R o t a t e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating % incrementally by the angle given, until the kernel repeats. % % WARNING: 45 degree rotations only works for 3x3 kernels. % While 90 degree roatations only works for linear and square kernels % % The format of the ExpandRotateKernelInfo method is: % % void ExpandRotateKernelInfo(KernelInfo *kernel, double angle) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o angle: angle to rotate in degrees % % This function is only internel to this module, as it is not finalized, % especially with regard to non-orthogonal angles, and rotation of larger % 2D kernels. */ /* Internal Routine - Return true if two kernels are the same */ static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1, const KernelInfo *kernel2) { register size_t i; /* check size and origin location */ if ( kernel1->width != kernel2->width || kernel1->height != kernel2->height || kernel1->x != kernel2->x || kernel1->y != kernel2->y ) return MagickFalse; /* check actual kernel values */ for (i=0; i < (kernel1->width*kernel1->height); i++) { /* Test for Nan equivalence */ if ( IsNan(kernel1->values[i]) && !IsNan(kernel2->values[i]) ) return MagickFalse; if ( IsNan(kernel2->values[i]) && !IsNan(kernel1->values[i]) ) return MagickFalse; /* Test actual values are equivalent */ if ( fabs(kernel1->values[i] - kernel2->values[i]) > MagickEpsilon ) return MagickFalse; } return MagickTrue; } static void ExpandRotateKernelInfo(KernelInfo *kernel, const double angle) { KernelInfo *clone, *last; last = kernel; while(1) { clone = CloneKernelInfo(last); RotateKernelInfo(clone, angle); if ( SameKernelInfo(kernel, clone) == MagickTrue ) break; LastKernelInfo(last)->next = clone; last = clone; } clone = DestroyKernelInfo(clone); /* kernel has repeated - junk the clone */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a l c M e t a K e r n a l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only, % using the kernel values. This should only ne used if it is not possible to % calculate that meta-data in some easier way. % % It is important that the meta-data is correct before ScaleKernelInfo() is % used to perform kernel normalization. % % The format of the CalcKernelMetaData method is: % % void CalcKernelMetaData(KernelInfo *kernel, const double scale ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to modify % % WARNING: Minimum and Maximum values are assumed to include zero, even if % zero is not part of the kernel (as in Gaussian Derived kernels). This % however is not true for flat-shaped morphological kernels. % % WARNING: Only the specific kernel pointed to is modified, not a list of % multiple kernels. % % This is an internal function and not expected to be useful outside this % module. This could change however. */ static void CalcKernelMetaData(KernelInfo *kernel) { register size_t i; kernel->minimum = kernel->maximum = 0.0; kernel->negative_range = kernel->positive_range = 0.0; for (i=0; i < (kernel->width*kernel->height); i++) { if ( fabs(kernel->values[i]) < MagickEpsilon ) kernel->values[i] = 0.0; ( kernel->values[i] < 0) ? ( kernel->negative_range += kernel->values[i] ) : ( kernel->positive_range += kernel->values[i] ); Minimize(kernel->minimum, kernel->values[i]); Maximize(kernel->maximum, kernel->values[i]); } return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h o l o g y A p p l y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MorphologyApply() applies a morphological method, multiple times using % a list of multiple kernels. % % It is basically equivalent to as MorphologyImageChannel() (see below) but % without any user controls. This allows internel programs to use this % function, to actually perform a specific task without possible interference % by any API user supplied settings. % % It is MorphologyImageChannel() task to extract any such user controls, and % pass them to this function for processing. % % More specifically kernels are not normalized/scaled/blended by the % 'convolve:scale' Image Artifact (setting), nor is the convolve bias % (-bias setting or image->bias) loooked at, but must be supplied from the % function arguments. % % The format of the MorphologyApply method is: % % Image *MorphologyApply(const Image *image,MorphologyMethod method, % const ChannelType channel, const ssize_t iterations, % const KernelInfo *kernel, const CompositeMethod compose, % const double bias, ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the source image % % o method: the morphology method to be applied. % % o channel: the channels to which the operations are applied % The channel 'sync' flag determines if 'alpha weighting' is % applied for convolution style operations. % % o iterations: apply the operation this many times (or no change). % A value of -1 means loop until no change found. % How this is applied may depend on the morphology method. % Typically this is a value of 1. % % o channel: the channel type. % % o kernel: An array of double representing the morphology kernel. % % o compose: How to handle or merge multi-kernel results. % If 'UndefinedCompositeOp' use default for the Morphology method. % If 'NoCompositeOp' force image to be re-iterated by each kernel. % Otherwise merge the results using the compose method given. % % o bias: Convolution Output Bias. % % o exception: return any errors or warnings in this structure. % */ /* Apply a Morphology Primative to an image using the given kernel. ** Two pre-created images must be provided, and no image is created. ** It returns the number of pixels that changed between the images ** for result convergence determination. */ static ssize_t MorphologyPrimitive(const Image *image, Image *result_image, const MorphologyMethod method, const ChannelType channel, const KernelInfo *kernel,const double bias,ExceptionInfo *exception) { #define MorphologyTag "Morphology/Image" CacheView *p_view, *q_view; ssize_t y, offx, offy; size_t virt_width, changed; MagickBooleanType status; MagickOffsetType progress; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(result_image != (Image *) NULL); assert(result_image->signature == MagickSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=MagickTrue; changed=0; progress=0; p_view=AcquireCacheView(image); q_view=AcquireCacheView(result_image); virt_width=image->columns+kernel->width-1; /* Some methods (including convolve) needs use a reflected kernel. * Adjust 'origin' offsets to loop though kernel as a reflection. */ offx = kernel->x; offy = kernel->y; switch(method) { case ConvolveMorphology: case DilateMorphology: case DilateIntensityMorphology: case IterativeDistanceMorphology: /* kernel needs to used with reflection about origin */ offx = (ssize_t) kernel->width-offx-1; offy = (ssize_t) kernel->height-offy-1; break; case ErodeMorphology: case ErodeIntensityMorphology: case HitAndMissMorphology: case ThinningMorphology: case ThickenMorphology: /* kernel is used as is, without reflection */ break; default: assert("Not a Primitive Morphology Method" != (char *) NULL); break; } if ( method == ConvolveMorphology && kernel->width == 1 ) { /* Special handling (for speed) of vertical (blur) kernels. ** This performs its handling in columns rather than in rows. ** This is only done for convolve as it is the only method that ** generates very large 1-D vertical kernels (such as a 'BlurKernel') ** ** Timing tests (on single CPU laptop) ** Using a vertical 1-d Blue with normal row-by-row (below) ** time convert logo: -morphology Convolve Blur:0x10+90 null: ** 0.807u ** Using this column method ** time convert logo: -morphology Convolve Blur:0x10+90 null: ** 0.620u ** ** Anthony Thyssen, 14 June 2010 */ register ssize_t x; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) #endif for (x=0; x < (ssize_t) image->columns; x++) { register const PixelPacket *restrict p; register const IndexPacket *restrict p_indexes; register PixelPacket *restrict q; register IndexPacket *restrict q_indexes; register ssize_t y; ssize_t r; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(p_view, x, -offy,1, image->rows+kernel->height-1, exception); q=GetCacheViewAuthenticPixels(q_view,x,0,1,result_image->rows,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } p_indexes=GetCacheViewVirtualIndexQueue(p_view); q_indexes=GetCacheViewAuthenticIndexQueue(q_view); /* offset to origin in 'p'. while 'q' points to it directly */ r = offy; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t v; register const MagickRealType *restrict k; register const PixelPacket *restrict k_pixels; register const IndexPacket *restrict k_indexes; MagickPixelPacket result; /* Copy input image to the output image for unused channels * This removes need for 'cloning' a new image every iteration */ *q = p[r]; if (image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+y,GetPixelIndex( p_indexes+r)); /* Set the bias of the weighted average output */ result.red = result.green = result.blue = result.opacity = result.index = bias; /* Weighted Average of pixels using reflected kernel ** ** NOTE for correct working of this operation for asymetrical ** kernels, the kernel needs to be applied in its reflected form. ** That is its values needs to be reversed. */ k = &kernel->values[ kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; if ( ((channel & SyncChannels) == 0 ) || (image->matte == MagickFalse) ) { /* No 'Sync' involved. ** Convolution is simple greyscale channel operation */ for (v=0; v < (ssize_t) kernel->height; v++) { if ( IsNan(*k) ) continue; result.red += (*k)*GetPixelRed(k_pixels); result.green += (*k)*GetPixelGreen(k_pixels); result.blue += (*k)*GetPixelBlue(k_pixels); result.opacity += (*k)*GetPixelOpacity(k_pixels); if ( image->colorspace == CMYKColorspace) result.index += (*k)*(*k_indexes); k--; k_pixels++; k_indexes++; } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(result.blue)); if ((channel & OpacityChannel) != 0 && image->matte == MagickTrue ) SetPixelOpacity(q,ClampToQuantum(result.opacity)); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,ClampToQuantum(result.index)); } else { /* Channel 'Sync' Flag, and Alpha Channel enabled. ** Weight the color channels with Alpha Channel so that ** transparent pixels are not part of the results. */ MagickRealType alpha, /* alpha weighting of colors : kernel*alpha */ gamma; /* divisor, sum of color weighting values */ gamma=0.0; for (v=0; v < (ssize_t) kernel->height; v++) { if ( IsNan(*k) ) continue; alpha=(*k)*(QuantumScale*(QuantumRange-GetPixelOpacity(k_pixels))); gamma += alpha; result.red += alpha*GetPixelRed(k_pixels); result.green += alpha*GetPixelGreen(k_pixels); result.blue += alpha*GetPixelBlue(k_pixels); result.opacity += (*k)*GetPixelOpacity(k_pixels); if ( image->colorspace == CMYKColorspace) result.index += alpha*(*k_indexes); k--; k_pixels++; k_indexes++; } /* Sync'ed channels, all channels are modified */ gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma); SetPixelRed(q,ClampToQuantum(gamma*result.red)); SetPixelGreen(q,ClampToQuantum(gamma*result.green)); SetPixelBlue(q,ClampToQuantum(gamma*result.blue)); SetPixelOpacity(q,ClampToQuantum(result.opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,ClampToQuantum(gamma* result.index)); } /* Count up changed pixels */ if ( ( p[r].red != GetPixelRed(q)) || ( p[r].green != GetPixelGreen(q)) || ( p[r].blue != GetPixelBlue(q)) || ( p[r].opacity != GetPixelOpacity(q)) || ( image->colorspace == CMYKColorspace && GetPixelIndex(p_indexes+r) != GetPixelIndex(q_indexes+x) ) ) changed++; /* The pixel was changed in some way! */ p++; q++; } /* y */ if ( SyncCacheViewAuthenticPixels(q_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_MorphologyImage) #endif proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } /* x */ result_image->type=image->type; q_view=DestroyCacheView(q_view); p_view=DestroyCacheView(p_view); return(status ? (ssize_t) changed : 0); } /* ** Normal handling of horizontal or rectangular kernels (row by row) */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register const IndexPacket *restrict p_indexes; register PixelPacket *restrict q; register IndexPacket *restrict q_indexes; register ssize_t x; size_t r; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(p_view, -offx, y-offy, virt_width, kernel->height, exception); q=GetCacheViewAuthenticPixels(q_view,0,y,result_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } p_indexes=GetCacheViewVirtualIndexQueue(p_view); q_indexes=GetCacheViewAuthenticIndexQueue(q_view); /* offset to origin in 'p'. while 'q' points to it directly */ r = virt_width*offy + offx; for (x=0; x < (ssize_t) image->columns; x++) { ssize_t v; register ssize_t u; register const MagickRealType *restrict k; register const PixelPacket *restrict k_pixels; register const IndexPacket *restrict k_indexes; MagickPixelPacket result, min, max; /* Copy input image to the output image for unused channels * This removes need for 'cloning' a new image every iteration */ *q = p[r]; if (image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,GetPixelIndex(p_indexes+r)); /* Defaults */ min.red = min.green = min.blue = min.opacity = min.index = (MagickRealType) QuantumRange; max.red = max.green = max.blue = max.opacity = max.index = (MagickRealType) 0; /* default result is the original pixel value */ result.red = (MagickRealType) p[r].red; result.green = (MagickRealType) p[r].green; result.blue = (MagickRealType) p[r].blue; result.opacity = QuantumRange - (MagickRealType) p[r].opacity; result.index = 0.0; if ( image->colorspace == CMYKColorspace) result.index = (MagickRealType) GetPixelIndex(p_indexes+r); switch (method) { case ConvolveMorphology: /* Set the bias of the weighted average output */ result.red = result.green = result.blue = result.opacity = result.index = bias; break; case DilateIntensityMorphology: case ErodeIntensityMorphology: /* use a boolean flag indicating when first match found */ result.red = 0.0; /* result is not used otherwise */ break; default: break; } switch ( method ) { case ConvolveMorphology: /* Weighted Average of pixels using reflected kernel ** ** NOTE for correct working of this operation for asymetrical ** kernels, the kernel needs to be applied in its reflected form. ** That is its values needs to be reversed. ** ** Correlation is actually the same as this but without reflecting ** the kernel, and thus 'lower-level' that Convolution. However ** as Convolution is the more common method used, and it does not ** really cost us much in terms of processing to use a reflected ** kernel, so it is Convolution that is implemented. ** ** Correlation will have its kernel reflected before calling ** this function to do a Convolve. ** ** For more details of Correlation vs Convolution see ** http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; if ( ((channel & SyncChannels) == 0 ) || (image->matte == MagickFalse) ) { /* No 'Sync' involved. ** Convolution is simple greyscale channel operation */ for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNan(*k) ) continue; result.red += (*k)*k_pixels[u].red; result.green += (*k)*k_pixels[u].green; result.blue += (*k)*k_pixels[u].blue; result.opacity += (*k)*k_pixels[u].opacity; if ( image->colorspace == CMYKColorspace) result.index += (*k)*GetPixelIndex(k_indexes+u); } k_pixels += virt_width; k_indexes += virt_width; } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(result.blue)); if ((channel & OpacityChannel) != 0 && image->matte == MagickTrue ) SetPixelOpacity(q,ClampToQuantum(result.opacity)); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,ClampToQuantum( result.index)); } else { /* Channel 'Sync' Flag, and Alpha Channel enabled. ** Weight the color channels with Alpha Channel so that ** transparent pixels are not part of the results. */ MagickRealType alpha, /* alpha weighting of colors : kernel*alpha */ gamma; /* divisor, sum of color weighting values */ gamma=0.0; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNan(*k) ) continue; alpha=(*k)*(QuantumScale*(QuantumRange- k_pixels[u].opacity)); gamma += alpha; result.red += alpha*k_pixels[u].red; result.green += alpha*k_pixels[u].green; result.blue += alpha*k_pixels[u].blue; result.opacity += (*k)*k_pixels[u].opacity; if ( image->colorspace == CMYKColorspace) result.index+=alpha*GetPixelIndex(k_indexes+u); } k_pixels += virt_width; k_indexes += virt_width; } /* Sync'ed channels, all channels are modified */ gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma); SetPixelRed(q,ClampToQuantum(gamma*result.red)); SetPixelGreen(q,ClampToQuantum(gamma*result.green)); SetPixelBlue(q,ClampToQuantum(gamma*result.blue)); SetPixelOpacity(q,ClampToQuantum(result.opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,ClampToQuantum(gamma* result.index)); } break; case ErodeMorphology: /* Minimum Value within kernel neighbourhood ** ** NOTE that the kernel is not reflected for this operation! ** ** NOTE: in normal Greyscale Morphology, the kernel value should ** be added to the real value, this is currently not done, due to ** the nature of the boolean kernels being used. */ k = kernel->values; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k++) { if ( IsNan(*k) || (*k) < 0.5 ) continue; Minimize(min.red, (double) k_pixels[u].red); Minimize(min.green, (double) k_pixels[u].green); Minimize(min.blue, (double) k_pixels[u].blue); Minimize(min.opacity, QuantumRange-(double) k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(min.index,(double) GetPixelIndex( k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } break; case DilateMorphology: /* Maximum Value within kernel neighbourhood ** ** NOTE for correct working of this operation for asymetrical ** kernels, the kernel needs to be applied in its reflected form. ** That is its values needs to be reversed. ** ** NOTE: in normal Greyscale Morphology, the kernel value should ** be added to the real value, this is currently not done, due to ** the nature of the boolean kernels being used. ** */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNan(*k) || (*k) < 0.5 ) continue; Maximize(max.red, (double) k_pixels[u].red); Maximize(max.green, (double) k_pixels[u].green); Maximize(max.blue, (double) k_pixels[u].blue); Maximize(max.opacity, QuantumRange-(double) k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Maximize(max.index, (double) GetPixelIndex( k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } break; case HitAndMissMorphology: case ThinningMorphology: case ThickenMorphology: /* Minimum of Foreground Pixel minus Maxumum of Background Pixels ** ** NOTE that the kernel is not reflected for this operation, ** and consists of both foreground and background pixel ** neighbourhoods, 0.0 for background, and 1.0 for foreground ** with either Nan or 0.5 values for don't care. ** ** Note that this will never produce a meaningless negative ** result. Such results can cause Thinning/Thicken to not work ** correctly when used against a greyscale image. */ k = kernel->values; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k++) { if ( IsNan(*k) ) continue; if ( (*k) > 0.7 ) { /* minimim of foreground pixels */ Minimize(min.red, (double) k_pixels[u].red); Minimize(min.green, (double) k_pixels[u].green); Minimize(min.blue, (double) k_pixels[u].blue); Minimize(min.opacity, QuantumRange-(double) k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(min.index,(double) GetPixelIndex( k_indexes+u)); } else if ( (*k) < 0.3 ) { /* maximum of background pixels */ Maximize(max.red, (double) k_pixels[u].red); Maximize(max.green, (double) k_pixels[u].green); Maximize(max.blue, (double) k_pixels[u].blue); Maximize(max.opacity, QuantumRange-(double) k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Maximize(max.index, (double) GetPixelIndex( k_indexes+u)); } } k_pixels += virt_width; k_indexes += virt_width; } /* Pattern Match if difference is positive */ min.red -= max.red; Maximize( min.red, 0.0 ); min.green -= max.green; Maximize( min.green, 0.0 ); min.blue -= max.blue; Maximize( min.blue, 0.0 ); min.opacity -= max.opacity; Maximize( min.opacity, 0.0 ); min.index -= max.index; Maximize( min.index, 0.0 ); break; case ErodeIntensityMorphology: /* Select Pixel with Minimum Intensity within kernel neighbourhood ** ** WARNING: the intensity test fails for CMYK and does not ** take into account the moderating effect of the alpha channel ** on the intensity. ** ** NOTE that the kernel is not reflected for this operation! */ k = kernel->values; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k++) { if ( IsNan(*k) || (*k) < 0.5 ) continue; if ( result.red == 0.0 || PixelIntensity(&(k_pixels[u])) < PixelIntensity(q) ) { /* copy the whole pixel - no channel selection */ *q = k_pixels[u]; if ( result.red > 0.0 ) changed++; result.red = 1.0; } } k_pixels += virt_width; k_indexes += virt_width; } break; case DilateIntensityMorphology: /* Select Pixel with Maximum Intensity within kernel neighbourhood ** ** WARNING: the intensity test fails for CMYK and does not ** take into account the moderating effect of the alpha channel ** on the intensity (yet). ** ** NOTE for correct working of this operation for asymetrical ** kernels, the kernel needs to be applied in its reflected form. ** That is its values needs to be reversed. */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNan(*k) || (*k) < 0.5 ) continue; /* boolean kernel */ if ( result.red == 0.0 || PixelIntensity(&(k_pixels[u])) > PixelIntensity(q) ) { /* copy the whole pixel - no channel selection */ *q = k_pixels[u]; if ( result.red > 0.0 ) changed++; result.red = 1.0; } } k_pixels += virt_width; k_indexes += virt_width; } break; case IterativeDistanceMorphology: /* Work out an iterative distance from black edge of a white image ** shape. Essentually white values are decreased to the smallest ** 'distance from edge' it can find. ** ** It works by adding kernel values to the neighbourhood, and and ** select the minimum value found. The kernel is rotated before ** use, so kernel distances match resulting distances, when a user ** provided asymmetric kernel is applied. ** ** ** This code is almost identical to True GrayScale Morphology But ** not quite. ** ** GreyDilate Kernel values added, maximum value found Kernel is ** rotated before use. ** ** GrayErode: Kernel values subtracted and minimum value found No ** kernel rotation used. ** ** Note the the Iterative Distance method is essentially a ** GrayErode, but with negative kernel values, and kernel ** rotation applied. */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNan(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index,(*k)+GetPixelIndex( k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } break; case UndefinedMorphology: default: break; /* Do nothing */ } /* Final mathematics of results (combine with original image?) ** ** NOTE: Difference Morphology operators Edge* and *Hat could also ** be done here but works better with iteration as a image difference ** in the controlling function (below). Thicken and Thinning however ** should be done here so thay can be iterated correctly. */ switch ( method ) { case HitAndMissMorphology: case ErodeMorphology: result = min; /* minimum of neighbourhood */ break; case DilateMorphology: result = max; /* maximum of neighbourhood */ break; case ThinningMorphology: /* subtract pattern match from original */ result.red -= min.red; result.green -= min.green; result.blue -= min.blue; result.opacity -= min.opacity; result.index -= min.index; break; case ThickenMorphology: /* Add the pattern matchs to the original */ result.red += min.red; result.green += min.green; result.blue += min.blue; result.opacity += min.opacity; result.index += min.index; break; default: /* result directly calculated or assigned */ break; } /* Assign the resulting pixel values - Clamping Result */ switch ( method ) { case UndefinedMorphology: case ConvolveMorphology: case DilateIntensityMorphology: case ErodeIntensityMorphology: break; /* full pixel was directly assigned - not a channel method */ default: if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(result.blue)); if ((channel & OpacityChannel) != 0 && image->matte == MagickTrue ) SetPixelAlpha(q,ClampToQuantum(result.opacity)); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,ClampToQuantum(result.index)); break; } /* Count up changed pixels */ if ( ( p[r].red != GetPixelRed(q) ) || ( p[r].green != GetPixelGreen(q) ) || ( p[r].blue != GetPixelBlue(q) ) || ( p[r].opacity != GetPixelOpacity(q) ) || ( image->colorspace == CMYKColorspace && GetPixelIndex(p_indexes+r) != GetPixelIndex(q_indexes+x) ) ) changed++; /* The pixel was changed in some way! */ p++; q++; } /* x */ if ( SyncCacheViewAuthenticPixels(q_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_MorphologyImage) #endif proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } /* y */ q_view=DestroyCacheView(q_view); p_view=DestroyCacheView(p_view); return(status ? (ssize_t)changed : -1); } /* This is almost identical to the MorphologyPrimative() function above, ** but will apply the primitive directly to the actual image using two ** passes, once in each direction, with the results of the previous (and ** current) row being re-used. ** ** That is after each row is 'Sync'ed' into the image, the next row will ** make use of those values as part of the calculation of the next row. ** It then repeats, but going in the oppisite (bottom-up) direction. ** ** Because of this 're-use of results' this function can not make use ** of multi-threaded, parellel processing. */ static ssize_t MorphologyPrimitiveDirect(Image *image, const MorphologyMethod method, const ChannelType channel, const KernelInfo *kernel,ExceptionInfo *exception) { CacheView *auth_view, *virt_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y, offx, offy; size_t virt_width, changed; status=MagickTrue; changed=0; progress=0; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); /* Some methods (including convolve) needs use a reflected kernel. * Adjust 'origin' offsets to loop though kernel as a reflection. */ offx = kernel->x; offy = kernel->y; switch(method) { case DistanceMorphology: case VoronoiMorphology: /* kernel needs to used with reflection about origin */ offx = (ssize_t) kernel->width-offx-1; offy = (ssize_t) kernel->height-offy-1; break; #if 0 case ?????Morphology: /* kernel is used as is, without reflection */ break; #endif default: assert("Not a PrimativeDirect Morphology Method" != (char *) NULL); break; } /* DO NOT THREAD THIS CODE! */ /* two views into same image (virtual, and actual) */ virt_view=AcquireCacheView(image); auth_view=AcquireCacheView(image); virt_width=image->columns+kernel->width-1; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register const IndexPacket *restrict p_indexes; register PixelPacket *restrict q; register IndexPacket *restrict q_indexes; register ssize_t x; ssize_t r; /* NOTE read virtual pixels, and authentic pixels, from the same image! ** we read using virtual to get virtual pixel handling, but write back ** into the same image. ** ** Only top half of kernel is processed as we do a single pass downward ** through the image iterating the distance function as we go. */ if (status == MagickFalse) break; p=GetCacheViewVirtualPixels(virt_view, -offx, y-offy, virt_width, (size_t) offy+1, exception); q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) status=MagickFalse; if (status == MagickFalse) break; p_indexes=GetCacheViewVirtualIndexQueue(virt_view); q_indexes=GetCacheViewAuthenticIndexQueue(auth_view); /* offset to origin in 'p'. while 'q' points to it directly */ r = (ssize_t) virt_width*offy + offx; for (x=0; x < (ssize_t) image->columns; x++) { ssize_t v; register ssize_t u; register const MagickRealType *restrict k; register const PixelPacket *restrict k_pixels; register const IndexPacket *restrict k_indexes; MagickPixelPacket result; /* Starting Defaults */ GetMagickPixelPacket(image,&result); SetMagickPixelPacket(image,q,q_indexes,&result); if ( method != VoronoiMorphology ) result.opacity = QuantumRange - result.opacity; switch ( method ) { case DistanceMorphology: /* Add kernel Value and select the minimum value found. */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v <= (ssize_t) offy; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNan(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index, (*k)+GetPixelIndex(k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } /* repeat with the just processed pixels of this row */ k = &kernel->values[ kernel->width*(kernel->y+1)-1 ]; k_pixels = q-offx; k_indexes = q_indexes-offx; for (u=0; u < (ssize_t) offx; u++, k--) { if ( x+u-offx < 0 ) continue; /* off the edge! */ if ( IsNan(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index, (*k)+GetPixelIndex(k_indexes+u)); } break; case VoronoiMorphology: /* Apply Distance to 'Matte' channel, coping the closest color. ** ** This is experimental, and realy the 'alpha' component should ** be completely separate 'masking' channel so that alpha can ** also be used as part of the results. */ k = &kernel->values[ kernel->width*kernel->height-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=0; v <= (ssize_t) offy; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNan(*k) ) continue; if( result.opacity > (*k)+k_pixels[u].opacity ) { SetMagickPixelPacket(image,&k_pixels[u],&k_indexes[u], &result); result.opacity += *k; } } k_pixels += virt_width; k_indexes += virt_width; } /* repeat with the just processed pixels of this row */ k = &kernel->values[ kernel->width*(kernel->y+1)-1 ]; k_pixels = q-offx; k_indexes = q_indexes-offx; for (u=0; u < (ssize_t) offx; u++, k--) { if ( x+u-offx < 0 ) continue; /* off the edge! */ if ( IsNan(*k) ) continue; if( result.opacity > (*k)+k_pixels[u].opacity ) { SetMagickPixelPacket(image,&k_pixels[u],&k_indexes[u], &result); result.opacity += *k; } } break; default: /* result directly calculated or assigned */ break; } /* Assign the resulting pixel values - Clamping Result */ switch ( method ) { case VoronoiMorphology: SetPixelPacket(image,&result,q,q_indexes); break; default: if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(result.blue)); if ((channel & OpacityChannel) != 0 && image->matte == MagickTrue ) SetPixelAlpha(q,ClampToQuantum(result.opacity)); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,ClampToQuantum(result.index)); break; } /* Count up changed pixels */ if ( ( p[r].red != GetPixelRed(q) ) || ( p[r].green != GetPixelGreen(q) ) || ( p[r].blue != GetPixelBlue(q) ) || ( p[r].opacity != GetPixelOpacity(q) ) || ( image->colorspace == CMYKColorspace && GetPixelIndex(p_indexes+r) != GetPixelIndex(q_indexes+x) ) ) changed++; /* The pixel was changed in some way! */ p++; /* increment pixel buffers */ q++; } /* x */ if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) if ( SetImageProgress(image,MorphologyTag,progress++,image->rows) == MagickFalse ) status=MagickFalse; } /* y */ /* Do the reversed pass through the image */ for (y=(ssize_t)image->rows-1; y >= 0; y--) { register const PixelPacket *restrict p; register const IndexPacket *restrict p_indexes; register PixelPacket *restrict q; register IndexPacket *restrict q_indexes; register ssize_t x; ssize_t r; if (status == MagickFalse) break; /* NOTE read virtual pixels, and authentic pixels, from the same image! ** we read using virtual to get virtual pixel handling, but write back ** into the same image. ** ** Only the bottom half of the kernel will be processes as we ** up the image. */ p=GetCacheViewVirtualPixels(virt_view, -offx, y, virt_width, (size_t) kernel->y+1, exception); q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) status=MagickFalse; if (status == MagickFalse) break; p_indexes=GetCacheViewVirtualIndexQueue(virt_view); q_indexes=GetCacheViewAuthenticIndexQueue(auth_view); /* adjust positions to end of row */ p += image->columns-1; q += image->columns-1; /* offset to origin in 'p'. while 'q' points to it directly */ r = offx; for (x=(ssize_t)image->columns-1; x >= 0; x--) { ssize_t v; register ssize_t u; register const MagickRealType *restrict k; register const PixelPacket *restrict k_pixels; register const IndexPacket *restrict k_indexes; MagickPixelPacket result; /* Default - previously modified pixel */ GetMagickPixelPacket(image,&result); SetMagickPixelPacket(image,q,q_indexes,&result); if ( method != VoronoiMorphology ) result.opacity = QuantumRange - result.opacity; switch ( method ) { case DistanceMorphology: /* Add kernel Value and select the minimum value found. */ k = &kernel->values[ kernel->width*(kernel->y+1)-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=offy; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNan(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index,(*k)+GetPixelIndex(k_indexes+u)); } k_pixels += virt_width; k_indexes += virt_width; } /* repeat with the just processed pixels of this row */ k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ]; k_pixels = q-offx; k_indexes = q_indexes-offx; for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) { if ( (x+u-offx) >= (ssize_t)image->columns ) continue; if ( IsNan(*k) ) continue; Minimize(result.red, (*k)+k_pixels[u].red); Minimize(result.green, (*k)+k_pixels[u].green); Minimize(result.blue, (*k)+k_pixels[u].blue); Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity); if ( image->colorspace == CMYKColorspace) Minimize(result.index, (*k)+GetPixelIndex(k_indexes+u)); } break; case VoronoiMorphology: /* Apply Distance to 'Matte' channel, coping the closest color. ** ** This is experimental, and realy the 'alpha' component should ** be completely separate 'masking' channel. */ k = &kernel->values[ kernel->width*(kernel->y+1)-1 ]; k_pixels = p; k_indexes = p_indexes; for (v=offy; v < (ssize_t) kernel->height; v++) { for (u=0; u < (ssize_t) kernel->width; u++, k--) { if ( IsNan(*k) ) continue; if( result.opacity > (*k)+k_pixels[u].opacity ) { SetMagickPixelPacket(image,&k_pixels[u],&k_indexes[u], &result); result.opacity += *k; } } k_pixels += virt_width; k_indexes += virt_width; } /* repeat with the just processed pixels of this row */ k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ]; k_pixels = q-offx; k_indexes = q_indexes-offx; for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) { if ( (x+u-offx) >= (ssize_t)image->columns ) continue; if ( IsNan(*k) ) continue; if( result.opacity > (*k)+k_pixels[u].opacity ) { SetMagickPixelPacket(image,&k_pixels[u],&k_indexes[u], &result); result.opacity += *k; } } break; default: /* result directly calculated or assigned */ break; } /* Assign the resulting pixel values - Clamping Result */ switch ( method ) { case VoronoiMorphology: SetPixelPacket(image,&result,q,q_indexes); break; default: if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(result.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(result.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(result.blue)); if ((channel & OpacityChannel) != 0 && image->matte == MagickTrue ) SetPixelAlpha(q,ClampToQuantum(result.opacity)); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) SetPixelIndex(q_indexes+x,ClampToQuantum(result.index)); break; } /* Count up changed pixels */ if ( ( p[r].red != GetPixelRed(q) ) || ( p[r].green != GetPixelGreen(q) ) || ( p[r].blue != GetPixelBlue(q) ) || ( p[r].opacity != GetPixelOpacity(q) ) || ( image->colorspace == CMYKColorspace && GetPixelIndex(p_indexes+r) != GetPixelIndex(q_indexes+x) ) ) changed++; /* The pixel was changed in some way! */ p--; /* go backward through pixel buffers */ q--; } /* x */ if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) if ( SetImageProgress(image,MorphologyTag,progress++,image->rows) == MagickFalse ) status=MagickFalse; } /* y */ auth_view=DestroyCacheView(auth_view); virt_view=DestroyCacheView(virt_view); return(status ? (ssize_t) changed : -1); } /* Apply a Morphology by calling one of the above low level primitive ** application functions. This function handles any iteration loops, ** composition or re-iteration of results, and compound morphology methods ** that is based on multiple low-level (staged) morphology methods. ** ** Basically this provides the complex grue between the requested morphology ** method and raw low-level implementation (above). */ MagickExport Image *MorphologyApply(const Image *image, const ChannelType channel,const MorphologyMethod method, const ssize_t iterations, const KernelInfo *kernel, const CompositeOperator compose, const double bias, ExceptionInfo *exception) { CompositeOperator curr_compose; Image *curr_image, /* Image we are working with or iterating */ *work_image, /* secondary image for primitive iteration */ *save_image, /* saved image - for 'edge' method only */ *rslt_image; /* resultant image - after multi-kernel handling */ KernelInfo *reflected_kernel, /* A reflected copy of the kernel (if needed) */ *norm_kernel, /* the current normal un-reflected kernel */ *rflt_kernel, /* the current reflected kernel (if needed) */ *this_kernel; /* the kernel being applied */ MorphologyMethod primitive; /* the current morphology primitive being applied */ CompositeOperator rslt_compose; /* multi-kernel compose method for results to use */ MagickBooleanType special, /* do we use a direct modify function? */ verbose; /* verbose output of results */ size_t method_loop, /* Loop 1: number of compound method iterations (norm 1) */ method_limit, /* maximum number of compound method iterations */ kernel_number, /* Loop 2: the kernel number being applied */ stage_loop, /* Loop 3: primitive loop for compound morphology */ stage_limit, /* how many primitives are in this compound */ kernel_loop, /* Loop 4: iterate the kernel over image */ kernel_limit, /* number of times to iterate kernel */ count, /* total count of primitive steps applied */ kernel_changed, /* total count of changed using iterated kernel */ method_changed; /* total count of changed over method iteration */ ssize_t changed; /* number pixels changed by last primitive operation */ char v_info[80]; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(kernel != (KernelInfo *) NULL); assert(kernel->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); count = 0; /* number of low-level morphology primitives performed */ if ( iterations == 0 ) return((Image *)NULL); /* null operation - nothing to do! */ kernel_limit = (size_t) iterations; if ( iterations < 0 ) /* negative interations = infinite (well alomst) */ kernel_limit = image->columns>image->rows ? image->columns : image->rows; verbose = IsMagickTrue(GetImageArtifact(image,"verbose")); /* initialise for cleanup */ curr_image = (Image *) image; curr_compose = image->compose; (void) curr_compose; work_image = save_image = rslt_image = (Image *) NULL; reflected_kernel = (KernelInfo *) NULL; /* Initialize specific methods * + which loop should use the given iteratations * + how many primitives make up the compound morphology * + multi-kernel compose method to use (by default) */ method_limit = 1; /* just do method once, unless otherwise set */ stage_limit = 1; /* assume method is not a compound */ special = MagickFalse; /* assume it is NOT a direct modify primitive */ rslt_compose = compose; /* and we are composing multi-kernels as given */ switch( method ) { case SmoothMorphology: /* 4 primitive compound morphology */ stage_limit = 4; break; case OpenMorphology: /* 2 primitive compound morphology */ case OpenIntensityMorphology: case TopHatMorphology: case CloseMorphology: case CloseIntensityMorphology: case BottomHatMorphology: case EdgeMorphology: stage_limit = 2; break; case HitAndMissMorphology: rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */ /* FALL THUR */ case ThinningMorphology: case ThickenMorphology: method_limit = kernel_limit; /* iterate the whole method */ kernel_limit = 1; /* do not do kernel iteration */ break; case DistanceMorphology: case VoronoiMorphology: special = MagickTrue; /* use special direct primative */ break; default: break; } /* Apply special methods with special requirments ** For example, single run only, or post-processing requirements */ if ( special == MagickTrue ) { rslt_image=CloneImage(image,0,0,MagickTrue,exception); if (rslt_image == (Image *) NULL) goto error_cleanup; if (SetImageStorageClass(rslt_image,DirectClass) == MagickFalse) { InheritException(exception,&rslt_image->exception); goto error_cleanup; } changed = MorphologyPrimitiveDirect(rslt_image, method, channel, kernel, exception); if ( verbose == MagickTrue ) (void) (void) FormatLocaleFile(stderr, "%s:%.20g.%.20g #%.20g => Changed %.20g\n", CommandOptionToMnemonic(MagickMorphologyOptions, method), 1.0,0.0,1.0, (double) changed); if ( changed < 0 ) goto error_cleanup; if ( method == VoronoiMorphology ) { /* Preserve the alpha channel of input image - but turned off */ (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel); (void) CompositeImageChannel(rslt_image, DefaultChannels, CopyOpacityCompositeOp, image, 0, 0); (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel); } goto exit_cleanup; } /* Handle user (caller) specified multi-kernel composition method */ if ( compose != UndefinedCompositeOp ) rslt_compose = compose; /* override default composition for method */ if ( rslt_compose == UndefinedCompositeOp ) rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */ /* Some methods require a reflected kernel to use with primitives. * Create the reflected kernel for those methods. */ switch ( method ) { case CorrelateMorphology: case CloseMorphology: case CloseIntensityMorphology: case BottomHatMorphology: case SmoothMorphology: reflected_kernel = CloneKernelInfo(kernel); if (reflected_kernel == (KernelInfo *) NULL) goto error_cleanup; RotateKernelInfo(reflected_kernel,180); break; default: break; } /* Loops around more primitive morpholgy methods ** erose, dilate, open, close, smooth, edge, etc... */ /* Loop 1: iterate the compound method */ method_loop = 0; method_changed = 1; while ( method_loop < method_limit && method_changed > 0 ) { method_loop++; method_changed = 0; /* Loop 2: iterate over each kernel in a multi-kernel list */ norm_kernel = (KernelInfo *) kernel; this_kernel = (KernelInfo *) kernel; rflt_kernel = reflected_kernel; kernel_number = 0; while ( norm_kernel != NULL ) { /* Loop 3: Compound Morphology Staging - Select Primative to apply */ stage_loop = 0; /* the compound morphology stage number */ while ( stage_loop < stage_limit ) { stage_loop++; /* The stage of the compound morphology */ /* Select primitive morphology for this stage of compound method */ this_kernel = norm_kernel; /* default use unreflected kernel */ primitive = method; /* Assume method is a primitive */ switch( method ) { case ErodeMorphology: /* just erode */ case EdgeInMorphology: /* erode and image difference */ primitive = ErodeMorphology; break; case DilateMorphology: /* just dilate */ case EdgeOutMorphology: /* dilate and image difference */ primitive = DilateMorphology; break; case OpenMorphology: /* erode then dialate */ case TopHatMorphology: /* open and image difference */ primitive = ErodeMorphology; if ( stage_loop == 2 ) primitive = DilateMorphology; break; case OpenIntensityMorphology: primitive = ErodeIntensityMorphology; if ( stage_loop == 2 ) primitive = DilateIntensityMorphology; break; case CloseMorphology: /* dilate, then erode */ case BottomHatMorphology: /* close and image difference */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateMorphology; if ( stage_loop == 2 ) primitive = ErodeMorphology; break; case CloseIntensityMorphology: this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateIntensityMorphology; if ( stage_loop == 2 ) primitive = ErodeIntensityMorphology; break; case SmoothMorphology: /* open, close */ switch ( stage_loop ) { case 1: /* start an open method, which starts with Erode */ primitive = ErodeMorphology; break; case 2: /* now Dilate the Erode */ primitive = DilateMorphology; break; case 3: /* Reflect kernel a close */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = DilateMorphology; break; case 4: /* Finish the Close */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = ErodeMorphology; break; } break; case EdgeMorphology: /* dilate and erode difference */ primitive = DilateMorphology; if ( stage_loop == 2 ) { save_image = curr_image; /* save the image difference */ curr_image = (Image *) image; primitive = ErodeMorphology; } break; case CorrelateMorphology: /* A Correlation is a Convolution with a reflected kernel. ** However a Convolution is a weighted sum using a reflected ** kernel. It may seem stange to convert a Correlation into a ** Convolution as the Correlation is the simplier method, but ** Convolution is much more commonly used, and it makes sense to ** implement it directly so as to avoid the need to duplicate the ** kernel when it is not required (which is typically the ** default). */ this_kernel = rflt_kernel; /* use the reflected kernel */ primitive = ConvolveMorphology; break; default: break; } assert( this_kernel != (KernelInfo *) NULL ); /* Extra information for debugging compound operations */ if ( verbose == MagickTrue ) { if ( stage_limit > 1 ) (void) FormatLocaleString(v_info,MaxTextExtent,"%s:%.20g.%.20g -> ", CommandOptionToMnemonic(MagickMorphologyOptions,method),(double) method_loop,(double) stage_loop); else if ( primitive != method ) (void) FormatLocaleString(v_info, MaxTextExtent, "%s:%.20g -> ", CommandOptionToMnemonic(MagickMorphologyOptions, method),(double) method_loop); else v_info[0] = '\0'; } /* Loop 4: Iterate the kernel with primitive */ kernel_loop = 0; kernel_changed = 0; changed = 1; while ( kernel_loop < kernel_limit && changed > 0 ) { kernel_loop++; /* the iteration of this kernel */ /* Create a clone as the destination image, if not yet defined */ if ( work_image == (Image *) NULL ) { work_image=CloneImage(image,0,0,MagickTrue,exception); if (work_image == (Image *) NULL) goto error_cleanup; if (SetImageStorageClass(work_image,DirectClass) == MagickFalse) { InheritException(exception,&work_image->exception); goto error_cleanup; } /* work_image->type=image->type; ??? */ } /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */ count++; changed = MorphologyPrimitive(curr_image, work_image, primitive, channel, this_kernel, bias, exception); if ( verbose == MagickTrue ) { if ( kernel_loop > 1 ) (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line from previous */ (void) (void) FormatLocaleFile(stderr, "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g", v_info,CommandOptionToMnemonic(MagickMorphologyOptions, primitive),(this_kernel == rflt_kernel ) ? "*" : "", (double) (method_loop+kernel_loop-1),(double) kernel_number, (double) count,(double) changed); } if ( changed < 0 ) goto error_cleanup; kernel_changed += changed; method_changed += changed; /* prepare next loop */ { Image *tmp = work_image; /* swap images for iteration */ work_image = curr_image; curr_image = tmp; } if ( work_image == image ) work_image = (Image *) NULL; /* replace input 'image' */ } /* End Loop 4: Iterate the kernel with primitive */ if ( verbose == MagickTrue && kernel_changed != (size_t)changed ) (void) FormatLocaleFile(stderr, " Total %.20g",(double) kernel_changed); if ( verbose == MagickTrue && stage_loop < stage_limit ) (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line before looping */ #if 0 (void) FormatLocaleFile(stderr, "--E-- image=0x%lx\n", (unsigned long)image); (void) FormatLocaleFile(stderr, " curr =0x%lx\n", (unsigned long)curr_image); (void) FormatLocaleFile(stderr, " work =0x%lx\n", (unsigned long)work_image); (void) FormatLocaleFile(stderr, " save =0x%lx\n", (unsigned long)save_image); (void) FormatLocaleFile(stderr, " union=0x%lx\n", (unsigned long)rslt_image); #endif } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */ /* Final Post-processing for some Compound Methods ** ** The removal of any 'Sync' channel flag in the Image Compositon ** below ensures the methematical compose method is applied in a ** purely mathematical way, and only to the selected channels. ** Turn off SVG composition 'alpha blending'. */ switch( method ) { case EdgeOutMorphology: case EdgeInMorphology: case TopHatMorphology: case BottomHatMorphology: if ( verbose == MagickTrue ) (void) FormatLocaleFile(stderr, "\n%s: Difference with original image", CommandOptionToMnemonic(MagickMorphologyOptions, method) ); (void) CompositeImageChannel(curr_image, (ChannelType) (channel & ~SyncChannels), DifferenceCompositeOp, image, 0, 0); break; case EdgeMorphology: if ( verbose == MagickTrue ) (void) FormatLocaleFile(stderr, "\n%s: Difference of Dilate and Erode", CommandOptionToMnemonic(MagickMorphologyOptions, method) ); (void) CompositeImageChannel(curr_image, (ChannelType) (channel & ~SyncChannels), DifferenceCompositeOp, save_image, 0, 0); save_image = DestroyImage(save_image); /* finished with save image */ break; default: break; } /* multi-kernel handling: re-iterate, or compose results */ if ( kernel->next == (KernelInfo *) NULL ) rslt_image = curr_image; /* just return the resulting image */ else if ( rslt_compose == NoCompositeOp ) { if ( verbose == MagickTrue ) { if ( this_kernel->next != (KernelInfo *) NULL ) (void) FormatLocaleFile(stderr, " (re-iterate)"); else (void) FormatLocaleFile(stderr, " (done)"); } rslt_image = curr_image; /* return result, and re-iterate */ } else if ( rslt_image == (Image *) NULL) { if ( verbose == MagickTrue ) (void) FormatLocaleFile(stderr, " (save for compose)"); rslt_image = curr_image; curr_image = (Image *) image; /* continue with original image */ } else { /* Add the new 'current' result to the composition ** ** The removal of any 'Sync' channel flag in the Image Compositon ** below ensures the methematical compose method is applied in a ** purely mathematical way, and only to the selected channels. ** IE: Turn off SVG composition 'alpha blending'. */ if ( verbose == MagickTrue ) (void) FormatLocaleFile(stderr, " (compose \"%s\")", CommandOptionToMnemonic(MagickComposeOptions, rslt_compose) ); (void) CompositeImageChannel(rslt_image, (ChannelType) (channel & ~SyncChannels), rslt_compose, curr_image, 0, 0); curr_image = DestroyImage(curr_image); curr_image = (Image *) image; /* continue with original image */ } if ( verbose == MagickTrue ) (void) FormatLocaleFile(stderr, "\n"); /* loop to the next kernel in a multi-kernel list */ norm_kernel = norm_kernel->next; if ( rflt_kernel != (KernelInfo *) NULL ) rflt_kernel = rflt_kernel->next; kernel_number++; } /* End Loop 2: Loop over each kernel */ } /* End Loop 1: compound method interation */ goto exit_cleanup; /* Yes goto's are bad, but it makes cleanup lot more efficient */ error_cleanup: if ( curr_image == rslt_image ) curr_image = (Image *) NULL; if ( rslt_image != (Image *) NULL ) rslt_image = DestroyImage(rslt_image); exit_cleanup: if ( curr_image == rslt_image || curr_image == image ) curr_image = (Image *) NULL; if ( curr_image != (Image *) NULL ) curr_image = DestroyImage(curr_image); if ( work_image != (Image *) NULL ) work_image = DestroyImage(work_image); if ( save_image != (Image *) NULL ) save_image = DestroyImage(save_image); if ( reflected_kernel != (KernelInfo *) NULL ) reflected_kernel = DestroyKernelInfo(reflected_kernel); return(rslt_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h o l o g y I m a g e C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MorphologyImageChannel() applies a user supplied kernel to the image % according to the given mophology method. % % This function applies any and all user defined settings before calling % the above internal function MorphologyApply(). % % User defined settings include... % * Output Bias for Convolution and correlation ("-bias") % * Kernel Scale/normalize settings ("-set 'option:convolve:scale'") % This can also includes the addition of a scaled unity kernel. % * Show Kernel being applied ("-set option:showkernel 1") % % The format of the MorphologyImage method is: % % Image *MorphologyImage(const Image *image,MorphologyMethod method, % const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception) % % Image *MorphologyImageChannel(const Image *image, const ChannelType % channel,MorphologyMethod method,const ssize_t iterations, % KernelInfo *kernel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the morphology method to be applied. % % o iterations: apply the operation this many times (or no change). % A value of -1 means loop until no change found. % How this is applied may depend on the morphology method. % Typically this is a value of 1. % % o channel: the channel type. % % o kernel: An array of double representing the morphology kernel. % Warning: kernel may be normalized for the Convolve method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphologyImageChannel(const Image *image, const ChannelType channel,const MorphologyMethod method, const ssize_t iterations,const KernelInfo *kernel,ExceptionInfo *exception) { KernelInfo *curr_kernel; CompositeOperator compose; Image *morphology_image; /* Apply Convolve/Correlate Normalization and Scaling Factors. * This is done BEFORE the ShowKernelInfo() function is called so that * users can see the results of the 'option:convolve:scale' option. */ curr_kernel = (KernelInfo *) kernel; if ( method == ConvolveMorphology || method == CorrelateMorphology ) { const char *artifact; artifact = GetImageArtifact(image,"convolve:scale"); if ( artifact != (const char *)NULL ) { if ( curr_kernel == kernel ) curr_kernel = CloneKernelInfo(kernel); if (curr_kernel == (KernelInfo *) NULL) { curr_kernel=DestroyKernelInfo(curr_kernel); return((Image *) NULL); } ScaleGeometryKernelInfo(curr_kernel, artifact); } } /* display the (normalized) kernel via stderr */ if ( IsMagickTrue(GetImageArtifact(image,"showkernel")) || IsMagickTrue(GetImageArtifact(image,"convolve:showkernel")) || IsMagickTrue(GetImageArtifact(image,"morphology:showkernel")) ) ShowKernelInfo(curr_kernel); /* Override the default handling of multi-kernel morphology results * If 'Undefined' use the default method * If 'None' (default for 'Convolve') re-iterate previous result * Otherwise merge resulting images using compose method given. * Default for 'HitAndMiss' is 'Lighten'. */ { const char *artifact; artifact = GetImageArtifact(image,"morphology:compose"); compose = UndefinedCompositeOp; /* use default for method */ if ( artifact != (const char *) NULL) compose = (CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,artifact); } /* Apply the Morphology */ morphology_image = MorphologyApply(image, channel, method, iterations, curr_kernel, compose, image->bias, exception); /* Cleanup and Exit */ if ( curr_kernel != kernel ) curr_kernel=DestroyKernelInfo(curr_kernel); return(morphology_image); } MagickExport Image *MorphologyImage(const Image *image, const MorphologyMethod method, const ssize_t iterations,const KernelInfo *kernel, ExceptionInfo *exception) { Image *morphology_image; morphology_image=MorphologyImageChannel(image,DefaultChannels,method, iterations,kernel,exception); return(morphology_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R o t a t e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RotateKernelInfo() rotates the kernel by the angle given. % % Currently it is restricted to 90 degree angles, of either 1D kernels % or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels. % It will ignore usless rotations for specific 'named' built-in kernels. % % The format of the RotateKernelInfo method is: % % void RotateKernelInfo(KernelInfo *kernel, double angle) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o angle: angle to rotate in degrees % % This function is currently internal to this module only, but can be exported % to other modules if needed. */ static void RotateKernelInfo(KernelInfo *kernel, double angle) { /* angle the lower kernels first */ if ( kernel->next != (KernelInfo *) NULL) RotateKernelInfo(kernel->next, angle); /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical ** ** TODO: expand beyond simple 90 degree rotates, flips and flops */ /* Modulus the angle */ angle = fmod(angle, 360.0); if ( angle < 0 ) angle += 360.0; if ( 337.5 < angle || angle <= 22.5 ) return; /* Near zero angle - no change! - At least not at this time */ /* Handle special cases */ switch (kernel->type) { /* These built-in kernels are cylindrical kernels, rotating is useless */ case GaussianKernel: case DoGKernel: case LoGKernel: case DiskKernel: case PeaksKernel: case LaplacianKernel: case ChebyshevKernel: case ManhattanKernel: case EuclideanKernel: return; /* These may be rotatable at non-90 angles in the future */ /* but simply rotating them in multiples of 90 degrees is useless */ case SquareKernel: case DiamondKernel: case PlusKernel: case CrossKernel: return; /* These only allows a +/-90 degree rotation (by transpose) */ /* A 180 degree rotation is useless */ case BlurKernel: if ( 135.0 < angle && angle <= 225.0 ) return; if ( 225.0 < angle && angle <= 315.0 ) angle -= 180; break; default: break; } /* Attempt rotations by 45 degrees -- 3x3 kernels only */ if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 ) { if ( kernel->width == 3 && kernel->height == 3 ) { /* Rotate a 3x3 square by 45 degree angle */ MagickRealType t = kernel->values[0]; kernel->values[0] = kernel->values[3]; kernel->values[3] = kernel->values[6]; kernel->values[6] = kernel->values[7]; kernel->values[7] = kernel->values[8]; kernel->values[8] = kernel->values[5]; kernel->values[5] = kernel->values[2]; kernel->values[2] = kernel->values[1]; kernel->values[1] = t; /* rotate non-centered origin */ if ( kernel->x != 1 || kernel->y != 1 ) { ssize_t x,y; x = (ssize_t) kernel->x-1; y = (ssize_t) kernel->y-1; if ( x == y ) x = 0; else if ( x == 0 ) x = -y; else if ( x == -y ) y = 0; else if ( y == 0 ) y = x; kernel->x = (ssize_t) x+1; kernel->y = (ssize_t) y+1; } angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */ kernel->angle = fmod(kernel->angle+45.0, 360.0); } else perror("Unable to rotate non-3x3 kernel by 45 degrees"); } if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 ) { if ( kernel->width == 1 || kernel->height == 1 ) { /* Do a transpose of a 1 dimensional kernel, ** which results in a fast 90 degree rotation of some type. */ ssize_t t; t = (ssize_t) kernel->width; kernel->width = kernel->height; kernel->height = (size_t) t; t = kernel->x; kernel->x = kernel->y; kernel->y = t; if ( kernel->width == 1 ) { angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */ kernel->angle = fmod(kernel->angle+90.0, 360.0); } else { angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */ kernel->angle = fmod(kernel->angle+270.0, 360.0); } } else if ( kernel->width == kernel->height ) { /* Rotate a square array of values by 90 degrees */ { register size_t i,j,x,y; register MagickRealType *k,t; k=kernel->values; for( i=0, x=kernel->width-1; i<=x; i++, x--) for( j=0, y=kernel->height-1; j<y; j++, y--) { t = k[i+j*kernel->width]; k[i+j*kernel->width] = k[j+x*kernel->width]; k[j+x*kernel->width] = k[x+y*kernel->width]; k[x+y*kernel->width] = k[y+i*kernel->width]; k[y+i*kernel->width] = t; } } /* rotate the origin - relative to center of array */ { register ssize_t x,y; x = (ssize_t) (kernel->x*2-kernel->width+1); y = (ssize_t) (kernel->y*2-kernel->height+1); kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2; kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2; } angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */ kernel->angle = fmod(kernel->angle+90.0, 360.0); } else perror("Unable to rotate a non-square, non-linear kernel 90 degrees"); } if ( 135.0 < angle && angle <= 225.0 ) { /* For a 180 degree rotation - also know as a reflection * This is actually a very very common operation! * Basically all that is needed is a reversal of the kernel data! * And a reflection of the origon */ MagickRealType t; register MagickRealType *k; size_t i, j; k=kernel->values; for ( i=0, j=kernel->width*kernel->height-1; i<j; i++, j--) t=k[i], k[i]=k[j], k[j]=t; kernel->x = (ssize_t) kernel->width - kernel->x - 1; kernel->y = (ssize_t) kernel->height - kernel->y - 1; angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */ kernel->angle = fmod(kernel->angle+180.0, 360.0); } /* At this point angle should at least between -45 (315) and +45 degrees * In the future some form of non-orthogonal angled rotates could be * performed here, posibily with a linear kernel restriction. */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e G e o m e t r y K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleGeometryKernelInfo() takes a geometry argument string, typically % provided as a "-set option:convolve:scale {geometry}" user setting, % and modifies the kernel according to the parsed arguments of that setting. % % The first argument (and any normalization flags) are passed to % ScaleKernelInfo() to scale/normalize the kernel. The second argument % is then passed to UnityAddKernelInfo() to add a scled unity kernel % into the scaled/normalized kernel. % % The format of the ScaleGeometryKernelInfo method is: % % void ScaleGeometryKernelInfo(KernelInfo *kernel, % const double scaling_factor,const MagickStatusType normalize_flags) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel to modify % % o geometry: % The geometry string to parse, typically from the user provided % "-set option:convolve:scale {geometry}" setting. % */ MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel, const char *geometry) { GeometryFlags flags; GeometryInfo args; SetGeometryInfo(&args); flags = (GeometryFlags) ParseGeometry(geometry, &args); #if 0 /* For Debugging Geometry Input */ (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n", flags, args.rho, args.sigma, args.xi, args.psi ); #endif if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/ args.rho *= 0.01, args.sigma *= 0.01; if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */ args.rho = 1.0; if ( (flags & SigmaValue) == 0 ) args.sigma = 0.0; /* Scale/Normalize the input kernel */ ScaleKernelInfo(kernel, args.rho, flags); /* Add Unity Kernel, for blending with original */ if ( (flags & SigmaValue) != 0 ) UnityAddKernelInfo(kernel, args.sigma); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleKernelInfo() scales the given kernel list by the given amount, with or % without normalization of the sum of the kernel values (as per given flags). % % By default (no flags given) the values within the kernel is scaled % directly using given scaling factor without change. % % If either of the two 'normalize_flags' are given the kernel will first be % normalized and then further scaled by the scaling factor value given. % % Kernel normalization ('normalize_flags' given) is designed to ensure that % any use of the kernel scaling factor with 'Convolve' or 'Correlate' % morphology methods will fall into -1.0 to +1.0 range. Note that for % non-HDRI versions of IM this may cause images to have any negative results % clipped, unless some 'bias' is used. % % More specifically. Kernels which only contain positive values (such as a % 'Gaussian' kernel) will be scaled so that those values sum to +1.0, % ensuring a 0.0 to +1.0 output range for non-HDRI images. % % For Kernels that contain some negative values, (such as 'Sharpen' kernels) % the kernel will be scaled by the absolute of the sum of kernel values, so % that it will generally fall within the +/- 1.0 range. % % For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel % will be scaled by just the sum of the postive values, so that its output % range will again fall into the +/- 1.0 range. % % For special kernels designed for locating shapes using 'Correlate', (often % only containing +1 and -1 values, representing foreground/brackground % matching) a special normalization method is provided to scale the positive % values separately to those of the negative values, so the kernel will be % forced to become a zero-sum kernel better suited to such searches. % % WARNING: Correct normalization of the kernel assumes that the '*_range' % attributes within the kernel structure have been correctly set during the % kernels creation. % % NOTE: The values used for 'normalize_flags' have been selected specifically % to match the use of geometry options, so that '!' means NormalizeValue, '^' % means CorrelateNormalizeValue. All other GeometryFlags values are ignored. % % The format of the ScaleKernelInfo method is: % % void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor, % const MagickStatusType normalize_flags ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o scaling_factor: % multiply all values (after normalization) by this factor if not % zero. If the kernel is normalized regardless of any flags. % % o normalize_flags: % GeometryFlags defining normalization method to use. % specifically: NormalizeValue, CorrelateNormalizeValue, % and/or PercentValue % */ MagickExport void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,const GeometryFlags normalize_flags) { register ssize_t i; register double pos_scale, neg_scale; /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags); /* Normalization of Kernel */ pos_scale = 1.0; if ( (normalize_flags&NormalizeValue) != 0 ) { if ( fabs(kernel->positive_range + kernel->negative_range) > MagickEpsilon ) /* non-zero-summing kernel (generally positive) */ pos_scale = fabs(kernel->positive_range + kernel->negative_range); else /* zero-summing kernel */ pos_scale = kernel->positive_range; } /* Force kernel into a normalized zero-summing kernel */ if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) { pos_scale = ( fabs(kernel->positive_range) > MagickEpsilon ) ? kernel->positive_range : 1.0; neg_scale = ( fabs(kernel->negative_range) > MagickEpsilon ) ? -kernel->negative_range : 1.0; } else neg_scale = pos_scale; /* finialize scaling_factor for positive and negative components */ pos_scale = scaling_factor/pos_scale; neg_scale = scaling_factor/neg_scale; for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++) if ( ! IsNan(kernel->values[i]) ) kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale; /* convolution output range */ kernel->positive_range *= pos_scale; kernel->negative_range *= neg_scale; /* maximum and minimum values in kernel */ kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale; kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale; /* swap kernel settings if user's scaling factor is negative */ if ( scaling_factor < MagickEpsilon ) { double t; t = kernel->positive_range; kernel->positive_range = kernel->negative_range; kernel->negative_range = t; t = kernel->maximum; kernel->maximum = kernel->minimum; kernel->minimum = 1; } return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h o w K e r n e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShowKernelInfo() outputs the details of the given kernel defination to % standard error, generally due to a users 'showkernel' option request. % % The format of the ShowKernel method is: % % void ShowKernelInfo(const KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % */ MagickExport void ShowKernelInfo(const KernelInfo *kernel) { const KernelInfo *k; size_t c, i, u, v; for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) { (void) FormatLocaleFile(stderr, "Kernel"); if ( kernel->next != (KernelInfo *) NULL ) (void) FormatLocaleFile(stderr, " #%lu", (unsigned long) c ); (void) FormatLocaleFile(stderr, " \"%s", CommandOptionToMnemonic(MagickKernelOptions, k->type) ); if ( fabs(k->angle) > MagickEpsilon ) (void) FormatLocaleFile(stderr, "@%lg", k->angle); (void) FormatLocaleFile(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long) k->width,(unsigned long) k->height,(long) k->x,(long) k->y); (void) FormatLocaleFile(stderr, " with values from %.*lg to %.*lg\n", GetMagickPrecision(), k->minimum, GetMagickPrecision(), k->maximum); (void) FormatLocaleFile(stderr, "Forming a output range from %.*lg to %.*lg", GetMagickPrecision(), k->negative_range, GetMagickPrecision(), k->positive_range); if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon ) (void) FormatLocaleFile(stderr, " (Zero-Summing)\n"); else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon ) (void) FormatLocaleFile(stderr, " (Normalized)\n"); else (void) FormatLocaleFile(stderr, " (Sum %.*lg)\n", GetMagickPrecision(), k->positive_range+k->negative_range); for (i=v=0; v < k->height; v++) { (void) FormatLocaleFile(stderr, "%2lu:", (unsigned long) v ); for (u=0; u < k->width; u++, i++) if ( IsNan(k->values[i]) ) (void) FormatLocaleFile(stderr," %*s", GetMagickPrecision()+3, "nan"); else (void) FormatLocaleFile(stderr," %*.*lg", GetMagickPrecision()+3, GetMagickPrecision(), k->values[i]); (void) FormatLocaleFile(stderr,"\n"); } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n i t y A d d K e r n a l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel % to the given pre-scaled and normalized Kernel. This in effect adds that % amount of the original image into the resulting convolution kernel. This % value is usually provided by the user as a percentage value in the % 'convolve:scale' setting. % % The resulting effect is to convert the defined kernels into blended % soft-blurs, unsharp kernels or into sharpening kernels. % % The format of the UnityAdditionKernelInfo method is: % % void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale ) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % % o scale: % scaling factor for the unity kernel to be added to % the given kernel. % */ MagickExport void UnityAddKernelInfo(KernelInfo *kernel, const double scale) { /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) UnityAddKernelInfo(kernel->next, scale); /* Add the scaled unity kernel to the existing kernel */ kernel->values[kernel->x+kernel->y*kernel->width] += scale; CalcKernelMetaData(kernel); /* recalculate the meta-data */ return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Z e r o K e r n e l N a n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZeroKernelNans() replaces any special 'nan' value that may be present in % the kernel with a zero value. This is typically done when the kernel will % be used in special hardware (GPU) convolution processors, to simply % matters. % % The format of the ZeroKernelNans method is: % % void ZeroKernelNans (KernelInfo *kernel) % % A description of each parameter follows: % % o kernel: the Morphology/Convolution kernel % */ MagickExport void ZeroKernelNans(KernelInfo *kernel) { register size_t i; /* do the other kernels in a multi-kernel list first */ if ( kernel->next != (KernelInfo *) NULL) ZeroKernelNans(kernel->next); for (i=0; i < (kernel->width*kernel->height); i++) if ( IsNan(kernel->values[i]) ) kernel->values[i] = 0.0; return; }
tensor_voting.h
#ifndef CVD_INC_TENSOR_VOTE_H #define CVD_INC_TENSOR_VOTE_H #include <cvd/image.h> #include <TooN/TooN.h> #include <TooN/helpers.h> #include <vector> #include <utility> namespace CVD { #ifndef DOXYGEN_IGNORE_INTERNAL namespace TensorVoting { struct TV_coord { std::ptrdiff_t o; int x; int y; }; std::vector<std::pair<TV_coord, TooN::Matrix<2> > > compute_a_tensor_kernel(int radius, double cutoff, double angle, double sigma, double ratio, int row_stride); inline unsigned int quantize_half_angle(double r, int num_divs) { return ((int)floor((r/M_PI+100) * num_divs + 0.5)) % num_divs; } } #endif /** This function performs tensor voting on the gradients of an image. The voting is performed densely at each pixel, and the contribution of each pixel is scaled by its gradient magnitude. The kernel for voting is computed as follows. Consider that there is a point at \f$(0,0)\f$, with gradient normal \f$(0,1)\f$. This will make a contribution to the point \f$(x,y)\f$. The arc-length, \f$l\f$, of the arc passing through \f$(0,0)\f$, tangent to the gradient at this point and also passing through \f$(x, y)\f$ is: \f[ l = 2 r \theta \f] Where \f[ \theta = \tan^{-1}\frac{y}{x} \f] and the radius of the arc, \f$r\f$ is: \f[ r = \frac{x^2 + y^2}{2y}. \f] The scale of the contribution is: \f[ s = e^{-\frac{l^2}{\sigma^2} - \kappa\frac{\sigma^2}{r^2}}. \f] Note that this is achieved by scaling \f$x\f$ and \f$y\f$ by \f$\sigma\f$, so \f$\kappa\f$ controls the kernel shape independent of the size. The complete tensor contribution is therefore: \f[ e^{-\frac{l^2}{\sigma^2} - \kappa\frac{\sigma^2}{r^2}} \left[ \begin{array}{c} \cos 2\theta\\ \sin 2\theta \end{array} \right] [ \cos 2\theta\ \ \sin 2\theta] \f] @param image The image on which to perform tensor voting @param sigma \f$ \sigma \f$ @param ratio \f$ \kappa \f$ @param cutoff When \f$s\f$ points drop below the cutoff, it is set to zero. @param num_divs The voting kernels are quantized by angle in to this many dicisions in the half-circle. @ingroup gVision **/ template<class C> Image<TooN::Matrix<2> > dense_tensor_vote_gradients(const BasicImage<C>& image, double sigma, double ratio, double cutoff=0.001, unsigned int num_divs = 4096) { using TooN::Matrix; using std::pair; using std::vector; using TensorVoting::TV_coord; Matrix<2> zero(TooN::Zeros); Image<Matrix<2> > field(image.size(), zero); //Kernel values go as exp(-x*x / sigma * sigma) //So, for cutoff = exp(-x*x / sigma * sigma) //ln cutoff = -x*x / sigma*sigma //x = sigma * sqrt(-ln cutoff) int kernel_radius = (int)ceil(sigma * sqrt(-log(cutoff))); //First, build up the kernels vector<vector<pair<TV_coord, Matrix<2> > > > kernels; for(unsigned int i=0; i < num_divs; i++) { double angle = M_PI * i / num_divs; kernels.push_back(TensorVoting::compute_a_tensor_kernel(kernel_radius, cutoff, angle, sigma, ratio, field.row_stride())); } for(int y= kernel_radius; y < field.size().y - kernel_radius; y++) for(int x= kernel_radius; x < field.size().x - kernel_radius; x++) { double gx = ((double)image[y][x+1] - image[y][x-1])/2.; double gy = ((double)image[y+1][x] - image[y-1][x])/2.; double scale = sqrt(gx*gx + gy*gy); unsigned int direction = TensorVoting::quantize_half_angle(M_PI/2 + atan2(gy,gx), num_divs); const vector<pair<TV_coord, Matrix<2> > >& kernel = kernels[direction]; Matrix<2>* p = &field[y][x]; //The matrices are all symmetric, so only use the upper right triangle. for(unsigned int i=0; i < kernel.size(); i++) { p[kernel[i].first.o][0][0] += kernel[i].second[0][0] * scale; p[kernel[i].first.o][0][1] += kernel[i].second[0][1] * scale; p[kernel[i].first.o][1][1] += kernel[i].second[1][1] * scale; } } //Now do the edges for(int y= 1; y < field.size().y-1; y++) { for(int x= 1; x < field.size().x-1; x++) { //Skip the middle bit if(y >= kernel_radius && y < field.size().y - kernel_radius && x == kernel_radius) x = field.size().x - kernel_radius; double gx = ((double)image[y][x+1] - image[y][x-1])/2.; double gy = ((double)image[y+1][x] - image[y-1][x])/2.; double scale = sqrt(gx*gx + gy*gy); unsigned int direction = TensorVoting::quantize_half_angle(M_PI/2 + atan(gy / gx), num_divs); const vector<pair<TV_coord, Matrix<2> > >& kernel = kernels[direction]; Matrix<2>* p = &field[y][x]; //The matrices are all symmetric, so only use the upper right triangle. for(unsigned int i=0; i < kernel.size(); i++) { if(kernel[i].first.y+y >= 0 && kernel[i].first.y+y < field.size().y && kernel[i].first.x+x >= 0 && kernel[i].first.x+x < field.size().x) { p[kernel[i].first.o][0][0] += kernel[i].second[0][0] * scale; p[kernel[i].first.o][0][1] += kernel[i].second[0][1] * scale; p[kernel[i].first.o][1][1] += kernel[i].second[1][1] * scale; } } } } //Copy over bits to make the matrices symmetric for(Image<Matrix<2> >:: iterator i=field.begin(); i != field.end(); i++) (*i)[1][0] = (*i)[0][1]; return field; } #ifdef CVD_EXPERIMENTAL template<class C> Image<TooN::Matrix<2> > dense_tensor_vote_gradients_fast(const BasicImage<C>& image, double sigma, double ratio, double cutoff=0.001, int num_divs = 4096) { using TooN::Matrix; using std::pair; using std::make_pair; using std::vector; using TensorVoting::TV_coord; Matrix<2> zero(TooN::Zeros); Image<Matrix<2> > ffield(image.size(), zero); Image<__m128> field(image.size()); field.zero(); //In much the same way as dense_tensor_vote_gradients, build up the kernel. int kernel_radius = (int)ceil(sigma * sqrt(-log(cutoff))); vector<vector<pair<TV_coord, Matrix<2> > > > matrix_kernels; for(int i=0; i < num_divs; i++) { double angle = M_PI * i / num_divs; matrix_kernels.push_back(TensorVoting::compute_a_tensor_kernel(kernel_radius, cutoff, angle, sigma, ratio, field.row_stride())); } //Put the kernel in aligned SSE registers. //Image<__m128> is used since it guarantees SSE aligned memory. vector<vector<int> > kernel_offsets; vector<Image<__m128> > kernel_values; for(unsigned int i=0; i < matrix_kernels.size(); i++) { vector<int> off(matrix_kernels[i].size()); Image<__m128> val(ImageRef(matrix_kernels[i].size(), 1)); for(unsigned int j=0; j < matrix_kernels[i].size(); j++) { off[j] = matrix_kernels[i][j].first.o; Matrix<2>& m = matrix_kernels[i][j].second; val.data()[j] = _mm_setr_ps(m[0][0], m[0][1], m[1][0], m[1][1]); } kernel_offsets.push_back(off); kernel_values.push_back(val); } #pragma omp parallel for for(int y= kernel_radius; y < field.size().y - kernel_radius; y++) for(int x= kernel_radius; x < field.size().x - kernel_radius; x++) { float gx = ((float)image[y][x+1] - image[y][x-1])/2.; float gy = ((float)image[y+1][x] - image[y-1][x])/2.; float scale = sqrt(gx*gx + gy*gy); unsigned int direction = TensorVoting::quantize_half_angle(M_PI/2 + atan(gy / gx), num_divs); const vector<int> & off = kernel_offsets[direction]; __m128* val = kernel_values[direction].data(); __m128* p = &field[y][x]; __m128 s = _mm_set1_ps(scale); for(unsigned int i=0; i < off.size(); i++) p[off[i]] = _mm_add_ps(p[off[i]], _mm_mul_ps(val[i], s)); } for(int y=0; y < field.size().y; y++) for(int x=0; x < field.size().x; x++) { float f[4]; _mm_storeu_ps(f, field[y][x]); ffield[y][x][0][0] = f[0]; ffield[y][x][0][1] = f[1]; ffield[y][x][1][0] = f[2]; ffield[y][x][1][1] = f[3]; } return ffield; } #endif } #endif
implicit_blender.c
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) Blender Foundation * All rights reserved. */ /** \file * \ingroup bph */ #include "implicit.h" #ifdef IMPLICIT_SOLVER_BLENDER # include "MEM_guardedalloc.h" # include "DNA_scene_types.h" # include "DNA_object_types.h" # include "DNA_object_force_types.h" # include "DNA_meshdata_types.h" # include "DNA_texture_types.h" # include "BLI_math.h" # include "BLI_utildefines.h" # include "BKE_cloth.h" # include "BKE_collision.h" # include "BKE_effect.h" # include "BPH_mass_spring.h" # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wtype-limits" # endif # ifdef _OPENMP # define CLOTH_OPENMP_LIMIT 512 # endif //#define DEBUG_TIME # ifdef DEBUG_TIME # include "PIL_time.h" # endif static float I[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static float ZERO[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; # if 0 # define C99 # ifdef C99 # defineDO_INLINE inline # else # defineDO_INLINE static # endif # endif /* if 0 */ struct Cloth; ////////////////////////////////////////// /* fast vector / matrix library, enhancements are welcome :) -dg */ ///////////////////////////////////////// /* DEFINITIONS */ typedef float lfVector[3]; typedef struct fmatrix3x3 { float m[3][3]; /* 3x3 matrix */ unsigned int c, r; /* column and row number */ /* int pinned; // is this vertex allowed to move? */ float n1, n2, n3; /* three normal vectors for collision constrains */ unsigned int vcount; /* vertex count */ unsigned int scount; /* spring count */ } fmatrix3x3; /////////////////////////// // float[3] vector /////////////////////////// /* simple vector code */ /* STATUS: verified */ DO_INLINE void mul_fvector_S(float to[3], float from[3], float scalar) { to[0] = from[0] * scalar; to[1] = from[1] * scalar; to[2] = from[2] * scalar; } /* simple v^T * v product ("outer product") */ /* STATUS: HAS TO BE verified (*should* work) */ DO_INLINE void mul_fvectorT_fvector(float to[3][3], float vectorA[3], float vectorB[3]) { mul_fvector_S(to[0], vectorB, vectorA[0]); mul_fvector_S(to[1], vectorB, vectorA[1]); mul_fvector_S(to[2], vectorB, vectorA[2]); } /* simple v^T * v product with scalar ("outer product") */ /* STATUS: HAS TO BE verified (*should* work) */ DO_INLINE void mul_fvectorT_fvectorS(float to[3][3], float vectorA[3], float vectorB[3], float aS) { mul_fvectorT_fvector(to, vectorA, vectorB); mul_fvector_S(to[0], to[0], aS); mul_fvector_S(to[1], to[1], aS); mul_fvector_S(to[2], to[2], aS); } # if 0 /* printf vector[3] on console: for debug output */ static void print_fvector(float m3[3]) { printf("%f\n%f\n%f\n\n", m3[0], m3[1], m3[2]); } /////////////////////////// // long float vector float (*)[3] /////////////////////////// /* print long vector on console: for debug output */ DO_INLINE void print_lfvector(float (*fLongVector)[3], unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { print_fvector(fLongVector[i]); } } # endif /* create long vector */ DO_INLINE lfVector *create_lfvector(unsigned int verts) { /* TODO: check if memory allocation was successful */ return (lfVector *)MEM_callocN(verts * sizeof(lfVector), "cloth_implicit_alloc_vector"); // return (lfVector *)cloth_aligned_malloc(&MEMORY_BASE, verts * sizeof(lfVector)); } /* delete long vector */ DO_INLINE void del_lfvector(float (*fLongVector)[3]) { if (fLongVector != NULL) { MEM_freeN(fLongVector); // cloth_aligned_free(&MEMORY_BASE, fLongVector); } } /* copy long vector */ DO_INLINE void cp_lfvector(float (*to)[3], float (*from)[3], unsigned int verts) { memcpy(to, from, verts * sizeof(lfVector)); } /* init long vector with float[3] */ DO_INLINE void init_lfvector(float (*fLongVector)[3], float vector[3], unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { copy_v3_v3(fLongVector[i], vector); } } /* zero long vector with float[3] */ DO_INLINE void zero_lfvector(float (*to)[3], unsigned int verts) { memset(to, 0.0f, verts * sizeof(lfVector)); } /* multiply long vector with scalar*/ DO_INLINE void mul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { mul_fvector_S(to[i], fLongVector[i], scalar); } } /* multiply long vector with scalar*/ /* A -= B * float */ DO_INLINE void submul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { VECSUBMUL(to[i], fLongVector[i], scalar); } } /* dot product for big vector */ DO_INLINE float dot_lfvector(float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts) { long i = 0; float temp = 0.0; // XXX brecht, disabled this for now (first schedule line was already disabled), // due to non-commutative nature of floating point ops this makes the sim give // different results each time you run it! // schedule(guided, 2) //#pragma omp parallel for reduction(+: temp) if (verts > CLOTH_OPENMP_LIMIT) for (i = 0; i < (long)verts; i++) { temp += dot_v3v3(fLongVectorA[i], fLongVectorB[i]); } return temp; } /* A = B + C --> for big vector */ DO_INLINE void add_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { add_v3_v3v3(to[i], fLongVectorA[i], fLongVectorB[i]); } } /* A = B + C * float --> for big vector */ DO_INLINE void add_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { VECADDS(to[i], fLongVectorA[i], fLongVectorB[i], bS); } } /* A = B * float + C * float --> for big vector */ DO_INLINE void add_lfvectorS_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float aS, float (*fLongVectorB)[3], float bS, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { VECADDSS(to[i], fLongVectorA[i], aS, fLongVectorB[i], bS); } } /* A = B - C * float --> for big vector */ DO_INLINE void sub_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { VECSUBS(to[i], fLongVectorA[i], fLongVectorB[i], bS); } } /* A = B - C --> for big vector */ DO_INLINE void sub_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { sub_v3_v3v3(to[i], fLongVectorA[i], fLongVectorB[i]); } } /////////////////////////// // 3x3 matrix /////////////////////////// # if 0 /* printf 3x3 matrix on console: for debug output */ static void print_fmatrix(float m3[3][3]) { printf("%f\t%f\t%f\n", m3[0][0], m3[0][1], m3[0][2]); printf("%f\t%f\t%f\n", m3[1][0], m3[1][1], m3[1][2]); printf("%f\t%f\t%f\n\n", m3[2][0], m3[2][1], m3[2][2]); } static void print_sparse_matrix(fmatrix3x3 *m) { if (m) { unsigned int i; for (i = 0; i < m[0].vcount + m[0].scount; i++) { printf("%d:\n", i); print_fmatrix(m[i].m); } } } # endif # if 0 static void print_lvector(lfVector *v, int numverts) { int i; for (i = 0; i < numverts; i++) { if (i > 0) { printf("\n"); } printf("%f,\n", v[i][0]); printf("%f,\n", v[i][1]); printf("%f,\n", v[i][2]); } } # endif # if 0 static void print_bfmatrix(fmatrix3x3 *m) { int tot = m[0].vcount + m[0].scount; int size = m[0].vcount * 3; float *t = MEM_callocN(sizeof(float) * size * size, "bfmatrix"); int q, i, j; for (q = 0; q < tot; q++) { int k = 3 * m[q].r; int l = 3 * m[q].c; for (j = 0; j < 3; j++) { for (i = 0; i < 3; i++) { // if (t[k + i + (l + j) * size] != 0.0f) { // printf("warning: overwriting value at %d, %d\n", m[q].r, m[q].c); // } if (k == l) { t[k + i + (k + j) * size] += m[q].m[i][j]; } else { t[k + i + (l + j) * size] += m[q].m[i][j]; t[l + j + (k + i) * size] += m[q].m[j][i]; } } } } for (j = 0; j < size; j++) { if (j > 0 && j % 3 == 0) { printf("\n"); } for (i = 0; i < size; i++) { if (i > 0 && i % 3 == 0) { printf(" "); } implicit_print_matrix_elem(t[i + j * size]); } printf("\n"); } MEM_freeN(t); } # endif /* copy 3x3 matrix */ DO_INLINE void cp_fmatrix(float to[3][3], float from[3][3]) { // memcpy(to, from, sizeof (float) * 9); copy_v3_v3(to[0], from[0]); copy_v3_v3(to[1], from[1]); copy_v3_v3(to[2], from[2]); } /* copy 3x3 matrix */ DO_INLINE void initdiag_fmatrixS(float to[3][3], float aS) { cp_fmatrix(to, ZERO); to[0][0] = aS; to[1][1] = aS; to[2][2] = aS; } # if 0 /* calculate determinant of 3x3 matrix */ DO_INLINE float det_fmatrix(float m[3][3]) { return m[0][0] * m[1][1] * m[2][2] + m[1][0] * m[2][1] * m[0][2] + m[0][1] * m[1][2] * m[2][0] - m[0][0] * m[1][2] * m[2][1] - m[0][1] * m[1][0] * m[2][2] - m[2][0] * m[1][1] * m[0][2]; } DO_INLINE void inverse_fmatrix(float to[3][3], float from[3][3]) { unsigned int i, j; float d; if ((d = det_fmatrix(from)) == 0) { printf("can't build inverse"); exit(0); } for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { int i1 = (i + 1) % 3; int i2 = (i + 2) % 3; int j1 = (j + 1) % 3; int j2 = (j + 2) % 3; /** Reverse indexes i&j to take transpose. */ to[j][i] = (from[i1][j1] * from[i2][j2] - from[i1][j2] * from[i2][j1]) / d; /** * <pre> * if (i == j) { * to[i][j] = 1.0f / from[i][j]; * } * else { * to[i][j] = 0; * } * </pre> */ } } } # endif /* 3x3 matrix multiplied by a scalar */ /* STATUS: verified */ DO_INLINE void mul_fmatrix_S(float matrix[3][3], float scalar) { mul_fvector_S(matrix[0], matrix[0], scalar); mul_fvector_S(matrix[1], matrix[1], scalar); mul_fvector_S(matrix[2], matrix[2], scalar); } /* a vector multiplied by a 3x3 matrix */ /* STATUS: verified */ DO_INLINE void mul_fvector_fmatrix(float *to, float *from, float matrix[3][3]) { to[0] = matrix[0][0] * from[0] + matrix[1][0] * from[1] + matrix[2][0] * from[2]; to[1] = matrix[0][1] * from[0] + matrix[1][1] * from[1] + matrix[2][1] * from[2]; to[2] = matrix[0][2] * from[0] + matrix[1][2] * from[1] + matrix[2][2] * from[2]; } /* 3x3 matrix multiplied by a vector */ /* STATUS: verified */ DO_INLINE void mul_fmatrix_fvector(float *to, float matrix[3][3], float from[3]) { to[0] = dot_v3v3(matrix[0], from); to[1] = dot_v3v3(matrix[1], from); to[2] = dot_v3v3(matrix[2], from); } /* 3x3 matrix addition with 3x3 matrix */ DO_INLINE void add_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3]) { add_v3_v3v3(to[0], matrixA[0], matrixB[0]); add_v3_v3v3(to[1], matrixA[1], matrixB[1]); add_v3_v3v3(to[2], matrixA[2], matrixB[2]); } /* A -= B*x + C*y (3x3 matrix sub-addition with 3x3 matrix) */ DO_INLINE void subadd_fmatrixS_fmatrixS( float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS) { VECSUBADDSS(to[0], matrixA[0], aS, matrixB[0], bS); VECSUBADDSS(to[1], matrixA[1], aS, matrixB[1], bS); VECSUBADDSS(to[2], matrixA[2], aS, matrixB[2], bS); } /* A = B - C (3x3 matrix subtraction with 3x3 matrix) */ DO_INLINE void sub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3]) { sub_v3_v3v3(to[0], matrixA[0], matrixB[0]); sub_v3_v3v3(to[1], matrixA[1], matrixB[1]); sub_v3_v3v3(to[2], matrixA[2], matrixB[2]); } ///////////////////////////////////////////////////////////////// // special functions ///////////////////////////////////////////////////////////////// /* 3x3 matrix multiplied+added by a vector */ /* STATUS: verified */ DO_INLINE void muladd_fmatrix_fvector(float to[3], float matrix[3][3], float from[3]) { to[0] += dot_v3v3(matrix[0], from); to[1] += dot_v3v3(matrix[1], from); to[2] += dot_v3v3(matrix[2], from); } DO_INLINE void muladd_fmatrixT_fvector(float to[3], float matrix[3][3], float from[3]) { to[0] += matrix[0][0] * from[0] + matrix[1][0] * from[1] + matrix[2][0] * from[2]; to[1] += matrix[0][1] * from[0] + matrix[1][1] * from[1] + matrix[2][1] * from[2]; to[2] += matrix[0][2] * from[0] + matrix[1][2] * from[1] + matrix[2][2] * from[2]; } BLI_INLINE void outerproduct(float r[3][3], const float a[3], const float b[3]) { mul_v3_v3fl(r[0], a, b[0]); mul_v3_v3fl(r[1], a, b[1]); mul_v3_v3fl(r[2], a, b[2]); } BLI_INLINE void cross_m3_v3m3(float r[3][3], const float v[3], float m[3][3]) { cross_v3_v3v3(r[0], v, m[0]); cross_v3_v3v3(r[1], v, m[1]); cross_v3_v3v3(r[2], v, m[2]); } BLI_INLINE void cross_v3_identity(float r[3][3], const float v[3]) { r[0][0] = 0.0f; r[1][0] = v[2]; r[2][0] = -v[1]; r[0][1] = -v[2]; r[1][1] = 0.0f; r[2][1] = v[0]; r[0][2] = v[1]; r[1][2] = -v[0]; r[2][2] = 0.0f; } BLI_INLINE void madd_m3_m3fl(float r[3][3], float m[3][3], float f) { r[0][0] += m[0][0] * f; r[0][1] += m[0][1] * f; r[0][2] += m[0][2] * f; r[1][0] += m[1][0] * f; r[1][1] += m[1][1] * f; r[1][2] += m[1][2] * f; r[2][0] += m[2][0] * f; r[2][1] += m[2][1] * f; r[2][2] += m[2][2] * f; } ///////////////////////////////////////////////////////////////// /////////////////////////// // SPARSE SYMMETRIC big matrix with 3x3 matrix entries /////////////////////////// /* printf a big matrix on console: for debug output */ # if 0 static void print_bfmatrix(fmatrix3x3 *m3) { unsigned int i = 0; for (i = 0; i < m3[0].vcount + m3[0].scount; i++) { print_fmatrix(m3[i].m); } } # endif BLI_INLINE void init_fmatrix(fmatrix3x3 *matrix, int r, int c) { matrix->r = r; matrix->c = c; } /* create big matrix */ DO_INLINE fmatrix3x3 *create_bfmatrix(unsigned int verts, unsigned int springs) { // TODO: check if memory allocation was successful */ fmatrix3x3 *temp = (fmatrix3x3 *)MEM_callocN(sizeof(fmatrix3x3) * (verts + springs), "cloth_implicit_alloc_matrix"); int i; temp[0].vcount = verts; temp[0].scount = springs; /* vertex part of the matrix is diagonal blocks */ for (i = 0; i < verts; i++) { init_fmatrix(temp + i, i, i); } return temp; } /* delete big matrix */ DO_INLINE void del_bfmatrix(fmatrix3x3 *matrix) { if (matrix != NULL) { MEM_freeN(matrix); } } /* copy big matrix */ DO_INLINE void cp_bfmatrix(fmatrix3x3 *to, fmatrix3x3 *from) { // TODO bounds checking memcpy(to, from, sizeof(fmatrix3x3) * (from[0].vcount + from[0].scount)); } /* init big matrix */ // slow in parallel DO_INLINE void init_bfmatrix(fmatrix3x3 *matrix, float m3[3][3]) { unsigned int i; for (i = 0; i < matrix[0].vcount + matrix[0].scount; i++) { cp_fmatrix(matrix[i].m, m3); } } /* init the diagonal of big matrix */ // slow in parallel DO_INLINE void initdiag_bfmatrix(fmatrix3x3 *matrix, float m3[3][3]) { unsigned int i, j; float tmatrix[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; for (i = 0; i < matrix[0].vcount; i++) { cp_fmatrix(matrix[i].m, m3); } for (j = matrix[0].vcount; j < matrix[0].vcount + matrix[0].scount; j++) { cp_fmatrix(matrix[j].m, tmatrix); } } /* SPARSE SYMMETRIC multiply big matrix with long vector*/ /* STATUS: verified */ DO_INLINE void mul_bfmatrix_lfvector(float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector) { unsigned int vcount = from[0].vcount; lfVector *temp = create_lfvector(vcount); zero_lfvector(to, vcount); # pragma omp parallel sections if (vcount > CLOTH_OPENMP_LIMIT) { # pragma omp section { for (unsigned int i = from[0].vcount; i < from[0].vcount + from[0].scount; i++) { /* This is the lower triangle of the sparse matrix, * therefore multiplication occurs with transposed submatrices. */ muladd_fmatrixT_fvector(to[from[i].c], from[i].m, fLongVector[from[i].r]); } } # pragma omp section { for (unsigned int i = 0; i < from[0].vcount + from[0].scount; i++) { muladd_fmatrix_fvector(temp[from[i].r], from[i].m, fLongVector[from[i].c]); } } } add_lfvector_lfvector(to, to, temp, from[0].vcount); del_lfvector(temp); } /* SPARSE SYMMETRIC sub big matrix with big matrix*/ /* A -= B * float + C * float --> for big matrix */ /* VERIFIED */ DO_INLINE void subadd_bfmatrixS_bfmatrixS( fmatrix3x3 *to, fmatrix3x3 *from, float aS, fmatrix3x3 *matrix, float bS) { unsigned int i = 0; /* process diagonal elements */ for (i = 0; i < matrix[0].vcount + matrix[0].scount; i++) { subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS); } } /////////////////////////////////////////////////////////////////// // simulator start /////////////////////////////////////////////////////////////////// typedef struct Implicit_Data { /* inputs */ fmatrix3x3 *bigI; /* identity (constant) */ fmatrix3x3 *tfm; /* local coordinate transform */ fmatrix3x3 *M; /* masses */ lfVector *F; /* forces */ fmatrix3x3 *dFdV, *dFdX; /* force jacobians */ int num_blocks; /* number of off-diagonal blocks (springs) */ /* motion state data */ lfVector *X, *Xnew; /* positions */ lfVector *V, *Vnew; /* velocities */ /* internal solver data */ lfVector *B; /* B for A*dV = B */ fmatrix3x3 *A; /* A for A*dV = B */ lfVector *dV; /* velocity change (solution of A*dV = B) */ lfVector *z; /* target velocity in constrained directions */ fmatrix3x3 *S; /* filtering matrix for constraints */ fmatrix3x3 *P, *Pinv; /* pre-conditioning matrix */ } Implicit_Data; Implicit_Data *BPH_mass_spring_solver_create(int numverts, int numsprings) { Implicit_Data *id = (Implicit_Data *)MEM_callocN(sizeof(Implicit_Data), "implicit vecmat"); /* process diagonal elements */ id->tfm = create_bfmatrix(numverts, 0); id->A = create_bfmatrix(numverts, numsprings); id->dFdV = create_bfmatrix(numverts, numsprings); id->dFdX = create_bfmatrix(numverts, numsprings); id->S = create_bfmatrix(numverts, 0); id->Pinv = create_bfmatrix(numverts, numsprings); id->P = create_bfmatrix(numverts, numsprings); id->bigI = create_bfmatrix(numverts, numsprings); // TODO 0 springs id->M = create_bfmatrix(numverts, numsprings); id->X = create_lfvector(numverts); id->Xnew = create_lfvector(numverts); id->V = create_lfvector(numverts); id->Vnew = create_lfvector(numverts); id->F = create_lfvector(numverts); id->B = create_lfvector(numverts); id->dV = create_lfvector(numverts); id->z = create_lfvector(numverts); initdiag_bfmatrix(id->bigI, I); return id; } void BPH_mass_spring_solver_free(Implicit_Data *id) { del_bfmatrix(id->tfm); del_bfmatrix(id->A); del_bfmatrix(id->dFdV); del_bfmatrix(id->dFdX); del_bfmatrix(id->S); del_bfmatrix(id->P); del_bfmatrix(id->Pinv); del_bfmatrix(id->bigI); del_bfmatrix(id->M); del_lfvector(id->X); del_lfvector(id->Xnew); del_lfvector(id->V); del_lfvector(id->Vnew); del_lfvector(id->F); del_lfvector(id->B); del_lfvector(id->dV); del_lfvector(id->z); MEM_freeN(id); } /* ==== Transformation from/to root reference frames ==== */ BLI_INLINE void world_to_root_v3(Implicit_Data *data, int index, float r[3], const float v[3]) { copy_v3_v3(r, v); mul_transposed_m3_v3(data->tfm[index].m, r); } BLI_INLINE void root_to_world_v3(Implicit_Data *data, int index, float r[3], const float v[3]) { mul_v3_m3v3(r, data->tfm[index].m, v); } BLI_INLINE void world_to_root_m3(Implicit_Data *data, int index, float r[3][3], float m[3][3]) { float trot[3][3]; copy_m3_m3(trot, data->tfm[index].m); transpose_m3(trot); mul_m3_m3m3(r, trot, m); } BLI_INLINE void root_to_world_m3(Implicit_Data *data, int index, float r[3][3], float m[3][3]) { mul_m3_m3m3(r, data->tfm[index].m, m); } /* ================================ */ DO_INLINE void filter(lfVector *V, fmatrix3x3 *S) { unsigned int i = 0; for (i = 0; i < S[0].vcount; i++) { mul_m3_v3(S[i].m, V[S[i].r]); } } /* this version of the CG algorithm does not work very well with partial constraints * (where S has non-zero elements). */ # if 0 static int cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S) { // Solves for unknown X in equation AX=B unsigned int conjgrad_loopcount = 0, conjgrad_looplimit = 100; float conjgrad_epsilon = 0.0001f /* , conjgrad_lasterror=0 */ /* UNUSED */; lfVector *q, *d, *tmp, *r; float s, starget, a, s_prev; unsigned int numverts = lA[0].vcount; q = create_lfvector(numverts); d = create_lfvector(numverts); tmp = create_lfvector(numverts); r = create_lfvector(numverts); // zero_lfvector(ldV, CLOTHPARTICLES); filter(ldV, S); add_lfvector_lfvector(ldV, ldV, z, numverts); // r = B - Mul(tmp, A, X); // just use B if X known to be zero cp_lfvector(r, lB, numverts); mul_bfmatrix_lfvector(tmp, lA, ldV); sub_lfvector_lfvector(r, r, tmp, numverts); filter(r, S); cp_lfvector(d, r, numverts); s = dot_lfvector(r, r, numverts); starget = s * sqrtf(conjgrad_epsilon); while (s > starget && conjgrad_loopcount < conjgrad_looplimit) { // Mul(q, A, d); // q = A*d; mul_bfmatrix_lfvector(q, lA, d); filter(q, S); a = s / dot_lfvector(d, q, numverts); // X = X + d*a; add_lfvector_lfvectorS(ldV, ldV, d, a, numverts); // r = r - q*a; sub_lfvector_lfvectorS(r, r, q, a, numverts); s_prev = s; s = dot_lfvector(r, r, numverts); //d = r+d*(s/s_prev); add_lfvector_lfvectorS(d, r, d, (s / s_prev), numverts); filter(d, S); conjgrad_loopcount++; } /* conjgrad_lasterror = s; */ /* UNUSED */ del_lfvector(q); del_lfvector(d); del_lfvector(tmp); del_lfvector(r); // printf("W/O conjgrad_loopcount: %d\n", conjgrad_loopcount); return conjgrad_loopcount < conjgrad_looplimit; // true means we reached desired accuracy in given time - ie stable } # endif static int cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, ImplicitSolverResult *result) { // Solves for unknown X in equation AX=B unsigned int conjgrad_loopcount = 0, conjgrad_looplimit = 100; float conjgrad_epsilon = 0.01f; unsigned int numverts = lA[0].vcount; lfVector *fB = create_lfvector(numverts); lfVector *AdV = create_lfvector(numverts); lfVector *r = create_lfvector(numverts); lfVector *c = create_lfvector(numverts); lfVector *q = create_lfvector(numverts); lfVector *s = create_lfvector(numverts); float bnorm2, delta_new, delta_old, delta_target, alpha; cp_lfvector(ldV, z, numverts); /* d0 = filter(B)^T * P * filter(B) */ cp_lfvector(fB, lB, numverts); filter(fB, S); bnorm2 = dot_lfvector(fB, fB, numverts); delta_target = conjgrad_epsilon * conjgrad_epsilon * bnorm2; /* r = filter(B - A * dV) */ mul_bfmatrix_lfvector(AdV, lA, ldV); sub_lfvector_lfvector(r, lB, AdV, numverts); filter(r, S); /* c = filter(P^-1 * r) */ cp_lfvector(c, r, numverts); filter(c, S); /* delta = r^T * c */ delta_new = dot_lfvector(r, c, numverts); # ifdef IMPLICIT_PRINT_SOLVER_INPUT_OUTPUT printf("==== A ====\n"); print_bfmatrix(lA); printf("==== z ====\n"); print_lvector(z, numverts); printf("==== B ====\n"); print_lvector(lB, numverts); printf("==== S ====\n"); print_bfmatrix(S); # endif while (delta_new > delta_target && conjgrad_loopcount < conjgrad_looplimit) { mul_bfmatrix_lfvector(q, lA, c); filter(q, S); alpha = delta_new / dot_lfvector(c, q, numverts); add_lfvector_lfvectorS(ldV, ldV, c, alpha, numverts); add_lfvector_lfvectorS(r, r, q, -alpha, numverts); /* s = P^-1 * r */ cp_lfvector(s, r, numverts); delta_old = delta_new; delta_new = dot_lfvector(r, s, numverts); add_lfvector_lfvectorS(c, s, c, delta_new / delta_old, numverts); filter(c, S); conjgrad_loopcount++; } # ifdef IMPLICIT_PRINT_SOLVER_INPUT_OUTPUT printf("==== dV ====\n"); print_lvector(ldV, numverts); printf("========\n"); # endif del_lfvector(fB); del_lfvector(AdV); del_lfvector(r); del_lfvector(c); del_lfvector(q); del_lfvector(s); // printf("W/O conjgrad_loopcount: %d\n", conjgrad_loopcount); result->status = conjgrad_loopcount < conjgrad_looplimit ? BPH_SOLVER_SUCCESS : BPH_SOLVER_NO_CONVERGENCE; result->iterations = conjgrad_loopcount; result->error = bnorm2 > 0.0f ? sqrtf(delta_new / bnorm2) : 0.0f; return conjgrad_loopcount < conjgrad_looplimit; // true means we reached desired accuracy in given time - ie stable } # if 0 // block diagonalizer DO_INLINE void BuildPPinv(fmatrix3x3 *lA, fmatrix3x3 *P, fmatrix3x3 *Pinv) { unsigned int i = 0; // Take only the diagonal blocks of A // #pragma omp parallel for private(i) if (lA[0].vcount > CLOTH_OPENMP_LIMIT) for (i = 0; i < lA[0].vcount; i++) { // block diagonalizer cp_fmatrix(P[i].m, lA[i].m); inverse_fmatrix(Pinv[i].m, P[i].m); } } # if 0 // version 1.3 static int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv) { unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit = 100; float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0; float conjgrad_epsilon = 0.0001; // 0.2 is dt for steps=5 lfVector *r = create_lfvector(numverts); lfVector *p = create_lfvector(numverts); lfVector *s = create_lfvector(numverts); lfVector *h = create_lfvector(numverts); BuildPPinv(lA, P, Pinv); filter(dv, S); add_lfvector_lfvector(dv, dv, z, numverts); mul_bfmatrix_lfvector(r, lA, dv); sub_lfvector_lfvector(r, lB, r, numverts); filter(r, S); mul_prevfmatrix_lfvector(p, Pinv, r); filter(p, S); deltaNew = dot_lfvector(r, p, numverts); delta0 = deltaNew * sqrt(conjgrad_epsilon); # ifdef DEBUG_TIME double start = PIL_check_seconds_timer(); # endif while ((deltaNew > delta0) && (iterations < conjgrad_looplimit)) { iterations++; mul_bfmatrix_lfvector(s, lA, p); filter(s, S); alpha = deltaNew / dot_lfvector(p, s, numverts); add_lfvector_lfvectorS(dv, dv, p, alpha, numverts); add_lfvector_lfvectorS(r, r, s, -alpha, numverts); mul_prevfmatrix_lfvector(h, Pinv, r); filter(h, S); deltaOld = deltaNew; deltaNew = dot_lfvector(r, h, numverts); add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts); filter(p, S); } # ifdef DEBUG_TIME double end = PIL_check_seconds_timer(); printf("cg_filtered_pre time: %f\n", (float)(end - start)); # endif del_lfvector(h); del_lfvector(s); del_lfvector(p); del_lfvector(r); printf("iterations: %d\n", iterations); return iterations < conjgrad_looplimit; } # endif // version 1.4 static int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv, fmatrix3x3 *bigI) { unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit = 100; float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0, tol = 0; lfVector *r = create_lfvector(numverts); lfVector *p = create_lfvector(numverts); lfVector *s = create_lfvector(numverts); lfVector *h = create_lfvector(numverts); lfVector *bhat = create_lfvector(numverts); lfVector *btemp = create_lfvector(numverts); BuildPPinv(lA, P, Pinv); initdiag_bfmatrix(bigI, I); sub_bfmatrix_Smatrix(bigI, bigI, S); // x = Sx_0+(I-S)z filter(dv, S); add_lfvector_lfvector(dv, dv, z, numverts); // b_hat = S(b-A(I-S)z) mul_bfmatrix_lfvector(r, lA, z); mul_bfmatrix_lfvector(bhat, bigI, r); sub_lfvector_lfvector(bhat, lB, bhat, numverts); // r = S(b-Ax) mul_bfmatrix_lfvector(r, lA, dv); sub_lfvector_lfvector(r, lB, r, numverts); filter(r, S); // p = SP^-1r mul_prevfmatrix_lfvector(p, Pinv, r); filter(p, S); // delta0 = bhat^TP^-1bhat mul_prevfmatrix_lfvector(btemp, Pinv, bhat); delta0 = dot_lfvector(bhat, btemp, numverts); // deltaNew = r^TP deltaNew = dot_lfvector(r, p, numverts); # if 0 filter(dv, S); add_lfvector_lfvector(dv, dv, z, numverts); mul_bfmatrix_lfvector(r, lA, dv); sub_lfvector_lfvector(r, lB, r, numverts); filter(r, S); mul_prevfmatrix_lfvector(p, Pinv, r); filter(p, S); deltaNew = dot_lfvector(r, p, numverts); delta0 = deltaNew * sqrt(conjgrad_epsilon); # endif # ifdef DEBUG_TIME double start = PIL_check_seconds_timer(); # endif tol = (0.01 * 0.2); while ((deltaNew > delta0 * tol * tol) && (iterations < conjgrad_looplimit)) { iterations++; mul_bfmatrix_lfvector(s, lA, p); filter(s, S); alpha = deltaNew / dot_lfvector(p, s, numverts); add_lfvector_lfvectorS(dv, dv, p, alpha, numverts); add_lfvector_lfvectorS(r, r, s, -alpha, numverts); mul_prevfmatrix_lfvector(h, Pinv, r); filter(h, S); deltaOld = deltaNew; deltaNew = dot_lfvector(r, h, numverts); add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts); filter(p, S); } # ifdef DEBUG_TIME double end = PIL_check_seconds_timer(); printf("cg_filtered_pre time: %f\n", (float)(end - start)); # endif del_lfvector(btemp); del_lfvector(bhat); del_lfvector(h); del_lfvector(s); del_lfvector(p); del_lfvector(r); // printf("iterations: %d\n", iterations); return iterations < conjgrad_looplimit; } # endif bool BPH_mass_spring_solve_velocities(Implicit_Data *data, float dt, ImplicitSolverResult *result) { unsigned int numverts = data->dFdV[0].vcount; lfVector *dFdXmV = create_lfvector(numverts); zero_lfvector(data->dV, numverts); cp_bfmatrix(data->A, data->M); subadd_bfmatrixS_bfmatrixS(data->A, data->dFdV, dt, data->dFdX, (dt * dt)); mul_bfmatrix_lfvector(dFdXmV, data->dFdX, data->V); add_lfvectorS_lfvectorS(data->B, data->F, dt, dFdXmV, (dt * dt), numverts); # ifdef DEBUG_TIME double start = PIL_check_seconds_timer(); # endif /* Conjugate gradient algorithm to solve Ax=b. */ cg_filtered(data->dV, data->A, data->B, data->z, data->S, result); // cg_filtered_pre(id->dV, id->A, id->B, id->z, id->S, id->P, id->Pinv, id->bigI); # ifdef DEBUG_TIME double end = PIL_check_seconds_timer(); printf("cg_filtered calc time: %f\n", (float)(end - start)); # endif // advance velocities add_lfvector_lfvector(data->Vnew, data->V, data->dV, numverts); del_lfvector(dFdXmV); return result->status == BPH_SOLVER_SUCCESS; } bool BPH_mass_spring_solve_positions(Implicit_Data *data, float dt) { int numverts = data->M[0].vcount; // advance positions add_lfvector_lfvectorS(data->Xnew, data->X, data->Vnew, dt, numverts); return true; } void BPH_mass_spring_apply_result(Implicit_Data *data) { int numverts = data->M[0].vcount; cp_lfvector(data->X, data->Xnew, numverts); cp_lfvector(data->V, data->Vnew, numverts); } void BPH_mass_spring_set_vertex_mass(Implicit_Data *data, int index, float mass) { unit_m3(data->M[index].m); mul_m3_fl(data->M[index].m, mass); } void BPH_mass_spring_set_rest_transform(Implicit_Data *data, int index, float tfm[3][3]) { # ifdef CLOTH_ROOT_FRAME copy_m3_m3(data->tfm[index].m, tfm); # else unit_m3(data->tfm[index].m); (void)tfm; # endif } void BPH_mass_spring_set_motion_state(Implicit_Data *data, int index, const float x[3], const float v[3]) { world_to_root_v3(data, index, data->X[index], x); world_to_root_v3(data, index, data->V[index], v); } void BPH_mass_spring_set_position(Implicit_Data *data, int index, const float x[3]) { world_to_root_v3(data, index, data->X[index], x); } void BPH_mass_spring_set_velocity(Implicit_Data *data, int index, const float v[3]) { world_to_root_v3(data, index, data->V[index], v); } void BPH_mass_spring_get_motion_state(struct Implicit_Data *data, int index, float x[3], float v[3]) { if (x) { root_to_world_v3(data, index, x, data->X[index]); } if (v) { root_to_world_v3(data, index, v, data->V[index]); } } void BPH_mass_spring_get_position(struct Implicit_Data *data, int index, float x[3]) { root_to_world_v3(data, index, x, data->X[index]); } void BPH_mass_spring_get_new_position(struct Implicit_Data *data, int index, float x[3]) { root_to_world_v3(data, index, x, data->Xnew[index]); } void BPH_mass_spring_set_new_position(struct Implicit_Data *data, int index, const float x[3]) { world_to_root_v3(data, index, data->Xnew[index], x); } void BPH_mass_spring_get_new_velocity(struct Implicit_Data *data, int index, float v[3]) { root_to_world_v3(data, index, v, data->Vnew[index]); } void BPH_mass_spring_set_new_velocity(struct Implicit_Data *data, int index, const float v[3]) { world_to_root_v3(data, index, data->Vnew[index], v); } /* -------------------------------- */ static int BPH_mass_spring_add_block(Implicit_Data *data, int v1, int v2) { int s = data->M[0].vcount + data->num_blocks; /* index from array start */ BLI_assert(s < data->M[0].vcount + data->M[0].scount); ++data->num_blocks; /* tfm and S don't have spring entries (diagonal blocks only) */ init_fmatrix(data->bigI + s, v1, v2); init_fmatrix(data->M + s, v1, v2); init_fmatrix(data->dFdX + s, v1, v2); init_fmatrix(data->dFdV + s, v1, v2); init_fmatrix(data->A + s, v1, v2); init_fmatrix(data->P + s, v1, v2); init_fmatrix(data->Pinv + s, v1, v2); return s; } void BPH_mass_spring_clear_constraints(Implicit_Data *data) { int i, numverts = data->S[0].vcount; for (i = 0; i < numverts; i++) { unit_m3(data->S[i].m); zero_v3(data->z[i]); } } void BPH_mass_spring_add_constraint_ndof0(Implicit_Data *data, int index, const float dV[3]) { zero_m3(data->S[index].m); world_to_root_v3(data, index, data->z[index], dV); } void BPH_mass_spring_add_constraint_ndof1( Implicit_Data *data, int index, const float c1[3], const float c2[3], const float dV[3]) { float m[3][3], p[3], q[3], u[3], cmat[3][3]; world_to_root_v3(data, index, p, c1); mul_fvectorT_fvector(cmat, p, p); sub_m3_m3m3(m, I, cmat); world_to_root_v3(data, index, q, c2); mul_fvectorT_fvector(cmat, q, q); sub_m3_m3m3(m, m, cmat); /* XXX not sure but multiplication should work here */ copy_m3_m3(data->S[index].m, m); // mul_m3_m3m3(data->S[index].m, data->S[index].m, m); world_to_root_v3(data, index, u, dV); add_v3_v3(data->z[index], u); } void BPH_mass_spring_add_constraint_ndof2(Implicit_Data *data, int index, const float c1[3], const float dV[3]) { float m[3][3], p[3], u[3], cmat[3][3]; world_to_root_v3(data, index, p, c1); mul_fvectorT_fvector(cmat, p, p); sub_m3_m3m3(m, I, cmat); copy_m3_m3(data->S[index].m, m); // mul_m3_m3m3(data->S[index].m, data->S[index].m, m); world_to_root_v3(data, index, u, dV); add_v3_v3(data->z[index], u); } void BPH_mass_spring_clear_forces(Implicit_Data *data) { int numverts = data->M[0].vcount; zero_lfvector(data->F, numverts); init_bfmatrix(data->dFdX, ZERO); init_bfmatrix(data->dFdV, ZERO); data->num_blocks = 0; } void BPH_mass_spring_force_reference_frame(Implicit_Data *data, int index, const float acceleration[3], const float omega[3], const float domega_dt[3], float mass) { # ifdef CLOTH_ROOT_FRAME float acc[3], w[3], dwdt[3]; float f[3], dfdx[3][3], dfdv[3][3]; float euler[3], coriolis[3], centrifugal[3], rotvel[3]; float deuler[3][3], dcoriolis[3][3], dcentrifugal[3][3], drotvel[3][3]; world_to_root_v3(data, index, acc, acceleration); world_to_root_v3(data, index, w, omega); world_to_root_v3(data, index, dwdt, domega_dt); cross_v3_v3v3(euler, dwdt, data->X[index]); cross_v3_v3v3(coriolis, w, data->V[index]); mul_v3_fl(coriolis, 2.0f); cross_v3_v3v3(rotvel, w, data->X[index]); cross_v3_v3v3(centrifugal, w, rotvel); sub_v3_v3v3(f, acc, euler); sub_v3_v3(f, coriolis); sub_v3_v3(f, centrifugal); mul_v3_fl(f, mass); /* F = m * a */ cross_v3_identity(deuler, dwdt); cross_v3_identity(dcoriolis, w); mul_m3_fl(dcoriolis, 2.0f); cross_v3_identity(drotvel, w); cross_m3_v3m3(dcentrifugal, w, drotvel); add_m3_m3m3(dfdx, deuler, dcentrifugal); negate_m3(dfdx); mul_m3_fl(dfdx, mass); copy_m3_m3(dfdv, dcoriolis); negate_m3(dfdv); mul_m3_fl(dfdv, mass); add_v3_v3(data->F[index], f); add_m3_m3m3(data->dFdX[index].m, data->dFdX[index].m, dfdx); add_m3_m3m3(data->dFdV[index].m, data->dFdV[index].m, dfdv); # else (void)data; (void)index; (void)acceleration; (void)omega; (void)domega_dt; # endif } void BPH_mass_spring_force_gravity(Implicit_Data *data, int index, float mass, const float g[3]) { /* force = mass * acceleration (in this case: gravity) */ float f[3]; world_to_root_v3(data, index, f, g); mul_v3_fl(f, mass); add_v3_v3(data->F[index], f); } void BPH_mass_spring_force_drag(Implicit_Data *data, float drag) { int i, numverts = data->M[0].vcount; for (i = 0; i < numverts; i++) { float tmp[3][3]; /* NB: uses root space velocity, no need to transform */ madd_v3_v3fl(data->F[i], data->V[i], -drag); copy_m3_m3(tmp, I); mul_m3_fl(tmp, -drag); add_m3_m3m3(data->dFdV[i].m, data->dFdV[i].m, tmp); } } void BPH_mass_spring_force_extern( struct Implicit_Data *data, int i, const float f[3], float dfdx[3][3], float dfdv[3][3]) { float tf[3], tdfdx[3][3], tdfdv[3][3]; world_to_root_v3(data, i, tf, f); world_to_root_m3(data, i, tdfdx, dfdx); world_to_root_m3(data, i, tdfdv, dfdv); add_v3_v3(data->F[i], tf); add_m3_m3m3(data->dFdX[i].m, data->dFdX[i].m, tdfdx); add_m3_m3m3(data->dFdV[i].m, data->dFdV[i].m, tdfdv); } static float calc_nor_area_tri(float nor[3], const float v1[3], const float v2[3], const float v3[3]) { float n1[3], n2[3]; sub_v3_v3v3(n1, v1, v2); sub_v3_v3v3(n2, v2, v3); cross_v3_v3v3(nor, n1, n2); return normalize_v3(nor); } /* XXX does not support force jacobians yet, since the effector system does not provide them either */ void BPH_mass_spring_force_face_wind( Implicit_Data *data, int v1, int v2, int v3, const float (*winvec)[3]) { const float effector_scale = 0.02f; float win[3], nor[3], area; float factor; /* calculate face normal and area */ area = calc_nor_area_tri(nor, data->X[v1], data->X[v2], data->X[v3]); /* The force is calculated and split up evenly for each of the three face verts */ factor = effector_scale * area / 3.0f; world_to_root_v3(data, v1, win, winvec[v1]); madd_v3_v3fl(data->F[v1], nor, factor * dot_v3v3(win, nor)); world_to_root_v3(data, v2, win, winvec[v2]); madd_v3_v3fl(data->F[v2], nor, factor * dot_v3v3(win, nor)); world_to_root_v3(data, v3, win, winvec[v3]); madd_v3_v3fl(data->F[v3], nor, factor * dot_v3v3(win, nor)); } float BPH_tri_tetra_volume_signed_6x(Implicit_Data *data, int v1, int v2, int v3) { /* The result will be 6x the volume */ return volume_tri_tetrahedron_signed_v3_6x(data->X[v1], data->X[v2], data->X[v3]); } void BPH_mass_spring_force_pressure( Implicit_Data *data, int v1, int v2, int v3, float pressure_difference, float weights[3]) { float nor[3], area; float factor; /* calculate face normal and area */ area = calc_nor_area_tri(nor, data->X[v1], data->X[v2], data->X[v3]); /* The force is calculated and split up evenly for each of the three face verts */ factor = pressure_difference * area / 3.0f; /* add pressure to each of the face verts */ madd_v3_v3fl(data->F[v1], nor, factor * weights[0]); madd_v3_v3fl(data->F[v2], nor, factor * weights[1]); madd_v3_v3fl(data->F[v3], nor, factor * weights[2]); } static void edge_wind_vertex(const float dir[3], float length, float radius, const float wind[3], float f[3], float UNUSED(dfdx[3][3]), float UNUSED(dfdv[3][3])) { const float density = 0.01f; /* XXX arbitrary value, corresponds to effect of air density */ float cos_alpha, sin_alpha, cross_section; float windlen = len_v3(wind); if (windlen == 0.0f) { zero_v3(f); return; } /* angle of wind direction to edge */ cos_alpha = dot_v3v3(wind, dir) / windlen; sin_alpha = sqrtf(1.0f - cos_alpha * cos_alpha); cross_section = radius * ((float)M_PI * radius * sin_alpha + length * cos_alpha); mul_v3_v3fl(f, wind, density * cross_section); } void BPH_mass_spring_force_edge_wind( Implicit_Data *data, int v1, int v2, float radius1, float radius2, const float (*winvec)[3]) { float win[3], dir[3], length; float f[3], dfdx[3][3], dfdv[3][3]; sub_v3_v3v3(dir, data->X[v1], data->X[v2]); length = normalize_v3(dir); world_to_root_v3(data, v1, win, winvec[v1]); edge_wind_vertex(dir, length, radius1, win, f, dfdx, dfdv); add_v3_v3(data->F[v1], f); world_to_root_v3(data, v2, win, winvec[v2]); edge_wind_vertex(dir, length, radius2, win, f, dfdx, dfdv); add_v3_v3(data->F[v2], f); } void BPH_mass_spring_force_vertex_wind(Implicit_Data *data, int v, float UNUSED(radius), const float (*winvec)[3]) { const float density = 0.01f; /* XXX arbitrary value, corresponds to effect of air density */ float wind[3]; float f[3]; world_to_root_v3(data, v, wind, winvec[v]); mul_v3_v3fl(f, wind, density); add_v3_v3(data->F[v], f); } BLI_INLINE void dfdx_spring(float to[3][3], const float dir[3], float length, float L, float k) { // dir is unit length direction, rest is spring's restlength, k is spring constant. // return ( (I-outerprod(dir, dir))*Min(1.0f, rest/length) - I) * -k; outerproduct(to, dir, dir); sub_m3_m3m3(to, I, to); mul_m3_fl(to, (L / length)); sub_m3_m3m3(to, to, I); mul_m3_fl(to, k); } /* unused */ # if 0 BLI_INLINE void dfdx_damp(float to[3][3], const float dir[3], float length, const float vel[3], float rest, float damping) { // inner spring damping vel is the relative velocity of the endpoints. // return (I-outerprod(dir, dir)) * (-damping * -(dot(dir, vel)/Max(length, rest))); mul_fvectorT_fvector(to, dir, dir); sub_fmatrix_fmatrix(to, I, to); mul_fmatrix_S(to, (-damping * -(dot_v3v3(dir, vel) / MAX2(length, rest)))); } # endif BLI_INLINE void dfdv_damp(float to[3][3], const float dir[3], float damping) { // derivative of force wrt velocity outerproduct(to, dir, dir); mul_m3_fl(to, -damping); } BLI_INLINE float fb(float length, float L) { float x = length / L; float xx = x * x; float xxx = xx * x; float xxxx = xxx * x; return (-11.541f * xxxx + 34.193f * xxx - 39.083f * xx + 23.116f * x - 9.713f); } BLI_INLINE float fbderiv(float length, float L) { float x = length / L; float xx = x * x; float xxx = xx * x; return (-46.164f * xxx + 102.579f * xx - 78.166f * x + 23.116f); } BLI_INLINE float fbstar(float length, float L, float kb, float cb) { float tempfb_fl = kb * fb(length, L); float fbstar_fl = cb * (length - L); if (tempfb_fl < fbstar_fl) { return fbstar_fl; } else { return tempfb_fl; } } // function to calculae bending spring force (taken from Choi & Co) BLI_INLINE float fbstar_jacobi(float length, float L, float kb, float cb) { float tempfb_fl = kb * fb(length, L); float fbstar_fl = cb * (length - L); if (tempfb_fl < fbstar_fl) { return -cb; } else { return -kb * fbderiv(length, L); } } /* calculate elonglation */ BLI_INLINE bool spring_length(Implicit_Data *data, int i, int j, float r_extent[3], float r_dir[3], float *r_length, float r_vel[3]) { sub_v3_v3v3(r_extent, data->X[j], data->X[i]); sub_v3_v3v3(r_vel, data->V[j], data->V[i]); *r_length = len_v3(r_extent); if (*r_length > ALMOST_ZERO) { # if 0 if (length > L) { if ((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && (((length - L) * 100.0f / L) > clmd->sim_parms->maxspringlen)) { // cut spring! s->flags |= CSPRING_FLAG_DEACTIVATE; return false; } } # endif mul_v3_v3fl(r_dir, r_extent, 1.0f / (*r_length)); } else { zero_v3(r_dir); } return true; } BLI_INLINE void apply_spring( Implicit_Data *data, int i, int j, const float f[3], float dfdx[3][3], float dfdv[3][3]) { int block_ij = BPH_mass_spring_add_block(data, i, j); add_v3_v3(data->F[i], f); sub_v3_v3(data->F[j], f); add_m3_m3m3(data->dFdX[i].m, data->dFdX[i].m, dfdx); add_m3_m3m3(data->dFdX[j].m, data->dFdX[j].m, dfdx); sub_m3_m3m3(data->dFdX[block_ij].m, data->dFdX[block_ij].m, dfdx); add_m3_m3m3(data->dFdV[i].m, data->dFdV[i].m, dfdv); add_m3_m3m3(data->dFdV[j].m, data->dFdV[j].m, dfdv); sub_m3_m3m3(data->dFdV[block_ij].m, data->dFdV[block_ij].m, dfdv); } bool BPH_mass_spring_force_spring_linear(Implicit_Data *data, int i, int j, float restlen, float stiffness_tension, float damping_tension, float stiffness_compression, float damping_compression, bool resist_compress, bool new_compress, float clamp_force) { float extent[3], length, dir[3], vel[3]; float f[3], dfdx[3][3], dfdv[3][3]; float damping = 0; // calculate elonglation spring_length(data, i, j, extent, dir, &length, vel); /* This code computes not only the force, but also its derivative. * Zero derivative effectively disables the spring for the implicit solver. * Thus length > restlen makes cloth unconstrained at the start of simulation. */ if ((length >= restlen && length > 0) || resist_compress) { float stretch_force; damping = damping_tension; stretch_force = stiffness_tension * (length - restlen); if (clamp_force > 0.0f && stretch_force > clamp_force) { stretch_force = clamp_force; } mul_v3_v3fl(f, dir, stretch_force); dfdx_spring(dfdx, dir, length, restlen, stiffness_tension); } else if (new_compress) { /* This is based on the Choi and Ko bending model, * which works surprisingly well for compression. */ float kb = stiffness_compression; float cb = kb; /* cb equal to kb seems to work, but a factor can be added if necessary */ damping = damping_compression; mul_v3_v3fl(f, dir, fbstar(length, restlen, kb, cb)); outerproduct(dfdx, dir, dir); mul_m3_fl(dfdx, fbstar_jacobi(length, restlen, kb, cb)); } else { return false; } madd_v3_v3fl(f, dir, damping * dot_v3v3(vel, dir)); dfdv_damp(dfdv, dir, damping); apply_spring(data, i, j, f, dfdx, dfdv); return true; } /* See "Stable but Responsive Cloth" (Choi, Ko 2005) */ bool BPH_mass_spring_force_spring_bending( Implicit_Data *data, int i, int j, float restlen, float kb, float cb) { float extent[3], length, dir[3], vel[3]; // calculate elonglation spring_length(data, i, j, extent, dir, &length, vel); if (length < restlen) { float f[3], dfdx[3][3], dfdv[3][3]; mul_v3_v3fl(f, dir, fbstar(length, restlen, kb, cb)); outerproduct(dfdx, dir, dir); mul_m3_fl(dfdx, fbstar_jacobi(length, restlen, kb, cb)); /* XXX damping not supported */ zero_m3(dfdv); apply_spring(data, i, j, f, dfdx, dfdv); return true; } else { return false; } } BLI_INLINE void poly_avg(lfVector *data, int *inds, int len, float r_avg[3]) { float fact = 1.0f / (float)len; zero_v3(r_avg); for (int i = 0; i < len; i++) { madd_v3_v3fl(r_avg, data[inds[i]], fact); } } BLI_INLINE void poly_norm(lfVector *data, int i, int j, int *inds, int len, float r_dir[3]) { float mid[3]; poly_avg(data, inds, len, mid); normal_tri_v3(r_dir, data[i], data[j], mid); } BLI_INLINE void edge_avg(lfVector *data, int i, int j, float r_avg[3]) { r_avg[0] = (data[i][0] + data[j][0]) * 0.5f; r_avg[1] = (data[i][1] + data[j][1]) * 0.5f; r_avg[2] = (data[i][2] + data[j][2]) * 0.5f; } BLI_INLINE void edge_norm(lfVector *data, int i, int j, float r_dir[3]) { sub_v3_v3v3(r_dir, data[i], data[j]); normalize_v3(r_dir); } BLI_INLINE float bend_angle(float dir_a[3], float dir_b[3], float dir_e[3]) { float cos, sin; float tmp[3]; cos = dot_v3v3(dir_a, dir_b); cross_v3_v3v3(tmp, dir_a, dir_b); sin = dot_v3v3(tmp, dir_e); return atan2f(sin, cos); } BLI_INLINE void spring_angle(Implicit_Data *data, int i, int j, int *i_a, int *i_b, int len_a, int len_b, float r_dir_a[3], float r_dir_b[3], float *r_angle, float r_vel_a[3], float r_vel_b[3]) { float dir_e[3], vel_e[3]; poly_norm(data->X, j, i, i_a, len_a, r_dir_a); poly_norm(data->X, i, j, i_b, len_b, r_dir_b); edge_norm(data->X, i, j, dir_e); *r_angle = bend_angle(r_dir_a, r_dir_b, dir_e); poly_avg(data->V, i_a, len_a, r_vel_a); poly_avg(data->V, i_b, len_b, r_vel_b); edge_avg(data->V, i, j, vel_e); sub_v3_v3(r_vel_a, vel_e); sub_v3_v3(r_vel_b, vel_e); } /* Angular springs roughly based on the bending model proposed by Baraff and Witkin in "Large Steps * in Cloth Simulation". */ bool BPH_mass_spring_force_spring_angular(Implicit_Data *data, int i, int j, int *i_a, int *i_b, int len_a, int len_b, float restang, float stiffness, float damping) { float angle, dir_a[3], dir_b[3], vel_a[3], vel_b[3]; float f_a[3], f_b[3], f_e[3]; float force; int x; spring_angle(data, i, j, i_a, i_b, len_a, len_b, dir_a, dir_b, &angle, vel_a, vel_b); /* spring force */ force = stiffness * (angle - restang); /* damping force */ force += -damping * (dot_v3v3(vel_a, dir_a) + dot_v3v3(vel_b, dir_b)); mul_v3_v3fl(f_a, dir_a, force / len_a); mul_v3_v3fl(f_b, dir_b, force / len_b); for (x = 0; x < len_a; x++) { add_v3_v3(data->F[i_a[x]], f_a); } for (x = 0; x < len_b; x++) { add_v3_v3(data->F[i_b[x]], f_b); } mul_v3_v3fl(f_a, dir_a, force * 0.5f); mul_v3_v3fl(f_b, dir_b, force * 0.5f); add_v3_v3v3(f_e, f_a, f_b); sub_v3_v3(data->F[i], f_e); sub_v3_v3(data->F[j], f_e); return true; } /* Jacobian of a direction vector. * Basically the part of the differential orthogonal to the direction, * inversely proportional to the length of the edge. * * dD_ij/dx_i = -dD_ij/dx_j = (D_ij * D_ij^T - I) / len_ij */ BLI_INLINE void spring_grad_dir( Implicit_Data *data, int i, int j, float edge[3], float dir[3], float grad_dir[3][3]) { float length; sub_v3_v3v3(edge, data->X[j], data->X[i]); length = normalize_v3_v3(dir, edge); if (length > ALMOST_ZERO) { outerproduct(grad_dir, dir, dir); sub_m3_m3m3(grad_dir, I, grad_dir); mul_m3_fl(grad_dir, 1.0f / length); } else { zero_m3(grad_dir); } } BLI_INLINE void spring_hairbend_forces(Implicit_Data *data, int i, int j, int k, const float goal[3], float stiffness, float damping, int q, const float dx[3], const float dv[3], float r_f[3]) { float edge_ij[3], dir_ij[3]; float edge_jk[3], dir_jk[3]; float vel_ij[3], vel_jk[3], vel_ortho[3]; float f_bend[3], f_damp[3]; float fk[3]; float dist[3]; zero_v3(fk); sub_v3_v3v3(edge_ij, data->X[j], data->X[i]); if (q == i) { sub_v3_v3(edge_ij, dx); } if (q == j) { add_v3_v3(edge_ij, dx); } normalize_v3_v3(dir_ij, edge_ij); sub_v3_v3v3(edge_jk, data->X[k], data->X[j]); if (q == j) { sub_v3_v3(edge_jk, dx); } if (q == k) { add_v3_v3(edge_jk, dx); } normalize_v3_v3(dir_jk, edge_jk); sub_v3_v3v3(vel_ij, data->V[j], data->V[i]); if (q == i) { sub_v3_v3(vel_ij, dv); } if (q == j) { add_v3_v3(vel_ij, dv); } sub_v3_v3v3(vel_jk, data->V[k], data->V[j]); if (q == j) { sub_v3_v3(vel_jk, dv); } if (q == k) { add_v3_v3(vel_jk, dv); } /* bending force */ sub_v3_v3v3(dist, goal, edge_jk); mul_v3_v3fl(f_bend, dist, stiffness); add_v3_v3(fk, f_bend); /* damping force */ madd_v3_v3v3fl(vel_ortho, vel_jk, dir_jk, -dot_v3v3(vel_jk, dir_jk)); mul_v3_v3fl(f_damp, vel_ortho, damping); sub_v3_v3(fk, f_damp); copy_v3_v3(r_f, fk); } /* Finite Differences method for estimating the jacobian of the force */ BLI_INLINE void spring_hairbend_estimate_dfdx(Implicit_Data *data, int i, int j, int k, const float goal[3], float stiffness, float damping, int q, float dfdx[3][3]) { const float delta = 0.00001f; // TODO find a good heuristic for this float dvec_null[3][3], dvec_pos[3][3], dvec_neg[3][3]; float f[3]; int a, b; zero_m3(dvec_null); unit_m3(dvec_pos); mul_m3_fl(dvec_pos, delta * 0.5f); copy_m3_m3(dvec_neg, dvec_pos); negate_m3(dvec_neg); /* XXX TODO offset targets to account for position dependency */ for (a = 0; a < 3; a++) { spring_hairbend_forces( data, i, j, k, goal, stiffness, damping, q, dvec_pos[a], dvec_null[a], f); copy_v3_v3(dfdx[a], f); spring_hairbend_forces( data, i, j, k, goal, stiffness, damping, q, dvec_neg[a], dvec_null[a], f); sub_v3_v3(dfdx[a], f); for (b = 0; b < 3; b++) { dfdx[a][b] /= delta; } } } /* Finite Differences method for estimating the jacobian of the force */ BLI_INLINE void spring_hairbend_estimate_dfdv(Implicit_Data *data, int i, int j, int k, const float goal[3], float stiffness, float damping, int q, float dfdv[3][3]) { const float delta = 0.00001f; // TODO find a good heuristic for this float dvec_null[3][3], dvec_pos[3][3], dvec_neg[3][3]; float f[3]; int a, b; zero_m3(dvec_null); unit_m3(dvec_pos); mul_m3_fl(dvec_pos, delta * 0.5f); copy_m3_m3(dvec_neg, dvec_pos); negate_m3(dvec_neg); /* XXX TODO offset targets to account for position dependency */ for (a = 0; a < 3; a++) { spring_hairbend_forces( data, i, j, k, goal, stiffness, damping, q, dvec_null[a], dvec_pos[a], f); copy_v3_v3(dfdv[a], f); spring_hairbend_forces( data, i, j, k, goal, stiffness, damping, q, dvec_null[a], dvec_neg[a], f); sub_v3_v3(dfdv[a], f); for (b = 0; b < 3; b++) { dfdv[a][b] /= delta; } } } /* Angular spring that pulls the vertex toward the local target * See "Artistic Simulation of Curly Hair" (Pixar technical memo #12-03a) */ bool BPH_mass_spring_force_spring_bending_hair(Implicit_Data *data, int i, int j, int k, const float target[3], float stiffness, float damping) { float goal[3]; float fj[3], fk[3]; float dfj_dxi[3][3], dfj_dxj[3][3], dfk_dxi[3][3], dfk_dxj[3][3], dfk_dxk[3][3]; float dfj_dvi[3][3], dfj_dvj[3][3], dfk_dvi[3][3], dfk_dvj[3][3], dfk_dvk[3][3]; const float vecnull[3] = {0.0f, 0.0f, 0.0f}; int block_ij = BPH_mass_spring_add_block(data, i, j); int block_jk = BPH_mass_spring_add_block(data, j, k); int block_ik = BPH_mass_spring_add_block(data, i, k); world_to_root_v3(data, j, goal, target); spring_hairbend_forces(data, i, j, k, goal, stiffness, damping, k, vecnull, vecnull, fk); negate_v3_v3(fj, fk); /* counterforce */ spring_hairbend_estimate_dfdx(data, i, j, k, goal, stiffness, damping, i, dfk_dxi); spring_hairbend_estimate_dfdx(data, i, j, k, goal, stiffness, damping, j, dfk_dxj); spring_hairbend_estimate_dfdx(data, i, j, k, goal, stiffness, damping, k, dfk_dxk); copy_m3_m3(dfj_dxi, dfk_dxi); negate_m3(dfj_dxi); copy_m3_m3(dfj_dxj, dfk_dxj); negate_m3(dfj_dxj); spring_hairbend_estimate_dfdv(data, i, j, k, goal, stiffness, damping, i, dfk_dvi); spring_hairbend_estimate_dfdv(data, i, j, k, goal, stiffness, damping, j, dfk_dvj); spring_hairbend_estimate_dfdv(data, i, j, k, goal, stiffness, damping, k, dfk_dvk); copy_m3_m3(dfj_dvi, dfk_dvi); negate_m3(dfj_dvi); copy_m3_m3(dfj_dvj, dfk_dvj); negate_m3(dfj_dvj); /* add forces and jacobians to the solver data */ add_v3_v3(data->F[j], fj); add_v3_v3(data->F[k], fk); add_m3_m3m3(data->dFdX[j].m, data->dFdX[j].m, dfj_dxj); add_m3_m3m3(data->dFdX[k].m, data->dFdX[k].m, dfk_dxk); add_m3_m3m3(data->dFdX[block_ij].m, data->dFdX[block_ij].m, dfj_dxi); add_m3_m3m3(data->dFdX[block_jk].m, data->dFdX[block_jk].m, dfk_dxj); add_m3_m3m3(data->dFdX[block_ik].m, data->dFdX[block_ik].m, dfk_dxi); add_m3_m3m3(data->dFdV[j].m, data->dFdV[j].m, dfj_dvj); add_m3_m3m3(data->dFdV[k].m, data->dFdV[k].m, dfk_dvk); add_m3_m3m3(data->dFdV[block_ij].m, data->dFdV[block_ij].m, dfj_dvi); add_m3_m3m3(data->dFdV[block_jk].m, data->dFdV[block_jk].m, dfk_dvj); add_m3_m3m3(data->dFdV[block_ik].m, data->dFdV[block_ik].m, dfk_dvi); /* XXX analytical calculation of derivatives below is incorrect. * This proved to be difficult, but for now just using the finite difference method for * estimating the jacobians should be sufficient. */ # if 0 float edge_ij[3], dir_ij[3], grad_dir_ij[3][3]; float edge_jk[3], dir_jk[3], grad_dir_jk[3][3]; float dist[3], vel_jk[3], vel_jk_ortho[3], projvel[3]; float target[3]; float tmp[3][3]; float fi[3], fj[3], fk[3]; float dfi_dxi[3][3], dfj_dxi[3][3], dfj_dxj[3][3], dfk_dxi[3][3], dfk_dxj[3][3], dfk_dxk[3][3]; float dfdvi[3][3]; // TESTING damping = 0.0f; zero_v3(fi); zero_v3(fj); zero_v3(fk); zero_m3(dfi_dxi); zero_m3(dfj_dxi); zero_m3(dfk_dxi); zero_m3(dfk_dxj); zero_m3(dfk_dxk); /* jacobian of direction vectors */ spring_grad_dir(data, i, j, edge_ij, dir_ij, grad_dir_ij); spring_grad_dir(data, j, k, edge_jk, dir_jk, grad_dir_jk); sub_v3_v3v3(vel_jk, data->V[k], data->V[j]); /* bending force */ mul_v3_v3fl(target, dir_ij, restlen); sub_v3_v3v3(dist, target, edge_jk); mul_v3_v3fl(fk, dist, stiffness); /* damping force */ madd_v3_v3v3fl(vel_jk_ortho, vel_jk, dir_jk, -dot_v3v3(vel_jk, dir_jk)); madd_v3_v3fl(fk, vel_jk_ortho, damping); /* XXX this only holds true as long as we assume straight rest shape! * eventually will become a bit more involved since the opposite segment * gets its own target, under condition of having equal torque on both sides. */ copy_v3_v3(fi, fk); /* counterforce on the middle point */ sub_v3_v3(fj, fi); sub_v3_v3(fj, fk); /* === derivatives === */ madd_m3_m3fl(dfk_dxi, grad_dir_ij, stiffness * restlen); madd_m3_m3fl(dfk_dxj, grad_dir_ij, -stiffness * restlen); madd_m3_m3fl(dfk_dxj, I, stiffness); madd_m3_m3fl(dfk_dxk, I, -stiffness); copy_m3_m3(dfi_dxi, dfk_dxk); negate_m3(dfi_dxi); /* dfj_dfi == dfi_dfj due to symmetry, * dfi_dfj == dfk_dfj due to fi == fk * XXX see comment above on future bent rest shapes */ copy_m3_m3(dfj_dxi, dfk_dxj); /* dfj_dxj == -(dfi_dxj + dfk_dxj) due to fj == -(fi + fk) */ sub_m3_m3m3(dfj_dxj, dfj_dxj, dfj_dxi); sub_m3_m3m3(dfj_dxj, dfj_dxj, dfk_dxj); /* add forces and jacobians to the solver data */ add_v3_v3(data->F[i], fi); add_v3_v3(data->F[j], fj); add_v3_v3(data->F[k], fk); add_m3_m3m3(data->dFdX[i].m, data->dFdX[i].m, dfi_dxi); add_m3_m3m3(data->dFdX[j].m, data->dFdX[j].m, dfj_dxj); add_m3_m3m3(data->dFdX[k].m, data->dFdX[k].m, dfk_dxk); add_m3_m3m3(data->dFdX[block_ij].m, data->dFdX[block_ij].m, dfj_dxi); add_m3_m3m3(data->dFdX[block_jk].m, data->dFdX[block_jk].m, dfk_dxj); add_m3_m3m3(data->dFdX[block_ik].m, data->dFdX[block_ik].m, dfk_dxi); # endif return true; } bool BPH_mass_spring_force_spring_goal(Implicit_Data *data, int i, const float goal_x[3], const float goal_v[3], float stiffness, float damping) { float root_goal_x[3], root_goal_v[3], extent[3], length, dir[3], vel[3]; float f[3], dfdx[3][3], dfdv[3][3]; /* goal is in world space */ world_to_root_v3(data, i, root_goal_x, goal_x); world_to_root_v3(data, i, root_goal_v, goal_v); sub_v3_v3v3(extent, root_goal_x, data->X[i]); sub_v3_v3v3(vel, root_goal_v, data->V[i]); length = normalize_v3_v3(dir, extent); if (length > ALMOST_ZERO) { mul_v3_v3fl(f, dir, stiffness * length); // Ascher & Boxman, p.21: Damping only during elonglation // something wrong with it... madd_v3_v3fl(f, dir, damping * dot_v3v3(vel, dir)); dfdx_spring(dfdx, dir, length, 0.0f, stiffness); dfdv_damp(dfdv, dir, damping); add_v3_v3(data->F[i], f); add_m3_m3m3(data->dFdX[i].m, data->dFdX[i].m, dfdx); add_m3_m3m3(data->dFdV[i].m, data->dFdV[i].m, dfdv); return true; } else { return false; } } #endif /* IMPLICIT_SOLVER_BLENDER */
kernel_template.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include <stdio.h> #include "omp.h" #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; }; int Kernel(struct dataobj *restrict block_sizes_vec, const float h_x, const float h_y, const float h_z, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict save_src_fxx_vec, struct dataobj *restrict save_src_fyy_vec, struct dataobj *restrict save_src_fzz_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict tau_sol_xx_vec, struct dataobj *restrict tau_sol_xy_vec, struct dataobj *restrict tau_sol_xz_vec, struct dataobj *restrict tau_sol_yy_vec, struct dataobj *restrict tau_sol_yz_vec, struct dataobj *restrict tau_sol_zz_vec, struct dataobj *restrict v_sol_x_vec, struct dataobj *restrict v_sol_y_vec, struct dataobj *restrict v_sol_z_vec, const int sp_zi_m, const int time_M, const int time_m, struct profiler *timers, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int nthreads_nonaffine) { int(*restrict block_sizes) __attribute__((aligned(64))) = (int(*))block_sizes_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src_fxx)[save_src_fxx_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_fxx_vec->size[1]])save_src_fxx_vec->data; float(*restrict save_src_fyy)[save_src_fyy_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_fyy_vec->size[1]])save_src_fyy_vec->data; float(*restrict save_src_fzz)[save_src_fzz_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_fzz_vec->size[1]])save_src_fzz_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; float(*restrict tau_sol_xx)[tau_sol_xx_vec->size[1]][tau_sol_xx_vec->size[2]][tau_sol_xx_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_xx_vec->size[1]][tau_sol_xx_vec->size[2]][tau_sol_xx_vec->size[3]])tau_sol_xx_vec->data; float(*restrict tau_sol_xy)[tau_sol_xy_vec->size[1]][tau_sol_xy_vec->size[2]][tau_sol_xy_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_xy_vec->size[1]][tau_sol_xy_vec->size[2]][tau_sol_xy_vec->size[3]])tau_sol_xy_vec->data; float(*restrict tau_sol_xz)[tau_sol_xz_vec->size[1]][tau_sol_xz_vec->size[2]][tau_sol_xz_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_xz_vec->size[1]][tau_sol_xz_vec->size[2]][tau_sol_xz_vec->size[3]])tau_sol_xz_vec->data; float(*restrict tau_sol_yy)[tau_sol_yy_vec->size[1]][tau_sol_yy_vec->size[2]][tau_sol_yy_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_yy_vec->size[1]][tau_sol_yy_vec->size[2]][tau_sol_yy_vec->size[3]])tau_sol_yy_vec->data; float(*restrict tau_sol_yz)[tau_sol_yz_vec->size[1]][tau_sol_yz_vec->size[2]][tau_sol_yz_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_yz_vec->size[1]][tau_sol_yz_vec->size[2]][tau_sol_yz_vec->size[3]])tau_sol_yz_vec->data; float(*restrict tau_sol_zz)[tau_sol_zz_vec->size[1]][tau_sol_zz_vec->size[2]][tau_sol_zz_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_zz_vec->size[1]][tau_sol_zz_vec->size[2]][tau_sol_zz_vec->size[3]])tau_sol_zz_vec->data; float(*restrict v_sol_x)[v_sol_x_vec->size[1]][v_sol_x_vec->size[2]][v_sol_x_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_sol_x_vec->size[1]][v_sol_x_vec->size[2]][v_sol_x_vec->size[3]])v_sol_x_vec->data; float(*restrict v_sol_y)[v_sol_y_vec->size[1]][v_sol_y_vec->size[2]][v_sol_y_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_sol_y_vec->size[1]][v_sol_y_vec->size[2]][v_sol_y_vec->size[3]])v_sol_y_vec->data; float(*restrict v_sol_z)[v_sol_z_vec->size[1]][v_sol_z_vec->size[2]][v_sol_z_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_sol_z_vec->size[1]][v_sol_z_vec->size[2]][v_sol_z_vec->size[3]])v_sol_z_vec->data; /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); int xb_size = block_sizes[0]; int y0_blk0_size = block_sizes[3]; int x0_blk0_size = block_sizes[2]; int yb_size = block_sizes[1]; int sf = 4; int t_blk_size = 2 * sf * (time_M - time_m); //int xb_size = 64; //int yb_size = 64; //x0_blk0_size = 8; //y0_blk0_size = 8; printf(" Tiles: %d, %d ::: Blocks %d, %d \n", xb_size , yb_size , x0_blk0_size, y0_blk0_size); struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); for (int t_blk = time_m; t_blk < sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block { for (int xb = x_m; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size) { //printf(" Change of outer xblock %d \n", xb); for (int yb = y_m; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size) { for (int time = t_blk, t0 = (time) % (2), t1 = (time + 1) % (2); time <= 1 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1)) + 1) % (2), t1 = (((time / sf) % (time_M - time_m + 1))) % (2)) { int tw = ((time / sf) % (time_M - time_m + 1)); #pragma omp parallel num_threads(nthreads) { //printf(" Change of time block : %d \n", tw); #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size) { //printf(" Change of inner xblock %d \n", x0_blk0); for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++) { //printf(" Updating velocity x %d \n", x - time + 4); //printf(" \n PDE update : \n"); #pragma omp simd aligned(tau_sol_xx, tau_sol_xz, tau_sol_zz, v_sol_x, v_sol_z : 32) for (int z = z_m; z <= z_M; z += 1) { //printf(" Updating velocity x %d z: %d \n", x - time + 4, z + 4); float r26 = 1.0 / h_z; float r25 = 1.0 / h_y; float r24 = 1.0 / h_x; v_sol_x[t1][x - time + 4][y - time + 4][z + 4] = r24 * (2.7280354210856e-2F * (tau_sol_xx[t0][x - time + 3][y - time + 4][z + 4] - tau_sol_xx[t0][x - time + 6][y - time + 4][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xx[t0][x - time + 4][y - time + 4][z + 4] + tau_sol_xx[t0][x - time + 5][y - time + 4][z + 4])) + r25 * (2.7280354210856e-2F * (tau_sol_xy[t0][x - time + 4][y - time + 2][z + 4] - tau_sol_xy[t0][x - time + 4][y - time + 5][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xy[t0][x - time + 4][y - time + 3][z + 4] + tau_sol_xy[t0][x - time + 4][y - time + 4][z + 4])) + r26 * (2.7280354210856e-2F * (tau_sol_xz[t0][x - time + 4][y - time + 4][z + 2] - tau_sol_xz[t0][x - time + 4][y - time + 4][z + 5]) + 7.36569563735987e-1F * (-tau_sol_xz[t0][x - time + 4][y - time + 4][z + 3] + tau_sol_xz[t0][x - time + 4][y - time + 4][z + 4])) + v_sol_x[t0][x - time + 4][y - time + 4][z + 4]; v_sol_y[t1][x - time + 4][y - time + 4][z + 4] = r24 * (2.7280354210856e-2F * (tau_sol_xy[t0][x - time + 2][y - time + 4][z + 4] - tau_sol_xy[t0][x - time + 5][y - time + 4][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xy[t0][x - time + 3][y - time + 4][z + 4] + tau_sol_xy[t0][x - time + 4][y - time + 4][z + 4])) + r25 * (2.7280354210856e-2F * (tau_sol_yy[t0][x - time + 4][y - time + 3][z + 4] - tau_sol_yy[t0][x - time + 4][y - time + 6][z + 4]) + 7.36569563735987e-1F * (-tau_sol_yy[t0][x - time + 4][y - time + 4][z + 4] + tau_sol_yy[t0][x - time + 4][y - time + 5][z + 4])) + r26 * (2.7280354210856e-2F * (tau_sol_yz[t0][x - time + 4][y - time + 4][z + 2] - tau_sol_yz[t0][x - time + 4][y - time + 4][z + 5]) + 7.36569563735987e-1F * (-tau_sol_yz[t0][x - time + 4][y - time + 4][z + 3] + tau_sol_yz[t0][x - time + 4][y - time + 4][z + 4])) + v_sol_y[t0][x - time + 4][y - time + 4][z + 4]; v_sol_z[t1][x - time + 4][y - time + 4][z + 4] = r24 * (2.7280354210856e-2F * (tau_sol_xz[t0][x - time + 2][y - time + 4][z + 4] - tau_sol_xz[t0][x - time + 5][y - time + 4][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xz[t0][x - time + 3][y - time + 4][z + 4] + tau_sol_xz[t0][x - time + 4][y - time + 4][z + 4])) + r25 * (2.7280354210856e-2F * (tau_sol_yz[t0][x - time + 4][y - time + 2][z + 4] - tau_sol_yz[t0][x - time + 4][y - time + 5][z + 4]) + 7.36569563735987e-1F * (-tau_sol_yz[t0][x - time + 4][y - time + 3][z + 4] + tau_sol_yz[t0][x - time + 4][y - time + 4][z + 4])) + r26 * (2.7280354210856e-2F * (tau_sol_zz[t0][x - time + 4][y - time + 4][z + 3] - tau_sol_zz[t0][x - time + 4][y - time + 4][z + 6]) + 7.36569563735987e-1F * (-tau_sol_zz[t0][x - time + 4][y - time + 4][z + 4] + tau_sol_zz[t0][x - time + 4][y - time + 4][z + 5])) + v_sol_z[t0][x - time + 4][y - time + 4][z + 4]; } } } } } } #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb - 2); x0_blk0 <= +min((x_M + time), (xb - 2 + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb - 2); y0_blk0 <= +min((y_M + time), (yb - 2 + yb_size)); y0_blk0 += y0_blk0_size) { for (int x = x0_blk0; x <= min(min((x_M + time), (xb - 2 + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb - 2 + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++) { //printf(" Updating stress x %d \n", x - time + 4); #pragma omp simd aligned(tau_sol_xx, tau_sol_xz, tau_sol_zz, v_sol_x, v_sol_z : 32) for (int z = z_m; z <= z_M; z += 1) { //printf(" Updating x %d z: %d \n", x - time + 4, z + 4); float r41 = -v_sol_z[t1][x - time + 4][y - time + 4][z + 4]; float r40 = -v_sol_y[t1][x - time + 4][y - time + 4][z + 4]; float r39 = -v_sol_x[t1][x - time + 4][y - time + 4][z + 4]; float r38 = v_sol_y[t1][x - time + 4][y - time + 2][z + 4] - v_sol_y[t1][x - time + 4][y - time + 5][z + 4]; float r37 = -v_sol_y[t1][x - time + 4][y - time + 3][z + 4] + v_sol_y[t1][x - time + 4][y - time + 4][z + 4]; float r36 = v_sol_z[t1][x - time + 4][y - time + 4][z + 2] - v_sol_z[t1][x - time + 4][y - time + 4][z + 5]; float r35 = -v_sol_z[t1][x - time + 4][y - time + 4][z + 3] + v_sol_z[t1][x - time + 4][y - time + 4][z + 4]; float r34 = v_sol_x[t1][x - time + 2][y - time + 4][z + 4] - v_sol_x[t1][x - time + 5][y - time + 4][z + 4]; float r33 = -v_sol_x[t1][x - time + 3][y - time + 4][z + 4] + v_sol_x[t1][x - time + 4][y - time + 4][z + 4]; float r32 = 1.0 / h_y; float r31 = 1.0 / h_z; float r30 = 1.0 / h_x; float r29 = r30 * (4.7729707730092F * r33 + 1.76776695286347e-1F * r34); float r28 = r31 * (4.7729707730092F * r35 + 1.76776695286347e-1F * r36); float r27 = r32 * (4.7729707730092F * r37 + 1.76776695286347e-1F * r38); tau_sol_xx[t1][x - time + 4][y - time + 4][z + 4] = r27 + r28 + r30 * (9.54594154601839F * r33 + 3.53553390572694e-1F * r34) + tau_sol_xx[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_xy[t1][x - time + 4][y - time + 4][z + 4] = r30 * (2.3864853865046F * (r40 + v_sol_y[t1][x - time + 5][y - time + 4][z + 4]) + 8.83883476431735e-2F * (v_sol_y[t1][x - time + 3][y - time + 4][z + 4] - v_sol_y[t1][x - time + 6][y - time + 4][z + 4])) + r32 * (2.3864853865046F * (r39 + v_sol_x[t1][x - time + 4][y - time + 5][z + 4]) + 8.83883476431735e-2F * (v_sol_x[t1][x - time + 4][y - time + 3][z + 4] - v_sol_x[t1][x - time + 4][y - time + 6][z + 4])) + tau_sol_xy[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_xz[t1][x - time + 4][y - time + 4][z + 4] = r30 * (2.3864853865046F * (r41 + v_sol_z[t1][x - time + 5][y - time + 4][z + 4]) + 8.83883476431735e-2F * (v_sol_z[t1][x - time + 3][y - time + 4][z + 4] - v_sol_z[t1][x - time + 6][y - time + 4][z + 4])) + r31 * (2.3864853865046F * (r39 + v_sol_x[t1][x - time + 4][y - time + 4][z + 5]) + 8.83883476431735e-2F * (v_sol_x[t1][x - time + 4][y - time + 4][z + 3] - v_sol_x[t1][x - time + 4][y - time + 4][z + 6])) + tau_sol_xz[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_yy[t1][x - time + 4][y - time + 4][z + 4] = r28 + r29 + r32 * (9.54594154601839F * r37 + 3.53553390572694e-1F * r38) + tau_sol_yy[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_yz[t1][x - time + 4][y - time + 4][z + 4] = r31 * (2.3864853865046F * (r40 + v_sol_y[t1][x - time + 4][y - time + 4][z + 5]) + 8.83883476431735e-2F * (v_sol_y[t1][x - time + 4][y - time + 4][z + 3] - v_sol_y[t1][x - time + 4][y - time + 4][z + 6])) + r32 * (2.3864853865046F * (r41 + v_sol_z[t1][x - time + 4][y - time + 5][z + 4]) + 8.83883476431735e-2F * (v_sol_z[t1][x - time + 4][y - time + 3][z + 4] - v_sol_z[t1][x - time + 4][y - time + 6][z + 4])) + tau_sol_yz[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_zz[t1][x - time + 4][y - time + 4][z + 4] = r27 + r29 + r31 * (9.54594154601839F * r35 + 3.53553390572694e-1F * r36) + tau_sol_zz[t0][x - time + 4][y - time + 4][z + 4]; } for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time] - 1; sp_zi += 1) { //printf("\n Source_injection at : "); int zind = sp_source_mask[x - time][y - time][sp_zi]; float r0 = save_src_fxx[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; float r1 = save_src_fyy[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; float r2 = save_src_fzz[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; tau_sol_xx[t1][x - time + 4][y - time + 4][zind + 4] += r0; tau_sol_yy[t1][x - time + 4][y - time + 4][zind + 4] += r1; tau_sol_zz[t1][x - time + 4][y - time + 4][zind + 4] += r2; //printf(" Time %d , at : %d, %d \n", tw, x - time + 4, zind + 4); } } } } } } } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000; return 0; }
GB_binop__iseq_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__iseq_uint64 // A.*B function (eWiseMult): GB_AemultB__iseq_uint64 // A*D function (colscale): GB_AxD__iseq_uint64 // D*A function (rowscale): GB_DxB__iseq_uint64 // C+=B function (dense accum): GB_Cdense_accumB__iseq_uint64 // C+=b function (dense accum): GB_Cdense_accumb__iseq_uint64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__iseq_uint64 // C=scalar+B GB_bind1st__iseq_uint64 // C=scalar+B' GB_bind1st_tran__iseq_uint64 // C=A+scalar GB_bind2nd__iseq_uint64 // C=A'+scalar GB_bind2nd_tran__iseq_uint64 // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x == y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISEQ || GxB_NO_UINT64 || GxB_NO_ISEQ_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__iseq_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__iseq_uint64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__iseq_uint64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__iseq_uint64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__iseq_uint64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__iseq_uint64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__iseq_uint64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__iseq_uint64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t bij = Bx [p] ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__iseq_uint64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t aij = Ax [p] ; Cx [p] = (aij == y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB_bind1st_tran__iseq_uint64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB_bind2nd_tran__iseq_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
transform.h
/*! * Copyright 2018 XGBoost contributors */ #ifndef XGBOOST_COMMON_TRANSFORM_H_ #define XGBOOST_COMMON_TRANSFORM_H_ #include <dmlc/omp.h> #include <xgboost/data.h> #include <utility> #include <vector> #include <type_traits> // enable_if #include "host_device_vector.h" #include "common.h" #include "span.h" #if defined (__CUDACC__) #include "device_helpers.cuh" #endif // defined (__CUDACC__) namespace xgboost { namespace common { constexpr size_t kBlockThreads = 256; namespace detail { #if defined(__CUDACC__) template <typename Functor, typename... SpanType> __global__ void LaunchCUDAKernel(Functor _func, Range _range, SpanType... _spans) { for (auto i : dh::GridStrideRange(*_range.begin(), *_range.end())) { _func(i, _spans...); } } #endif // defined(__CUDACC__) } // namespace detail /*! \brief Do Transformation on HostDeviceVectors. * * \tparam CompiledWithCuda A bool parameter used to distinguish compilation * trajectories, users do not need to use it. * * Note: Using Transform is a VERY tricky thing to do. Transform uses template * argument to duplicate itself into two different types, one for CPU, * another for CUDA. The trick is not without its flaw: * * If you use it in a function that can be compiled by both nvcc and host * compiler, the behaviour is un-defined! Because your function is NOT * duplicated by `CompiledWithCuda`. At link time, cuda compiler resolution * will merge functions with same signature. */ template <bool CompiledWithCuda = WITH_CUDA()> class Transform { private: template <typename Functor> struct Evaluator { public: Evaluator(Functor func, Range range, GPUSet devices, bool reshard) : func_(func), range_{std::move(range)}, reshard_{reshard}, distribution_{std::move(GPUDistribution::Block(devices))} {} Evaluator(Functor func, Range range, GPUDistribution dist, bool reshard) : func_(func), range_{std::move(range)}, reshard_{reshard}, distribution_{std::move(dist)} {} /*! * \brief Evaluate the functor with input pointers to HostDeviceVector. * * \tparam HDV... HostDeviceVectors type. * \param vectors Pointers to HostDeviceVector. */ template <typename... HDV> void Eval(HDV... vectors) const { bool on_device = !distribution_.IsEmpty(); if (on_device) { LaunchCUDA(func_, vectors...); } else { LaunchCPU(func_, vectors...); } } private: // CUDA UnpackHDV template <typename T> Span<T> UnpackHDV(HostDeviceVector<T>* _vec, int _device) const { auto span = _vec->DeviceSpan(_device); return span; } template <typename T> Span<T const> UnpackHDV(const HostDeviceVector<T>* _vec, int _device) const { auto span = _vec->ConstDeviceSpan(_device); return span; } // CPU UnpackHDV template <typename T> Span<T> UnpackHDV(HostDeviceVector<T>* _vec) const { return Span<T> {_vec->HostPointer(), static_cast<typename Span<T>::index_type>(_vec->Size())}; } template <typename T> Span<T const> UnpackHDV(const HostDeviceVector<T>* _vec) const { return Span<T const> {_vec->ConstHostPointer(), static_cast<typename Span<T>::index_type>(_vec->Size())}; } // Recursive unpack for Reshard. template <typename T> void UnpackReshard(GPUDistribution dist, const HostDeviceVector<T>* vector) const { vector->Reshard(dist); } template <typename Head, typename... Rest> void UnpackReshard(GPUDistribution dist, const HostDeviceVector<Head>* _vector, const HostDeviceVector<Rest>*... _vectors) const { _vector->Reshard(dist); UnpackReshard(dist, _vectors...); } #if defined(__CUDACC__) template <typename std::enable_if<CompiledWithCuda>::type* = nullptr, typename... HDV> void LaunchCUDA(Functor _func, HDV*... _vectors) const { if (reshard_) UnpackReshard(distribution_, _vectors...); GPUSet devices = distribution_.Devices(); size_t range_size = *range_.end() - *range_.begin(); // Extract index to deal with possible old OpenMP. size_t device_beg = *(devices.begin()); size_t device_end = *(devices.end()); #pragma omp parallel for schedule(static, 1) if (devices.Size() > 1) for (omp_ulong device = device_beg; device < device_end; ++device) { // NOLINT // Ignore other attributes of GPUDistribution for spliting index. // This deals with situation like multi-class setting where // granularity is used in data vector. size_t shard_size = GPUDistribution::Block(devices).ShardSize( range_size, devices.Index(device)); Range shard_range {0, static_cast<Range::DifferenceType>(shard_size)}; dh::safe_cuda(cudaSetDevice(device)); const int GRID_SIZE = static_cast<int>(dh::DivRoundUp(*(range_.end()), kBlockThreads)); detail::LaunchCUDAKernel<<<GRID_SIZE, kBlockThreads>>>( _func, shard_range, UnpackHDV(_vectors, device)...); dh::safe_cuda(cudaGetLastError()); dh::safe_cuda(cudaDeviceSynchronize()); } } #else /*! \brief Dummy funtion defined when compiling for CPU. */ template <typename std::enable_if<!CompiledWithCuda>::type* = nullptr, typename... HDV> void LaunchCUDA(Functor _func, HDV*... _vectors) const { LOG(FATAL) << "Not part of device code. WITH_CUDA: " << WITH_CUDA(); } #endif // defined(__CUDACC__) template <typename... HDV> void LaunchCPU(Functor func, HDV*... vectors) const { omp_ulong end = static_cast<omp_ulong>(*(range_.end())); #pragma omp parallel for schedule(static) for (omp_ulong idx = 0; idx < end; ++idx) { func(idx, UnpackHDV(vectors)...); } } private: /*! \brief Callable object. */ Functor func_; /*! \brief Range object specifying parallel threads index range. */ Range range_; /*! \brief Whether resharding for vectors is required. */ GPUDistribution distribution_; bool reshard_; }; public: /*! * \brief Initialize a Transform object. * * \tparam Functor A callable object type. * \return A Evaluator having one method Eval. * * \param func A callable object, accepting a size_t thread index, * followed by a set of Span classes. * \param range Range object specifying parallel threads index range. * \param devices GPUSet specifying GPUs to use, when compiling for CPU, * this should be GPUSet::Empty(). * \param reshard Whether Reshard for HostDeviceVector is needed. */ template <typename Functor> static Evaluator<Functor> Init(Functor func, Range const range, GPUSet const devices, bool const reshard = true) { return Evaluator<Functor> {func, std::move(range), std::move(devices), reshard}; } template <typename Functor> static Evaluator<Functor> Init(Functor func, Range const range, GPUDistribution const dist, bool const reshard = true) { return Evaluator<Functor> {func, std::move(range), std::move(dist), reshard}; } }; } // namespace common } // namespace xgboost #endif // XGBOOST_COMMON_TRANSFORM_H_
GB_unaryop__identity_int8_uint64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_int8_uint64 // op(A') function: GB_tran__identity_int8_uint64 // C type: int8_t // A type: uint64_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ int8_t z = (int8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int8_uint64 ( int8_t *restrict Cx, const uint64_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_int8_uint64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__identity_int32_int8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_int32_int8 // op(A') function: GB_tran__identity_int32_int8 // C type: int32_t // A type: int8_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ int32_t z = (int32_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int32_int8 ( int32_t *restrict Cx, const int8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_int32_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
omp-barrier.c
#include "stdio.h" int main() { #pragma omp parallel { printf("hello world 1\n"); #pragma omp barrier printf("hello world 2\n"); #pragma omp barrier printf("hello world 3\n"); #pragma omp barrier printf("hello world 4\n"); } return 0; }
ljForce.c
/******************************************************************************* Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ /// \file /// Computes forces for the 12-6 Lennard Jones (LJ) potential. /// /// The Lennard-Jones model is not a good representation for the /// bonding in copper, its use has been limited to constant volume /// simulations where the embedding energy contribution to the cohesive /// energy is not included in the two-body potential /// /// The parameters here are taken from Wolf and Phillpot and fit to the /// room temperature lattice constant and the bulk melt temperature /// Ref: D. Wolf and S.Yip eds. Materials Interfaces (Chapman & Hall /// 1992) Page 230. /// /// Notes on LJ: /// /// http://en.wikipedia.org/wiki/Lennard_Jones_potential /// /// The total inter-atomic potential energy in the LJ model is: /// /// \f[ /// E_{tot} = \sum_{ij} U_{LJ}(r_{ij}) /// \f] /// \f[ /// U_{LJ}(r_{ij}) = 4 \epsilon /// \left\{ \left(\frac{\sigma}{r_{ij}}\right)^{12} /// - \left(\frac{\sigma}{r_{ij}}\right)^6 \right\} /// \f] /// /// where \f$\epsilon\f$ and \f$\sigma\f$ are the material parameters in the potential. /// - \f$\epsilon\f$ = well depth /// - \f$\sigma\f$ = hard sphere diameter /// /// To limit the interation range, the LJ potential is typically /// truncated to zero at some cutoff distance. A common choice for the /// cutoff distance is 2.5 * \f$\sigma\f$. /// This implementation can optionally shift the potential slightly /// upward so the value of the potential is zero at the cuotff /// distance. This shift has no effect on the particle dynamics. /// /// /// The force on atom i is given by /// /// \f[ /// F_i = -\nabla_i \sum_{jk} U_{LJ}(r_{jk}) /// \f] /// /// where the subsrcipt i on the gradient operator indicates that the /// derivatives are taken with respect to the coordinates of atom i. /// Liberal use of the chain rule leads to the expression /// /// \f{eqnarray*}{ /// F_i &=& - \sum_j U'_{LJ}(r_{ij})\hat{r}_{ij}\\ /// &=& \sum_j 24 \frac{\epsilon}{r_{ij}} \left\{ 2 \left(\frac{\sigma}{r_{ij}}\right)^{12} /// - \left(\frac{\sigma}{r_{ij}}\right)^6 \right\} \hat{r}_{ij} /// \f} /// /// where \f$\hat{r}_{ij}\f$ is a unit vector in the direction from atom /// i to atom j. /// /// #include "ljForce.h" #include <stdlib.h> #include <assert.h> #include <string.h> #include <omp.h> #include "constants.h" #include "mytype.h" #include "parallel.h" #include "linkCells.h" #include "memUtils.h" #include "CoMDTypes.h" #define POT_SHIFT 1.0 /// Derived struct for a Lennard Jones potential. /// Polymorphic with BasePotential. /// \see BasePotential typedef struct LjPotentialSt { real_t cutoff; //!< potential cutoff distance in Angstroms real_t mass; //!< mass of atoms in intenal units real_t lat; //!< lattice spacing (angs) of unit cell char latticeType[8]; //!< lattice type, e.g. FCC, BCC, etc. char name[3]; //!< element name int atomicNo; //!< atomic number int (*force)(SimFlat* s); //!< function pointer to force routine void (*print)(FILE* file, BasePotential* pot); void (*destroy)(BasePotential** pot); //!< destruction of the potential real_t sigma; real_t epsilon; } LjPotential; static int ljForce(SimFlat* s); static void ljPrint(FILE* file, BasePotential* pot); void ljDestroy(BasePotential** inppot) { if ( ! inppot ) return; LjPotential* pot = (LjPotential*)(*inppot); if ( ! pot ) return; comdFree(pot); *inppot = NULL; return; } /// Initialize an Lennard Jones potential for Copper. BasePotential* initLjPot(void) { LjPotential *pot = (LjPotential*)comdMalloc(sizeof(LjPotential)); pot->force = ljForce; pot->print = ljPrint; pot->destroy = ljDestroy; pot->sigma = 2.315; // Angstrom pot->epsilon = 0.167; // eV pot->mass = 63.55 * amuToInternalMass; // Atomic Mass Units (amu) pot->lat = 3.615; // Equilibrium lattice const in Angs strcpy(pot->latticeType, "FCC"); // lattice type, i.e. FCC, BCC, etc. pot->cutoff = 2.5*pot->sigma; // Potential cutoff in Angs strcpy(pot->name, "Cu"); pot->atomicNo = 29; return (BasePotential*) pot; } void ljPrint(FILE* file, BasePotential* pot) { LjPotential* ljPot = (LjPotential*) pot; fprintf(file, " Potential type : Lennard-Jones\n"); fprintf(file, " Species name : %s\n", ljPot->name); fprintf(file, " Atomic number : %d\n", ljPot->atomicNo); fprintf(file, " Mass : "FMT1" amu\n", ljPot->mass / amuToInternalMass); // print in amu fprintf(file, " Lattice Type : %s\n", ljPot->latticeType); fprintf(file, " Lattice spacing : "FMT1" Angstroms\n", ljPot->lat); fprintf(file, " Cutoff : "FMT1" Angstroms\n", ljPot->cutoff); fprintf(file, " Epsilon : "FMT1" eV\n", ljPot->epsilon); fprintf(file, " Sigma : "FMT1" Angstroms\n", ljPot->sigma); } int ljForce(SimFlat* s) { LjPotential* pot = (LjPotential *) s->pot; real_t sigma = pot->sigma; real_t epsilon = pot->epsilon; real_t rCut = pot->cutoff; real_t rCut2 = rCut*rCut; // zero forces and energy real_t ePot = 0.0; s->ePotential = 0.0; int fSize = s->boxes->nTotalBoxes*MAXATOMS; for (int ii=0; ii<fSize; ++ii) { zeroReal3(s->atoms->f[ii]); s->atoms->U[ii] = 0.; } real_t s6 = sigma*sigma*sigma*sigma*sigma*sigma; real_t rCut6 = s6 / (rCut2*rCut2*rCut2); real_t eShift = POT_SHIFT * rCut6 * (rCut6 - 1.0); int nNbrBoxes = 27; // Flattening structures int cnt = s->boxes->nLocalBoxes; int *nAtoms = s->boxes->nAtoms; real_t *r = (real_t *) s->atoms->r; real_t *f = (real_t *) s->atoms->f; real_t *U = s->atoms->U; int *nbrBoxes = (int *)s->boxes->nbrBoxes; int maxTotalAtoms = s->boxes->nTotalBoxes * MAXATOMS; int nTotalBoxes = 27 * s->boxes->nTotalBoxes; int nBoxes = s->boxes->nTotalBoxes; real_t *ePotLocal = (real_t *)calloc(cnt, sizeof(real_t)); int numTeams = cnt < 20000 ? cnt : 20000; #pragma omp target data map(to: cnt, eShift, s6, rCut2, epsilon, \ r[:maxTotalAtoms*3], \ nAtoms[:nBoxes], \ nbrBoxes[:nTotalBoxes]) \ map(tofrom: U[:maxTotalAtoms],\ f[:maxTotalAtoms*3], \ ePotLocal[:cnt]) #pragma omp target teams distribute num_teams(numTeams) thread_limit(27) for (int iBox = 0; iBox < cnt; iBox++) { int nIBox = nAtoms[iBox]; real_t ePot1 = 0.0; // loop over neighbors of iBox #pragma omp parallel for reduction (+:ePot1) for (int jTmp = 0; jTmp < 27; jTmp++) { int jBox = nbrBoxes[iBox*27 + jTmp]; if(jBox >= 0) { int nJBox = nAtoms[jBox]; // loop over atoms in iBox for (int iOff = MAXATOMS*iBox; iOff < (iBox*MAXATOMS + nIBox); iOff++) { real_t iU = 0.0; real_t if3[3] = {0.0,0.0,0.0}; // loop over atoms in jBox for (int jOff = jBox*MAXATOMS; jOff < (jBox*MAXATOMS+nJBox); jOff++) { real3 dr; real_t r2 = 0.0; for (int m=0; m<3; m++) { dr[m] = r[iOff*3+m] - r[jOff*3+m]; r2 += dr[m] * dr[m]; } if ( r2 <= rCut2 && r2 > 0.0) { // Important note: // from this point on r actually refers to 1.0/r r2 = 1.0/r2; real_t r6 = s6 * (r2 * r2 * r2); real_t eLocal = r6 * (r6 - 1.0) - eShift; iU += 0.5 * eLocal; ePot1 += 0.5*eLocal; // different formulation to avoid sqrt computation real_t fr = - 4.0 * epsilon * r6 * r2 * (12.0*r6 - 6.0); for (int m=0; m<3; m++) { if3[m] -= dr[m] * fr; } } } // loop over atoms in jBox #pragma omp atomic update U[iOff] += iU; for (int m=0; m<3; m++) #pragma omp atomic update f[iOff*3+m] += if3[m]; } // loop over atoms in iBox } } // loop over neighbor boxes ePotLocal[iBox] = ePot1; } // loop over local boxes in system for(int i = 0; i < cnt; i++) ePot += ePotLocal[i]; ePot = ePot*4.0*epsilon; s->ePotential = ePot; free(ePotLocal); return 0; }
bufradixsort_relocate.h
#ifndef BUFRADIXSORT_RELOCATE_H #define BUFRADIXSORT_RELOCATE_H #include "bufradixsort_common.h" #include <limits.h> #include <stddef.h> #include <stdint.h> #include <string.h> #if EXT_UNIQID(SSE2) == EXT_UNIQID(EXT_STREAM) #include <emmintrin.h> #include <smmintrin.h> #endif /* COPYMASKBUF */ #define COPYMASKBUF CAT(COPYMASKBUF_EXT_, EXT_STREAM) #define COPYMASKBUF_EXT_NONE() do { \ unsigned int i; \ for (i = 0; i < BUFFER_SIZE; i++) \ ASSUME_ALIGNED(copy_point_rst, BUFFER_SIZE)[i] = \ ASSUME_ALIGNED(buf_point_rst, BUFFER_SIZE)[i] ^ ASSUME_ALIGNED(float_mask_rst, BUFFER_SIZE)[i]; \ } while (0) #define COPYMASKBUF_EXT_SSE2() do { \ unsigned int i; \ for (i = 0; i < BUFFER_SIZE/16; i++) \ _mm_stream_si128((__m128i*)copy_point_rst+i, \ _mm_xor_si128(_mm_load_si128((__m128i*)buf_point_rst+i), _mm_load_si128((__m128i*)float_mask_rst+i))); \ } while(0) #if defined(__GNUC__) #pragma GCC optimize("tree-vectorize") #pragma GCC optimize("unroll-loops") #endif static int relocate_float_buf_full(unsigned int first_buf_bkt, unsigned char *restrict buf_point_rst, unsigned int bkt, unsigned char *restrict *restrict copy_points_rst, unsigned int invalid_elems_offset, const unsigned char *restrict float_mask_rst) { unsigned char *copy_point_rst = copy_points_rst[bkt]; copy_points_rst[bkt] = copy_point_rst + BUFFER_SIZE; if (UNLIKELY(bkt == first_buf_bkt)) { unsigned int i; for (i = invalid_elems_offset; i < BUFFER_SIZE; i++) copy_point_rst[i] = buf_point_rst[i] ^ float_mask_rst[i]; return BKT; } else { COPYMASKBUF(); return first_buf_bkt; } } #define RELOCATE_FLOAT_KERNEL(ELEM_SIZE) do { \ unsigned int bkt = *data_cur; \ data_cur += ELEM_SIZE; \ SIZEUTYP(ELEM_SIZE) val; \ memcpy(&val, data_rst, sizeof(val)); \ data_rst += ELEM_SIZE; \ unsigned char *buf_point_rst = buf_points_rst[bkt]; \ memcpy(buf_point_rst, &val, sizeof(val)); \ buf_point_rst += ELEM_SIZE; \ if (((uintptr_t)buf_point_rst & (BUFFER_SIZE-1)) == 0) { \ buf_point_rst -= BUFFER_SIZE; \ if (bkt < BKT>>1) \ first_buf_bkt = relocate_buf_full(first_buf_bkt, buf_point_rst, bkt, \ copy_points_rst, invalid_elems_offset); \ else \ first_buf_bkt = relocate_float_buf_full(first_buf_bkt, buf_point_rst, bkt, \ copy_points_rst, invalid_elems_offset, float_mask_rst); \ } \ buf_points_rst[bkt] = buf_point_rst; \ } while (0) #define RELOCATE_FLOAT_IF_F_DO(ELEM_SIZE) do { \ const unsigned char *data_cur = data_rst + bkt_pos_base + real_pos; \ while (data_rst < data_algn) { \ RELOCATE_FLOAT_KERNEL(ELEM_SIZE); \ } \ while (data_rst < data_end) { \ PREFETCH(data_rst+128, 0, 0); \ ITERARG(UNROLL_RELOCATE, RELOCATE_FLOAT_KERNEL, ELEM_SIZE); \ } \ } while (0) #define RELOCATE_FLOAT_IF_F(ELEM_SIZE) \ IF0(SUB(DIV(INDEX(0, SUPPORTED_FLOAT_BITS_LIST_LEN, SUPPORTED_FLOAT_BITS_LIST), BKT_BIT), ELEM_SIZE), \ RELOCATE_FLOAT_IF_F_DO(ELEM_SIZE), ;) /* * Otherwise, simply relocate. */ #define COPYBUF CAT(COPYBUF_EXT_, EXT_STREAM) #define COPYBUF_EXT_NONE() \ memcpy(ASSUME_ALIGNED(copy_point_rst, BUFFER_SIZE), ASSUME_ALIGNED(buf_point_rst, BUFFER_SIZE), BUFFER_SIZE) #define COPYBUF_EXT_SSE2() \ ITERNUM(DIV(BUFFER_SIZE, 16), COPYBUF_EXT_SSE2_KERNEL) #define COPYBUF_EXT_SSE2_KERNEL(n) \ _mm_stream_si128((__m128i*)copy_point_rst+n, _mm_load_si128((__m128i*)buf_point_rst+n)) #if defined(__GNUC__) #pragma GCC optimize("tree-vectorize") #pragma GCC optimize("unroll-loops") #endif static int relocate_buf_full(unsigned int first_buf_bkt, unsigned char *restrict buf_point_rst, unsigned int bkt, unsigned char *restrict *restrict copy_points_rst, unsigned int invalid_elems_offset) { unsigned char *copy_point_rst = copy_points_rst[bkt]; copy_points_rst[bkt] = copy_point_rst + BUFFER_SIZE; if (UNLIKELY(bkt == first_buf_bkt)) { unsigned int i; for (i = invalid_elems_offset; i < BUFFER_SIZE; i++) copy_point_rst[i] = buf_point_rst[i]; return BKT; } else { COPYBUF(); return first_buf_bkt; } } #define RELOCATE_NONFLOAT_KERNEL(ELEM_SIZE) do { \ unsigned int bkt = *data_cur; \ data_cur += ELEM_SIZE; \ SIZEUTYP(ELEM_SIZE) val; \ memcpy(&val, (SIZEUTYP(ELEM_SIZE)*)data_rst, sizeof(val)); \ data_rst += ELEM_SIZE; \ unsigned char *restrict buf_point_rst = buf_points_rst[bkt]; \ memcpy((SIZEUTYP(ELEM_SIZE)*)buf_point_rst, &val, sizeof(val)); \ buf_point_rst += ELEM_SIZE; \ if (((uintptr_t)buf_point_rst & (BUFFER_SIZE-1)) == 0) { \ buf_point_rst -= BUFFER_SIZE; \ first_buf_bkt = relocate_buf_full(first_buf_bkt, buf_point_rst, bkt, copy_points_rst, invalid_elems_offset); \ } \ buf_points_rst[bkt] = buf_point_rst; \ } while(0) #define RELOCATE_NONFLOAT_IF_F(ELEM_SIZE) do { \ const unsigned char *data_cur = data_rst + bkt_pos_base + real_pos; \ while (data_rst < data_algn) { \ RELOCATE_NONFLOAT_KERNEL(ELEM_SIZE); \ } \ while (data_rst < data_end) { \ PREFETCH(data_rst+128, 0, 0); \ ITERARG(UNROLL_RELOCATE, RELOCATE_NONFLOAT_KERNEL, ELEM_SIZE); \ } \ } while (0) /* * Generic part. */ #define RELOCATE_CASE_E(ELEM_SIZE_LOG) case ELEM_SIZE_LOG: { \ if (float_bits_if_msb) { \ RELOCATE_FLOAT_IF_F(POW(2, ELEM_SIZE_LOG)); \ } else { \ RELOCATE_NONFLOAT_IF_F(POW(2, ELEM_SIZE_LOG)); \ } \ } break static void relocate_data(const unsigned char *data, const unsigned char *data_end, unsigned char *dest, unsigned int elem_size_log, unsigned int bkt_pos_base, unsigned int real_pos, unsigned int float_bits_if_msb, unsigned int bkt_fix_sign, const size_t *histo, unsigned char **copy_points) { #ifdef ALIGNED unsigned char ALIGNED(BUFFER_SIZE) buf[BKT][BUFFER_SIZE]; unsigned char ALIGNED(BUFFER_SIZE) float_mask[BUFFER_SIZE]; #else unsigned char buf_space[BKT*(BUFFER_SIZE+2)]; unsigned char (*buf)[BUFFER_SIZE] = (unsigned char(*)[BUFFER_SIZE])(buf_space + (-(uintptr_t)buf_space & (BUFFER_SIZE-1))); unsigned char (*float_mask)[BUFFER_SIZE] = buf+BKT; #endif unsigned char *buf_points[BKT]; unsigned int first_buf_bkt = BKT; unsigned int invalid_elems_offset = 0; unsigned int bkt; /* * If current thread is sorting to the first area of destination, * even temporalily writing to the preceeding position should be considered as dangerous, * since they could be used by other parts of the program or be protected by segment. * So we must detect writing to the first position. */ { unsigned char *dest_algn = (void*)((uintptr_t)dest & -BUFFER_SIZE); if (dest != dest_algn) { unsigned char *dest_algn_up = dest_algn + BUFFER_SIZE; for (bkt = 0; bkt < BKT; bkt++) { unsigned char *strt_point = copy_points[bkt^bkt_fix_sign]; unsigned char *ends_point = strt_point + histo[bkt^bkt_fix_sign]; if (ends_point >= dest_algn_up) { if (strt_point < dest_algn_up) { first_buf_bkt = bkt^bkt_fix_sign; invalid_elems_offset = strt_point - dest_algn; } break; } } } } /* * Set up buf_points and copy_points (aligned), that is displays of the buffers and the dest resp. * Copypoints are aligned by the number of elements of a buffer. */ for (bkt = 0; bkt < BKT; bkt++) { unsigned char *copy_point = copy_points[bkt]; unsigned char *copy_point_algn = (void*)((uintptr_t)copy_point & -BUFFER_SIZE); int buf_offset = copy_point - copy_point_algn; copy_points[bkt] = copy_point - buf_offset; buf_points[bkt] = buf[bkt] + buf_offset; } /* * Set up float mask. */ memset(float_mask, 0, BUFFER_SIZE); if (float_bits_if_msb) { unsigned int i, j; for (i = 0; i < BUFFER_SIZE; i += 1 << elem_size_log) for (j = 0; j < float_bits_if_msb/BKT_BIT-1; j++) if (j != real_pos) float_mask[i + bkt_pos_base + j] = BKT-1; } /* * Run kernel. */ { const unsigned char *restrict data_rst = data; unsigned char *restrict *restrict buf_points_rst = buf_points; unsigned char *restrict *restrict copy_points_rst = copy_points; const unsigned char *data_algn = data + ((((data_end - data) >> elem_size_log) % UNROLL_RELOCATE) << elem_size_log); const unsigned char *restrict float_mask_rst = float_mask; switch (elem_size_log) { ITERNUM(SUCC(ELEM_SIZE_LOG_MAX), RELOCATE_CASE_E); } } #ifdef _OPENMP #pragma omp barrier #endif for (bkt = 0; bkt < BKT; bkt++) { unsigned char *ends_point = copy_points[bkt] + (buf_points[bkt] - buf[bkt]); unsigned char *strt_point = ends_point - histo[bkt]; unsigned char *ends_point_algn = (void*)((uintptr_t)ends_point & -BUFFER_SIZE); unsigned char *strt_point_algn = (void*)((uintptr_t)strt_point & -BUFFER_SIZE); unsigned char *copy_point; unsigned char *buf_point; if (strt_point_algn == ends_point_algn) { copy_point = strt_point; buf_point = buf[bkt] + (strt_point - strt_point_algn); } else { copy_point = ends_point_algn; buf_point = buf[bkt]; } while (copy_point < ends_point) *copy_point++ = *buf_point++; } } #endif /* BUFRADIXSORT_RELOCATE_H */
MatrixOp.c
#include "../include/MatrixOp.h" //==================== vector operations =========================== // put random values into the matrix if mode == 0 struct Vector * new_vec(int length, int mode) { struct Vector *vecp = (struct Vector *)malloc(sizeof(struct Vector)); vecp->length = length; vecp->vec = (float*)malloc(vecp->length * sizeof(float)); for(int i = 0;i < length;i++) vecp->vec[i] = mode ? 0 : (((float)rand()) / RAND_MAX); return vecp; } void free_vec(struct Vector *vecp) { free(vecp->vec); free(vecp); } void print_vec(struct Vector *vecp) { if(vecp == NULL) return ; for(int i = 0;i < vecp->length;i++) printf("%lf ", vecp->vec[i]); printf("\n"); } //==================== matrix operations =========================== struct Matrix * new_mat(int m, int n, int mode) { struct Matrix *matp = (struct Matrix*)malloc(sizeof(struct Matrix)); matp->m = m, matp->n = n; matp->mat = (struct Vector**)malloc(m * sizeof(struct Vector*)); for(int i = 0;i < m;i++) { matp->mat[i] = new_vec(n, mode); } return matp; } void free_mat(struct Matrix *matp) { for(int i = 0;i < matp->m;i++) free_vec(matp->mat[i]); free(matp); } void print_mat(struct Matrix *matp) { if(matp == NULL) return ; for(int i = 0;i < matp->m;i++) print_vec(matp->mat[i]); printf("\n"); } // take two corners and return the corresponding sub-matrix struct Matrix * submat(struct Matrix *Mat, int upperLefty, int upperLeftx, int lowerRighty, int lowerRightx) { struct Matrix *resMat = NULL; if(upperLefty > lowerRighty || upperLeftx > lowerRightx) return resMat; if(upperLefty < 0 || upperLeftx < 0 || lowerRighty >= Mat->m || lowerRightx >= Mat->n) return resMat; resMat = new_mat(lowerRighty - upperLefty + 1, lowerRightx - upperLeftx + 1, 1); int i, threadCount = omp_get_num_procs(); #pragma omp parallel for num_threads(threadCount) default(none) shared(upperLefty, upperLeftx, lowerRighty, lowerRightx, resMat, Mat) private(i) for(i = upperLefty;i <= lowerRighty;i++) for(int j = upperLeftx;j <= lowerRightx;j++) { resMat->mat[i-upperLefty]->vec[j-upperLeftx] = Mat->mat[i]->vec[j]; } return resMat; } // matrix addition/subtraction, optimized by OpenMP and AVX2 // add for mode == 0 and sub for mode == 1 int sign[2]={1,-1}; struct Matrix * matrix_add_sub(struct Matrix *mata, struct Matrix *matb, int mode) { struct Matrix *resMat = NULL; if(mata->m != matb->m || mata->n != matb->n) return resMat; resMat = new_mat(mata->m, mata->n, 1); int i, threadCount = omp_get_num_procs(); #pragma omp parallel for num_threads(threadCount) shared(resMat, mata, matb, sign, mode) private(i) for(i = 0;i < mata->m;i++) { for(int k = 0;k < mata->n / 8;k++) { __m256 intVec1 = _mm256_loadu_ps(&mata->mat[i]->vec[8*k]); __m256 intVec2 = _mm256_loadu_ps(&matb->mat[i]->vec[8*k]); __m256 intVec3 = mode ? _mm256_sub_ps(intVec1, intVec2) : _mm256_add_ps(intVec1, intVec2); _mm256_storeu_ps(&resMat->mat[i]->vec[8*k], intVec3); } for(int k = (mata->n / 8)*8;k < mata->n;k++) resMat->mat[i]->vec[k] = mata->mat[i]->vec[k] + sign[mode] * matb->mat[i]->vec[k]; } return resMat; } int mat_is_equal(struct Matrix *mata, struct Matrix *matb) { if(mata->m != matb->m || mata->n != matb->n) return 0; for(int i = 0;i < mata->m;i++) for(int j = 0;j < mata->n;j++) if(abs(mata->mat[i]->vec[j]-matb->mat[i]->vec[j]) > 1e-3) { #ifdef DEBUG printf("%lf, %lf\n", mata->mat[i]->vec[j], matb->mat[i]->vec[j]); #endif return 0; } return 1; } // combine four sub-matrices into one matrix; struct Matrix *combine_matrix(struct Matrix *upperLeftMat, struct Matrix *upperRightMat, struct Matrix *lowerLeftMat, struct Matrix *lowerRightMat) { struct Matrix *resMat = NULL; if(upperLeftMat->n != lowerLeftMat->n || upperRightMat->n != lowerRightMat->n) return resMat; if(upperLeftMat->m != upperRightMat->m || lowerLeftMat->m != lowerRightMat->m) return resMat; resMat = new_mat(upperLeftMat->m + lowerLeftMat->m, upperLeftMat->n + upperRightMat->n, 1); int i, threadCount = omp_get_num_procs(); #pragma omp parallel for num_threads(threadCount) default(none) shared(upperLeftMat, upperRightMat, resMat) private(i) for(i = 0;i < upperLeftMat->m;i++) { for(int j = 0;j < upperLeftMat->n;j++) resMat->mat[i]->vec[j] = upperLeftMat->mat[i]->vec[j]; for(int j = 0;j < upperRightMat->n;j++) resMat->mat[i]->vec[j+upperLeftMat->n] = upperRightMat->mat[i]->vec[j]; } #pragma omp parallel for num_threads(threadCount) default(none) shared(upperLeftMat, lowerLeftMat, lowerRightMat, resMat) private(i) for(i = 0;i < lowerLeftMat->m;i++) { for(int j = 0;j < lowerLeftMat->n;j++) resMat->mat[i+upperLeftMat->m]->vec[j] = lowerLeftMat->mat[i]->vec[j]; for(int j = 0;j < lowerRightMat->n;j++) resMat->mat[i+upperLeftMat->m]->vec[j+upperLeftMat->n] = lowerRightMat->mat[i]->vec[j]; } return resMat; } // copy matrix a into matrix b int copy_matrix(struct Matrix *mata, struct Matrix *matb, int uly, int ulx, int dy, int dx) { if(uly < 0 || ulx < 0 || dy < 0 || dx < 0 || dy > mata->m || dx > mata->n || uly + dy > matb->m || ulx + dx > matb->n) return 0; int y, x, threadCount = omp_get_num_procs(), i; #pragma omp parallel for num_threads(threadCount) default(none) shared(uly, ulx, dy, dx, mata, matb) private(i, x, y) for(i = 0;i < dy;i++) for(int j = 0;j < dx;j++) { y = uly + i, x = ulx + j; matb->mat[y]->vec[x] = mata->mat[i]->vec[j]; } } // optimization for the brutal multiplication void mul_1_by_1(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { register float res = 0; for(int k = 0;k < mata->n;k++) res += mata->mat[i]->vec[k] * matb->mat[k]->vec[j]; resMat->mat[i]->vec[j] = res; } void mul_1_by_8(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { register float resMat0, resMat1, resMat2, resMat3, resMat4, resMat5, resMat6, resMat7, mata0; resMat0 = resMat1 = resMat2 = resMat3 = resMat4 = resMat5 = resMat6 = resMat7 = 0; for(int k = 0;k < mata->n;k++) { mata0 = mata->mat[i]->vec[k]; resMat0 += mata0 * matb->mat[k]->vec[j]; resMat1 += mata0 * matb->mat[k]->vec[j+1]; resMat2 += mata0 * matb->mat[k]->vec[j+2]; resMat3 += mata0 * matb->mat[k]->vec[j+3]; resMat4 += mata0 * matb->mat[k]->vec[j+4]; resMat5 += mata0 * matb->mat[k]->vec[j+5]; resMat6 += mata0 * matb->mat[k]->vec[j+6]; resMat7 += mata0 * matb->mat[k]->vec[j+7]; } resMat->mat[i]->vec[j] = resMat0; resMat->mat[i]->vec[j+1] = resMat1; resMat->mat[i]->vec[j+2] = resMat2; resMat->mat[i]->vec[j+3] = resMat3; resMat->mat[i]->vec[j+4] = resMat4; resMat->mat[i]->vec[j+5] = resMat5; resMat->mat[i]->vec[j+6] = resMat6; resMat->mat[i]->vec[j+7] = resMat7; } void mul_8_by_1(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { mul_1_by_1(resMat, mata, matb, i, j); mul_1_by_1(resMat, mata, matb, i+1, j); mul_1_by_1(resMat, mata, matb, i+2, j); mul_1_by_1(resMat, mata, matb, i+3, j); mul_1_by_1(resMat, mata, matb, i+4, j); mul_1_by_1(resMat, mata, matb, i+5, j); mul_1_by_1(resMat, mata, matb, i+6, j); mul_1_by_1(resMat, mata, matb, i+7, j); } void mul_8_by_8(struct Matrix *resMat, struct Matrix *mata, struct Matrix *matb, int i, int j) { __m256 vecb, veca0, veca1, veca2, veca3, veca4, veca5, veca6, veca7, resMat0, resMat1, resMat2, resMat3, resMat4, resMat5, resMat6, resMat7; for(int k = 0;k < mata->n;k++) { vecb = _mm256_loadu_ps(&matb->mat[k]->vec[j]); veca0 = _mm256_broadcast_ss(&mata->mat[i]->vec[k]); veca1 = _mm256_broadcast_ss(&mata->mat[i+1]->vec[k]); veca2 = _mm256_broadcast_ss(&mata->mat[i+2]->vec[k]); veca3 = _mm256_broadcast_ss(&mata->mat[i+3]->vec[k]); veca4 = _mm256_broadcast_ss(&mata->mat[i+4]->vec[k]); veca5 = _mm256_broadcast_ss(&mata->mat[i+5]->vec[k]); veca6 = _mm256_broadcast_ss(&mata->mat[i+6]->vec[k]); veca7 = _mm256_broadcast_ss(&mata->mat[i+7]->vec[k]); resMat0 = k ? _mm256_add_ps(resMat0, _mm256_mul_ps(veca0, vecb)) : _mm256_mul_ps(veca0, vecb); resMat1 = k ? _mm256_add_ps(resMat1, _mm256_mul_ps(veca1, vecb)) : _mm256_mul_ps(veca1, vecb); resMat2 = k ? _mm256_add_ps(resMat2, _mm256_mul_ps(veca2, vecb)) : _mm256_mul_ps(veca2, vecb); resMat3 = k ? _mm256_add_ps(resMat3, _mm256_mul_ps(veca3, vecb)) : _mm256_mul_ps(veca3, vecb); resMat4 = k ? _mm256_add_ps(resMat4, _mm256_mul_ps(veca4, vecb)) : _mm256_mul_ps(veca4, vecb); resMat5 = k ? _mm256_add_ps(resMat5, _mm256_mul_ps(veca5, vecb)) : _mm256_mul_ps(veca5, vecb); resMat6 = k ? _mm256_add_ps(resMat6, _mm256_mul_ps(veca6, vecb)) : _mm256_mul_ps(veca6, vecb); resMat7 = k ? _mm256_add_ps(resMat7, _mm256_mul_ps(veca7, vecb)) : _mm256_mul_ps(veca7, vecb); } _mm256_storeu_ps(&resMat->mat[i]->vec[j], resMat0); _mm256_storeu_ps(&resMat->mat[i+1]->vec[j], resMat1); _mm256_storeu_ps(&resMat->mat[i+2]->vec[j], resMat2); _mm256_storeu_ps(&resMat->mat[i+3]->vec[j], resMat3); _mm256_storeu_ps(&resMat->mat[i+4]->vec[j], resMat4); _mm256_storeu_ps(&resMat->mat[i+5]->vec[j], resMat5); _mm256_storeu_ps(&resMat->mat[i+6]->vec[j], resMat6); _mm256_storeu_ps(&resMat->mat[i+7]->vec[j], resMat7); } //==================== Other helper operations =========================== int Min(int a, int b) { return a > b ? b : a; } int Max(int a, int b) { return a > b ? a : b; }
LAGraph_BF_full2.c
//------------------------------------------------------------------------------ // LAGraph_BF_full2.c: Bellman-Ford single-source shortest paths, returns tree, // while diagonal of input matrix A needs not to be explicit 0, using the // frontier idea from Roi Lipman //------------------------------------------------------------------------------ // LAGraph, (c) 2021 by The LAGraph Contributors, All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause // // See additional acknowledgments in the LICENSE file, // or contact permission@sei.cmu.edu for the full terms. //------------------------------------------------------------------------------ // LAGraph_BF_full2: Bellman-Ford single source shortest paths, returning both // the path lengths and the shortest-path tree. contributed by Jinhao Chen and // Tim Davis, Texas A&M. // LAGraph_BF_full2 performs a Bellman-Ford to find out shortest path, parent // nodes along the path and the hops (number of edges) in the path from given // source vertex s in the range of [0, n) on graph given as matrix A with size // n*n. The sparse matrix A has entry A(i, j) if there is an edge from vertex i // to vertex j with weight w, then A(i, j) = w. // LAGraph_BF_full2 returns GrB_SUCCESS if it succeeds. In this case, there // are no negative-weight cycles in the graph, and d, pi, and h are returned. // The vector d has d(k) as the shortest distance from s to k. pi(k) = p+1, // where p is the parent node of k-th node in the shortest path. In particular, // pi(s) = 0. h(k) = hop(s, k), the number of edges from s to k in the shortest // path. // If the graph has a negative-weight cycle, GrB_NO_VALUE is returned, and the // GrB_Vectors d(k), pi(k) and h(k) (i.e., *pd_output, *ppi_output and // *ph_output respectively) will be NULL when negative-weight cycle detected. // Otherwise, other errors such as GrB_OUT_OF_MEMORY, GrB_INVALID_OBJECT, and // so on, can be returned, if these errors are found by the underlying // GrB_* functions. //------------------------------------------------------------------------------ #define LAGraph_FREE_WORK \ { \ GrB_free(&d); \ GrB_free(&dtmp); \ GrB_free(&dfrontier); \ GrB_free(&Atmp); \ GrB_free(&BF_Tuple3); \ GrB_free(&BF_lMIN_Tuple3); \ GrB_free(&BF_PLUSrhs_Tuple3); \ GrB_free(&BF_EQ_Tuple3); \ GrB_free(&BF_lMIN_Tuple3_Monoid); \ GrB_free(&BF_lMIN_PLUSrhs_Tuple3); \ LAGraph_Free ((void**)&I); \ LAGraph_Free ((void**)&J); \ LAGraph_Free ((void**)&w); \ LAGraph_Free ((void**)&W); \ LAGraph_Free ((void**)&h); \ LAGraph_Free ((void**)&pi); \ } #define LAGraph_FREE_ALL \ { \ LAGraph_FREE_WORK \ GrB_free (pd_output); \ GrB_free (ppi_output); \ GrB_free (ph_output); \ } #include <LAGraph.h> #include <LAGraphX.h> #include <LG_internal.h> // from src/utility typedef void (*LAGraph_binary_function) (void *, const void *, const void *) ; //------------------------------------------------------------------------------ // data type for each entry of the adjacent matrix A and "distance" vector d; // <INFINITY,INFINITY,INFINITY> corresponds to nonexistence of a path, and // the value <0, 0, NULL> corresponds to a path from a vertex to itself //------------------------------------------------------------------------------ typedef struct { double w; // w corresponds to a path weight. GrB_Index h; // h corresponds to a path size or number of hops. GrB_Index pi;// pi corresponds to the penultimate vertex along a path. // vertex indexed as 1, 2, 3, ... , V, and pi = 0 (as nil) // for u=v, and pi = UINT64_MAX (as inf) for (u,v) not in E } BF2_Tuple3_struct; //------------------------------------------------------------------------------ // binary functions, z=f(x,y), where Tuple3xTuple3 -> Tuple3 //------------------------------------------------------------------------------ void BF2_lMIN2 ( BF2_Tuple3_struct *z, const BF2_Tuple3_struct *x, const BF2_Tuple3_struct *y ) { if (x->w < y->w || (x->w == y->w && x->h < y->h) || (x->w == y->w && x->h == y->h && x->pi < y->pi)) { if (z != x) { *z = *x; } } else { *z = *y; } } void BF2_PLUSrhs2 ( BF2_Tuple3_struct *z, const BF2_Tuple3_struct *x, const BF2_Tuple3_struct *y ) { z->w = x->w + y->w ; z->h = x->h + y->h ; z->pi = (x->pi != UINT64_MAX && y->pi != 0) ? y->pi : x->pi ; } void BF2_EQ ( bool *z, const BF2_Tuple3_struct *x, const BF2_Tuple3_struct *y ) { (*z) = (x->w == y->w && x->h == y->h && x->pi == y->pi) ; } // Given a n-by-n adjacency matrix A and a source vertex s. // If there is no negative-weight cycle reachable from s, return the distances // of shortest paths from s and parents along the paths as vector d. Otherwise, // returns d=NULL if there is a negtive-weight cycle. // pd_output is pointer to a GrB_Vector, where the i-th entry is d(s,i), the // sum of edges length in the shortest path // ppi_output is pointer to a GrB_Vector, where the i-th entry is pi(i), the // parent of i-th vertex in the shortest path // ph_output is pointer to a GrB_Vector, where the i-th entry is h(s,i), the // number of edges from s to i in the shortest path // A has weights on corresponding entries of edges // s is given index for source vertex GrB_Info LAGraph_BF_full2 ( GrB_Vector *pd_output, //the pointer to the vector of distance GrB_Vector *ppi_output, //the pointer to the vector of parent GrB_Vector *ph_output, //the pointer to the vector of hops const GrB_Matrix A, //matrix for the graph const GrB_Index s //given index of the source ) { GrB_Info info; char *msg = NULL ; // tmp vector to store distance vector after n (i.e., V) loops GrB_Vector d = NULL, dtmp = NULL, dfrontier = NULL; GrB_Matrix Atmp = NULL; GrB_Type BF_Tuple3; GrB_BinaryOp BF_lMIN_Tuple3; GrB_BinaryOp BF_PLUSrhs_Tuple3; GrB_BinaryOp BF_EQ_Tuple3; GrB_Monoid BF_lMIN_Tuple3_Monoid; GrB_Semiring BF_lMIN_PLUSrhs_Tuple3; GrB_Index nrows, ncols, n, nz; // n = # of row/col, nz = # of nnz in graph GrB_Index *I = NULL, *J = NULL; // for col/row indices of entries from A GrB_Index *h = NULL, *pi = NULL; double *w = NULL; BF2_Tuple3_struct *W = NULL; LG_CHECK (A == NULL || pd_output == NULL || ppi_output == NULL || ph_output == NULL, -1001, "inputs are NULL") ; *pd_output = NULL; *ppi_output = NULL; *ph_output = NULL; GrB_TRY (GrB_Matrix_nrows (&nrows, A)) ; GrB_TRY (GrB_Matrix_ncols (&ncols, A)) ; GrB_TRY (GrB_Matrix_nvals (&nz, A)); LG_CHECK (nrows != ncols, -1002, "A must be square") ; n = nrows; LG_CHECK (s >= n || s < 0, -1003, "invalid source node") ; //-------------------------------------------------------------------------- // create all GrB_Type GrB_BinaryOp GrB_Monoid and GrB_Semiring //-------------------------------------------------------------------------- // GrB_Type GrB_TRY (GrB_Type_new(&BF_Tuple3, sizeof(BF2_Tuple3_struct))); // GrB_BinaryOp GrB_TRY (GrB_BinaryOp_new(&BF_EQ_Tuple3, (LAGraph_binary_function) (&BF2_EQ), GrB_BOOL, BF_Tuple3, BF_Tuple3)); GrB_TRY (GrB_BinaryOp_new(&BF_lMIN_Tuple3, (LAGraph_binary_function) (&BF2_lMIN2), BF_Tuple3, BF_Tuple3, BF_Tuple3)); GrB_TRY (GrB_BinaryOp_new(&BF_PLUSrhs_Tuple3, (LAGraph_binary_function)(&BF2_PLUSrhs2), BF_Tuple3, BF_Tuple3, BF_Tuple3)); // GrB_Monoid BF2_Tuple3_struct BF_identity = (BF2_Tuple3_struct) { .w = INFINITY, .h = UINT64_MAX, .pi = UINT64_MAX }; LAGRAPH_OK(GrB_Monoid_new_UDT(&BF_lMIN_Tuple3_Monoid, BF_lMIN_Tuple3, &BF_identity)); //GrB_Semiring GrB_TRY (GrB_Semiring_new(&BF_lMIN_PLUSrhs_Tuple3, BF_lMIN_Tuple3_Monoid, BF_PLUSrhs_Tuple3)); //-------------------------------------------------------------------------- // allocate arrays used for tuplets //-------------------------------------------------------------------------- I = LAGraph_Malloc (nz, sizeof(GrB_Index)) ; J = LAGraph_Malloc (nz, sizeof(GrB_Index)) ; w = LAGraph_Malloc (nz, sizeof(double)) ; W = LAGraph_Malloc (nz, sizeof(BF2_Tuple3_struct)) ; LG_CHECK (I == NULL || J == NULL || w == NULL || W == NULL, -1004, "out of memory") ; //-------------------------------------------------------------------------- // create matrix Atmp based on A, while its entries become BF_Tuple3 type //-------------------------------------------------------------------------- LAGRAPH_OK(GrB_Matrix_extractTuples_FP64(I, J, w, &nz, A)); int nthreads; LAGRAPH_OK( LAGraph_GetNumThreads (&nthreads, NULL)) ; printf ("nthreads %d\n", nthreads) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (GrB_Index k = 0; k < nz; k++) { if (w[k] == 0) //diagonal entries { W[k] = (BF2_Tuple3_struct) { .w = 0, .h = 0, .pi = 0 }; } else { W[k] = (BF2_Tuple3_struct) { .w = w[k], .h = 1, .pi = I[k] + 1 }; } } GrB_TRY (GrB_Matrix_new(&Atmp, BF_Tuple3, n, n)); LAGRAPH_OK(GrB_Matrix_build_UDT(Atmp, I, J, W, nz, BF_lMIN_Tuple3)); LAGraph_Free ((void**)&I); LAGraph_Free ((void**)&J); LAGraph_Free ((void**)&W); LAGraph_Free ((void**)&w); //-------------------------------------------------------------------------- // create and initialize "distance" vector d //-------------------------------------------------------------------------- GrB_TRY (GrB_Vector_new(&d, BF_Tuple3, n)); // initial distance from s to itself BF2_Tuple3_struct d0 = (BF2_Tuple3_struct) { .w = 0, .h = 0, .pi = 0 }; LAGRAPH_OK(GrB_Vector_setElement_UDT(d, &d0, s)); //-------------------------------------------------------------------------- // start the Bellman Ford process //-------------------------------------------------------------------------- // copy d to dtmp in order to create a same size of vector GrB_TRY (GrB_Vector_dup(&dtmp, d)); GrB_TRY (GrB_Vector_dup(&dfrontier, d)); bool same= false; // variable indicating if d == dtmp int64_t iter = 0; // number of iterations // terminate when no new path is found or more than V-1 loops while (!same && iter < n - 1) { // execute semiring on d and A, and save the result to dtmp GrB_TRY (GrB_vxm(dfrontier, GrB_NULL, GrB_NULL, BF_lMIN_PLUSrhs_Tuple3, dfrontier, Atmp, GrB_NULL)); // dtmp[i] = min(d[i], dfrontier[i]). GrB_Vector_eWiseAdd_BinaryOp(dtmp, GrB_NULL, GrB_NULL, BF_lMIN_Tuple3, d, dfrontier, GrB_NULL); LAGRAPH_OK (LAGraph_Vector_IsEqual_op(&same, dtmp, d, BF_EQ_Tuple3, NULL)); if (!same) { GrB_Vector ttmp = dtmp; dtmp = d; d = ttmp; } iter ++; } // check for negative-weight cycle only when there was a new path in the // last loop, otherwise, there can't be a negative-weight cycle. if (!same) { // execute semiring again to check for negative-weight cycle GrB_TRY (GrB_vxm(dfrontier, GrB_NULL, GrB_NULL, BF_lMIN_PLUSrhs_Tuple3, dfrontier, Atmp, GrB_NULL)); // dtmp[i] = min(d[i], dfrontier[i]). GrB_Vector_eWiseAdd_BinaryOp(dtmp, GrB_NULL, GrB_NULL, BF_lMIN_Tuple3, d, dfrontier, GrB_NULL); // if d != dtmp, then there is a negative-weight cycle in the graph LAGRAPH_OK (LAGraph_Vector_IsEqual_op(&same, dtmp, d, BF_EQ_Tuple3, NULL)); if (!same) { // printf("A negative-weight cycle found. \n"); LAGraph_FREE_ALL; return (GrB_NO_VALUE) ; } } //-------------------------------------------------------------------------- // extract tuple from "distance" vector d and create GrB_Vectors for output //-------------------------------------------------------------------------- I = LAGraph_Malloc (n, sizeof(GrB_Index)) ; W = LAGraph_Malloc (n, sizeof(BF2_Tuple3_struct)) ; w = LAGraph_Malloc (n, sizeof(double)) ; h = LAGraph_Malloc (n, sizeof(GrB_Index)) ; pi = LAGraph_Malloc (n, sizeof(GrB_Index)) ; LG_CHECK (I == NULL || W == NULL || w == NULL || h == NULL || pi == NULL, -1004, "out of memory") ; nz = n ; LAGRAPH_OK(GrB_Vector_extractTuples_UDT (I, (void *) W, &nz, d)); for (GrB_Index k = 0; k < nz; k++) { w [k] = W[k].w ; h [k] = W[k].h ; pi[k] = W[k].pi; } GrB_TRY (GrB_Vector_new(pd_output, GrB_FP64, n)); GrB_TRY (GrB_Vector_new(ppi_output, GrB_UINT64, n)); GrB_TRY (GrB_Vector_new(ph_output, GrB_UINT64, n)); GrB_TRY (GrB_Vector_build (*pd_output , I, w , nz, GrB_MIN_FP64 )); GrB_TRY (GrB_Vector_build (*ppi_output, I, pi, nz, GrB_MIN_UINT64)); GrB_TRY (GrB_Vector_build (*ph_output , I, h , nz, GrB_MIN_UINT64)); LAGraph_FREE_WORK; return (GrB_SUCCESS) ; }
nt.c
/*************************************************************************** * * (C) Copyright 2007 The Board of Trustees of the * University of Illinois * All Rights Reserved * * MRI-Q: Magnetic Resonance Imaging * Computes a matrix Q, representing the scanner configuration for * calibration, used in a 3D magnetic resonance image reconstruction * algorithms in non-Cartesian space. * ***************************************************************************/ /*************************************************************************** * * This benchmark was adapted to run on GPUs with OpenMP 4.0 pragmas * and OpenCL driver implemented in gpuclang 2.1 (based on clang 3.5) * * Marcio M Pereira <mpereira@ic.unicamp.br> * ***************************************************************************/ /* * C code for creating the Q data structure for fast convolution-based * Hessian multiplication for arbitrary k-space trajectories. * * Inputs: * kx - VECTOR of kx values, same length as ky and kz * ky - VECTOR of ky values, same length as kx and kz * kz - VECTOR of kz values, same length as kx and ky * x - VECTOR of x values, same length as y and z * y - VECTOR of y values, same length as x and z * z - VECTOR of z values, same length as x and y * phi - VECTOR of the Fourier transform of the spatial basis * function, evaluated at [kx, ky, kz]. Same length as kx, ky, and kz. */ /* * === NOTE === * * The Polyhedral optmization used in gpuclang restricts the class of loops it * can manipulate to sequences of imperfectly nested loops with particular * constraints on the loop bound and array subscript expressions. * * To allow this optimization we fixed the problem size with __STATIC__ tag * Comment this tag to use the original version. * * Recommended gpuclang options: * -O3 -lm -ffast-math -opt-poly=tile */ #ifndef __STATIC__ #define __STATIC__ #endif #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <inttypes.h> #include <sys/time.h> #ifdef __APPLE__ #include <sys/malloc.h> #include <machine/endian.h> #else #include <endian.h> #include <malloc.h> #endif #if _POSIX_VERSION >= 200112L # include <sys/time.h> #endif #if __BYTE_ORDER != __LITTLE_ENDIAN # error "File I/O is not implemented for this system: wrong endianness." #endif #define SMALL_FLOAT_VAL 0.00000001f #define ERROR_THRESHOLD 0.5 #define GPU_DEVICE 1 #define PI 3.1415926535897932384626433832795029f #define PIx2 6.2831853071795864769252867665590058f #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) #ifdef __STATIC__ // Define statically the problem size #define NK 2048 // K_ELEMS_PER_GRID #define NX 262144 #else int NK, NX; #endif double t_start, t_end, t_start_GPU, t_end_GPU; double rtclock() { struct timezone Tzp; struct timeval Tp; int stat; stat = gettimeofday (&Tp, &Tzp); if (stat != 0) printf("Error return from gettimeofday: %d",stat); return(Tp.tv_sec + Tp.tv_usec*1.0e-6); } float absVal(float a) { if(a < 0) return (a * -1); else return a; } float percentDiff(double val1, double val2) { if ((absVal(val1) < 0.01) && (absVal(val2) < 0.01)) return 0.0f; else return 100.0f * (absVal(absVal(val1 - val2) / absVal(val1 + SMALL_FLOAT_VAL))); } /* Command line parameters for benchmark */ struct pb_Parameters { char *outFile; /* If not NULL, the raw output of the * computation should be saved to this * file. The string is owned. */ char **inpFiles; /* A NULL-terminated array of strings * holding the input file(s) for the * computation. The array and strings * are owned. */ }; /* A time or duration. */ #if _POSIX_VERSION >= 200112L typedef unsigned long long pb_Timestamp; /* time in microseconds */ #else # error "Timestamps not implemented" #endif enum pb_TimerState { pb_Timer_STOPPED, pb_Timer_RUNNING, }; struct pb_Timer { enum pb_TimerState state; pb_Timestamp elapsed; /* Amount of time elapsed so far */ pb_Timestamp init; /* Beginning of the current time interval, * if state is RUNNING. End of the last * recorded time interfal otherwise. */ }; /* Execution time is assigned to one of these categories. */ enum pb_TimerID { pb_TimerID_NONE = 0, pb_TimerID_IO, /* Time spent in input/output */ pb_TimerID_KERNEL, /* Time spent computing on the device, * recorded asynchronously */ pb_TimerID_COPY, /* Time spent synchronously moving data * to/from device and allocating/freeing * memory on the device */ pb_TimerID_DRIVER, /* Time spent in the host interacting with the * driver, primarily for recording the time * spent queueing asynchronous operations */ pb_TimerID_COPY_ASYNC, /* Time spent in asynchronous transfers */ pb_TimerID_COMPUTE, /* Time for all program execution other * than parsing command line arguments, * I/O, kernel, and copy */ pb_TimerID_OVERLAP, /* Time double-counted in asynchronous and * host activity: automatically filled in, * not intended for direct usage */ pb_TimerID_LAST /* Number of timer IDs */ }; /* Dynamic list of asynchronously tracked times between events */ struct pb_async_time_marker_list { char *label; // actually just a pointer to a string enum pb_TimerID timerID; /* The ID to which the interval beginning * with this marker should be attributed */ void * marker; //cudaEvent_t marker; /* The driver event for this marker */ struct pb_async_time_marker_list *next; }; struct pb_SubTimer { char *label; struct pb_Timer timer; struct pb_SubTimer *next; }; struct pb_SubTimerList { struct pb_SubTimer *current; struct pb_SubTimer *subtimer_list; }; /* A set of timers for recording execution times. */ struct pb_TimerSet { enum pb_TimerID current; struct pb_async_time_marker_list* async_markers; pb_Timestamp async_begin; pb_Timestamp wall_begin; struct pb_Timer timers[pb_TimerID_LAST]; struct pb_SubTimerList *sub_timer_list[pb_TimerID_LAST]; }; /* Free an array of owned strings. */ static void free_string_array(char **string_array) { char **p; if (!string_array) return; for (p = string_array; *p; p++) free(*p); free(string_array); } /* Parse a comma-delimited list of strings into an * array of strings. */ static char ** read_string_array(char *in) { char **ret; int i; int count; /* Number of items in the input */ char *substring; /* Current substring within 'in' */ /* Count the number of items in the string */ count = 1; for (i = 0; in[i]; i++) if (in[i] == ',') count++; /* Allocate storage */ ret = (char **)malloc((count + 1) * sizeof(char *)); /* Create copies of the strings from the list */ substring = in; for (i = 0; i < count; i++) { char *substring_end; int substring_length; /* Find length of substring */ for (substring_end = substring; (*substring_end != ',') && (*substring_end != 0); substring_end++); substring_length = substring_end - substring; /* Allocate memory and copy the substring */ ret[i] = (char *)malloc(substring_length + 1); memcpy(ret[i], substring, substring_length); ret[i][substring_length] = 0; /* go to next substring */ substring = substring_end + 1; } ret[i] = NULL; /* Write the sentinel value */ return ret; } struct argparse { int argc; /* Number of arguments. Mutable. */ char **argv; /* Argument values. Immutable. */ int argn; /* Current argument number. */ char **argv_get; /* Argument value being read. */ char **argv_put; /* Argument value being written. * argv_put <= argv_get. */ }; static void initialize_argparse(struct argparse *ap, int argc, char **argv) { ap->argc = argc; ap->argn = 0; ap->argv_get = ap->argv_put = ap->argv = argv; } static void finalize_argparse(struct argparse *ap) { /* Move the remaining arguments */ for(; ap->argn < ap->argc; ap->argn++) *ap->argv_put++ = *ap->argv_get++; } /* Delete the current argument. */ static void delete_argument(struct argparse *ap) { if (ap->argn >= ap->argc) { fprintf(stderr, "delete_argument\n"); } ap->argc--; ap->argv_get++; } /* Go to the next argument. Also, move the current argument to its * final location in argv. */ static void next_argument(struct argparse *ap) { if (ap->argn >= ap->argc) { fprintf(stderr, "next_argument\n"); } /* Move argument to its new location. */ *ap->argv_put++ = *ap->argv_get++; ap->argn++; } static int is_end_of_arguments(struct argparse *ap) { return ap->argn == ap->argc; } static char * get_argument(struct argparse *ap) { return *ap->argv_get; } static char * consume_argument(struct argparse *ap) { char *ret = get_argument(ap); delete_argument(ap); return ret; } void pb_FreeParameters(struct pb_Parameters *p) { char **cpp; free(p->outFile); free_string_array(p->inpFiles); free(p); } struct pb_Parameters * pb_ReadParameters(int *_argc, char **argv) { char *err_message; struct argparse ap; struct pb_Parameters *ret = (struct pb_Parameters *)malloc(sizeof(struct pb_Parameters)); /* Initialize the parameters structure */ ret->outFile = NULL; ret->inpFiles = (char **)malloc(sizeof(char *)); ret->inpFiles[0] = NULL; /* Each argument */ initialize_argparse(&ap, *_argc, argv); while(!is_end_of_arguments(&ap)) { char *arg = get_argument(&ap); /* Single-character flag */ if ((arg[0] == '-') && (arg[1] != 0) && (arg[2] == 0)) { delete_argument(&ap); /* This argument is consumed here */ switch(arg[1]) { case 'o': /* Output file name */ if (is_end_of_arguments(&ap)) { err_message = "Expecting file name after '-o'\n"; goto error; } free(ret->outFile); ret->outFile = strdup(consume_argument(&ap)); break; case 'i': /* Input file name */ if (is_end_of_arguments(&ap)) { err_message = "Expecting file name after '-i'\n"; goto error; } ret->inpFiles = read_string_array(consume_argument(&ap)); break; case '-': /* End of options */ goto end_of_options; default: err_message = "Unexpected command-line parameter\n"; goto error; } } else { /* Other parameters are ignored */ next_argument(&ap); } } /* end for each argument */ end_of_options: *_argc = ap.argc; /* Save the modified argc value */ finalize_argparse(&ap); return ret; error: fputs(err_message, stderr); pb_FreeParameters(ret); return NULL; } int pb_Parameters_CountInputs(struct pb_Parameters *p) { int n; for (n = 0; p->inpFiles[n]; n++); return n; } /*****************************************************************************/ /* Timer routines */ static void accumulate_time(pb_Timestamp *accum, pb_Timestamp start, pb_Timestamp end) { #if _POSIX_VERSION >= 200112L *accum += end - start; #else # error "Timestamps not implemented for this system" #endif } #if _POSIX_VERSION >= 200112L static pb_Timestamp get_time() { struct timeval tv; gettimeofday(&tv, NULL); return (pb_Timestamp) (tv.tv_sec * 1000000LL + tv.tv_usec); } #else # error "no supported time libraries are available on this platform" #endif void pb_ResetTimer(struct pb_Timer *timer) { timer->state = pb_Timer_STOPPED; #if _POSIX_VERSION >= 200112L timer->elapsed = 0; #else # error "pb_ResetTimer: not implemented for this system" #endif } void pb_StartTimer(struct pb_Timer *timer) { if (timer->state != pb_Timer_STOPPED) { fputs("Ignoring attempt to start a running timer\n", stderr); return; } timer->state = pb_Timer_RUNNING; #if _POSIX_VERSION >= 200112L { struct timeval tv; gettimeofday(&tv, NULL); timer->init = tv.tv_sec * 1000000LL + tv.tv_usec; } #else # error "pb_StartTimer: not implemented for this system" #endif } void pb_StartTimerAndSubTimer(struct pb_Timer *timer, struct pb_Timer *subtimer) { unsigned int numNotStopped = 0x3; // 11 if (timer->state != pb_Timer_STOPPED) { fputs("Warning: Timer was not stopped\n", stderr); numNotStopped &= 0x1; // Zero out 2^1 } if (subtimer->state != pb_Timer_STOPPED) { fputs("Warning: Subtimer was not stopped\n", stderr); numNotStopped &= 0x2; // Zero out 2^0 } if (numNotStopped == 0x0) { fputs("Ignoring attempt to start running timer and subtimer\n", stderr); return; } timer->state = pb_Timer_RUNNING; subtimer->state = pb_Timer_RUNNING; #if _POSIX_VERSION >= 200112L { struct timeval tv; gettimeofday(&tv, NULL); if (numNotStopped & 0x2) { timer->init = tv.tv_sec * 1000000LL + tv.tv_usec; } if (numNotStopped & 0x1) { subtimer->init = tv.tv_sec * 1000000LL + tv.tv_usec; } } #else # error "pb_StartTimer: not implemented for this system" #endif } void pb_StopTimer(struct pb_Timer *timer) { pb_Timestamp fini; if (timer->state != pb_Timer_RUNNING) { fputs("Ignoring attempt to stop a stopped timer\n", stderr); return; } timer->state = pb_Timer_STOPPED; #if _POSIX_VERSION >= 200112L { struct timeval tv; gettimeofday(&tv, NULL); fini = tv.tv_sec * 1000000LL + tv.tv_usec; } #else # error "pb_StopTimer: not implemented for this system" #endif accumulate_time(&timer->elapsed, timer->init, fini); timer->init = fini; } void pb_StopTimerAndSubTimer(struct pb_Timer *timer, struct pb_Timer *subtimer) { pb_Timestamp fini; unsigned int numNotRunning = 0x3; // 0b11 if (timer->state != pb_Timer_RUNNING) { fputs("Warning: Timer was not running\n", stderr); numNotRunning &= 0x1; // Zero out 2^1 } if (subtimer->state != pb_Timer_RUNNING) { fputs("Warning: Subtimer was not running\n", stderr); numNotRunning &= 0x2; // Zero out 2^0 } if (numNotRunning == 0x0) { fputs("Ignoring attempt to stop stopped timer and subtimer\n", stderr); return; } timer->state = pb_Timer_STOPPED; subtimer->state = pb_Timer_STOPPED; #if _POSIX_VERSION >= 200112L { struct timeval tv; gettimeofday(&tv, NULL); fini = tv.tv_sec * 1000000LL + tv.tv_usec; } #else # error "pb_StopTimer: not implemented for this system" #endif if (numNotRunning & 0x2) { accumulate_time(&timer->elapsed, timer->init, fini); timer->init = fini; } if (numNotRunning & 0x1) { accumulate_time(&subtimer->elapsed, subtimer->init, fini); subtimer->init = fini; } } /* Get the elapsed time in seconds. */ double pb_GetElapsedTime(struct pb_Timer *timer) { double ret; if (timer->state != pb_Timer_STOPPED) { fputs("Elapsed time from a running timer is inaccurate\n", stderr); } #if _POSIX_VERSION >= 200112L ret = timer->elapsed / 1e6; #else # error "pb_GetElapsedTime: not implemented for this system" #endif return ret; } void pb_InitializeTimerSet(struct pb_TimerSet *timers) { int n; timers->wall_begin = get_time(); timers->current = pb_TimerID_NONE; timers->async_markers = NULL; for (n = 0; n < pb_TimerID_LAST; n++) { pb_ResetTimer(&timers->timers[n]); timers->sub_timer_list[n] = NULL; // free first? } } void pb_AddSubTimer(struct pb_TimerSet *timers, char *label, enum pb_TimerID pb_Category) { struct pb_SubTimer *subtimer = (struct pb_SubTimer *) malloc (sizeof(struct pb_SubTimer)); int len = strlen(label); subtimer->label = (char *) malloc (sizeof(char)*(len+1)); sprintf(subtimer->label, "%s\n", label); pb_ResetTimer(&subtimer->timer); subtimer->next = NULL; struct pb_SubTimerList *subtimerlist = timers->sub_timer_list[pb_Category]; if (subtimerlist == NULL) { subtimerlist = (struct pb_SubTimerList *) malloc (sizeof(struct pb_SubTimerList)); subtimerlist->subtimer_list = subtimer; timers->sub_timer_list[pb_Category] = subtimerlist; } else { // Append to list struct pb_SubTimer *element = subtimerlist->subtimer_list; while (element->next != NULL) { element = element->next; } element->next = subtimer; } } void pb_SwitchToSubTimer(struct pb_TimerSet *timers, char *label, enum pb_TimerID category) { // switchToSub( NULL, NONE // switchToSub( NULL, some // switchToSub( some, some // switchToSub( some, NONE -- tries to find "some" in NONE's sublist, which won't be printed struct pb_Timer *topLevelToStop = NULL; if (timers->current != category && timers->current != pb_TimerID_NONE) { // Switching to subtimer in a different category needs to stop the top-level current, different categoried timer. // NONE shouldn't have a timer associated with it, so exclude from branch topLevelToStop = &timers->timers[timers->current]; } struct pb_SubTimerList *subtimerlist = timers->sub_timer_list[timers->current]; struct pb_SubTimer *curr = (subtimerlist == NULL) ? NULL : subtimerlist->current; if (timers->current != pb_TimerID_NONE) { if (curr != NULL && topLevelToStop != NULL) { pb_StopTimerAndSubTimer(topLevelToStop, &curr->timer); } else if (curr != NULL) { pb_StopTimer(&curr->timer); } else { pb_StopTimer(topLevelToStop); } } subtimerlist = timers->sub_timer_list[category]; struct pb_SubTimer *subtimer = NULL; if (label != NULL) { subtimer = subtimerlist->subtimer_list; while (subtimer != NULL) { if (strcmp(subtimer->label, label) == 0) { break; } else { subtimer = subtimer->next; } } } if (category != pb_TimerID_NONE) { if (subtimerlist != NULL) { subtimerlist->current = subtimer; } if (category != timers->current && subtimer != NULL) { pb_StartTimerAndSubTimer(&timers->timers[category], &subtimer->timer); } else if (subtimer != NULL) { // Same category, different non-NULL subtimer pb_StartTimer(&subtimer->timer); } else{ // Different category, but no subtimer (not found or specified as NULL) -- unprefered way of setting topLevel timer pb_StartTimer(&timers->timers[category]); } } timers->current = category; } void pb_SwitchToTimer(struct pb_TimerSet *timers, enum pb_TimerID timer) { /* Stop the currently running timer */ if (timers->current != pb_TimerID_NONE) { struct pb_SubTimer *currSubTimer = NULL; struct pb_SubTimerList *subtimerlist = timers->sub_timer_list[timers->current]; if ( subtimerlist != NULL) { currSubTimer = timers->sub_timer_list[timers->current]->current; } if ( currSubTimer!= NULL) { pb_StopTimerAndSubTimer(&timers->timers[timers->current], &currSubTimer->timer); } else { pb_StopTimer(&timers->timers[timers->current]); } } timers->current = timer; if (timer != pb_TimerID_NONE) { pb_StartTimer(&timers->timers[timer]); } } void pb_PrintTimerSet(struct pb_TimerSet *timers) { pb_Timestamp wall_end = get_time(); struct pb_Timer *t = timers->timers; struct pb_SubTimer* sub = NULL; int maxSubLength; const char *categories[] = { "IO", "Kernel", "Copy", "Driver", "Copy Async", "Compute" }; const int maxCategoryLength = 10; int i; for(i = 1; i < pb_TimerID_LAST-1; ++i) { // exclude NONE and OVRELAP from this format if(pb_GetElapsedTime(&t[i]) != 0) { // Print Category Timer printf("%-*s: %f\n", maxCategoryLength, categories[i-1], pb_GetElapsedTime(&t[i])); if (timers->sub_timer_list[i] != NULL) { sub = timers->sub_timer_list[i]->subtimer_list; maxSubLength = 0; while (sub != NULL) { // Find longest SubTimer label if (strlen(sub->label) > maxSubLength) { maxSubLength = strlen(sub->label); } sub = sub->next; } // Fit to Categories if (maxSubLength <= maxCategoryLength) { maxSubLength = maxCategoryLength; } sub = timers->sub_timer_list[i]->subtimer_list; // Print SubTimers while (sub != NULL) { printf(" -%-*s: %f\n", maxSubLength, sub->label, pb_GetElapsedTime(&sub->timer)); sub = sub->next; } } } } if(pb_GetElapsedTime(&t[pb_TimerID_OVERLAP]) != 0) printf("CPU/Kernel Overlap: %f\n", pb_GetElapsedTime(&t[pb_TimerID_OVERLAP])); float walltime = (wall_end - timers->wall_begin)/ 1e6; printf("Timer Wall Time: %f\n", walltime); } void pb_DestroyTimerSet(struct pb_TimerSet * timers) { /* clean up all of the async event markers */ struct pb_async_time_marker_list ** event = &(timers->async_markers); while( *event != NULL) { struct pb_async_time_marker_list ** next = &((*event)->next); free(*event); (*event) = NULL; event = next; } int i = 0; for(i = 0; i < pb_TimerID_LAST; ++i) { if (timers->sub_timer_list[i] != NULL) { struct pb_SubTimer *subtimer = timers->sub_timer_list[i]->subtimer_list; struct pb_SubTimer *prev = NULL; while (subtimer != NULL) { free(subtimer->label); prev = subtimer; subtimer = subtimer->next; free(prev); } free(timers->sub_timer_list[i]); } } } float *Qr_GPU, *Qi_GPU; /* Q signal (complex) */ float *Qr_CPU, *Qi_CPU; /* Q signal (complex) */ struct kValues { float Kx; float Ky; float Kz; float PhiMag; }; void ComputePhiMagCPU(float* phiR, float* phiI, float* phiMag) { int indexK = 0; for (indexK = 0; indexK < NK; indexK++) { float real = phiR[indexK]; float imag = phiI[indexK]; phiMag[indexK] = real*real + imag*imag; } } void ComputeQGPU(struct kValues *kVals, float* x, float* y, float* z, float *Qr, float *Qi, const int lNK, const int lNX, const double lPIx2) { int indexK, indexX; #pragma omp target device(1) #pragma omp target map(to: kVals[:lNK], x[:lNX], y[:lNX], z[:lNX]) map(tofrom: Qr[:lNX], Qi[:lNX]) #pragma omp parallel for for (indexK = 0; indexK < lNK; indexK++) { for (indexX = 0; indexX < lNX; indexX++) { float expArg = lPIx2 * (kVals[indexK].Kx * x[indexX] + kVals[indexK].Ky * y[indexX] + kVals[indexK].Kz * z[indexX]); float cosArg = cos(expArg); float sinArg = sin(expArg); float phi = kVals[indexK].PhiMag; Qr[indexX] += phi * cosArg; Qi[indexX] += phi * sinArg; } } } void ComputeQCPU(struct kValues *kVals, float* x, float* y, float* z, float *Qr, float *Qi) { int indexK, indexX; for (indexK = 0; indexK < NK; indexK++) { for (indexX = 0; indexX < NX; indexX++) { float expArg = PIx2 * (kVals[indexK].Kx * x[indexX] + kVals[indexK].Ky * y[indexX] + kVals[indexK].Kz * z[indexX]); float cosArg = cos(expArg); float sinArg = sin(expArg); float phi = kVals[indexK].PhiMag; Qr[indexX] += phi * cosArg; Qi[indexX] += phi * sinArg; } } } void createDataStructsCPU(float** phiMag, float** Qr, float** Qi) { *phiMag = (float* ) malloc(NK * sizeof(float)); *Qr = (float*) malloc(NX * sizeof (float)); memset((void *)*Qr, 0, NX * sizeof(float)); *Qi = (float*) malloc(NX * sizeof (float)); memset((void *)*Qi, 0, NX * sizeof(float)); } void inputData(char* fName, int* _numK, int* _numX, float** kx, float** ky, float** kz, float** x, float** y, float** z, float** phiR, float** phiI) { int numK, numX; FILE* fid = fopen(fName, "r"); if (fid == NULL) { fprintf(stderr, "Cannot open input file\n"); exit(-1); } fread (&numK, sizeof (int), 1, fid); *_numK = numK; fread (&numX, sizeof (int), 1, fid); *_numX = numX; *kx = (float *) malloc(numK * sizeof (float)); fread (*kx, sizeof (float), numK, fid); *ky = (float *) malloc(numK * sizeof (float)); fread (*ky, sizeof (float), numK, fid); *kz = (float *) malloc(numK * sizeof (float)); fread (*kz, sizeof (float), numK, fid); *x = (float *) malloc(numX * sizeof (float)); fread (*x, sizeof (float), numX, fid); *y = (float *) malloc(numX * sizeof (float)); fread (*y, sizeof (float), numX, fid); *z = (float *) malloc(numX * sizeof (float)); fread (*z, sizeof (float), numX, fid); *phiR = (float *) malloc(numK * sizeof (float)); fread (*phiR, sizeof (float), numK, fid); *phiI = (float *) malloc(numK * sizeof (float)); fread (*phiI, sizeof (float), numK, fid); fclose (fid); } void compareResults(float *A, float *A_GPU, float *B, float *B_GPU) { int i,fail=0; for (i=0; i < NX; i++) { if (percentDiff(A[i], A_GPU[i]) > ERROR_THRESHOLD) { fail++; } } for (i=0; i < NX; i++) { if (percentDiff(B[i], B_GPU[i]) > ERROR_THRESHOLD) { fail++; } } // print results printf(">>\n Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f%s: %d\n", ERROR_THRESHOLD, "%", fail); } double mriqGPU(int argc, char *argv[]) { int numX, numK; /* Number of X and K values */ int original_numK; /* Number of K values in input file */ float *kx, *ky, *kz; /* K trajectory (3D vectors) */ float *x, *y, *z; /* X coordinates (3D vectors) */ float *phiR, *phiI; /* Phi values (complex) */ float *phiMag; /* Magnitude of Phi */ struct kValues* kVals; struct pb_Parameters *params; /* Read command line */ params = pb_ReadParameters(&argc, argv); if ((params->inpFiles[0] == NULL) || (params->inpFiles[1] != NULL)) { fprintf(stderr, "Expecting one input filename\n"); exit(-1); } /* Read in data */ fprintf(stdout, "<< Reading data ... "); inputData(params->inpFiles[0], &original_numK, &numX, &kx, &ky, &kz, &x, &y, &z, &phiR, &phiI); /* Reduce the number of k-space samples if a number is given * on the command line */ if (argc < 2) numK = original_numK; else { int inputK; char *end; inputK = strtol(argv[1], &end, 10); if (end == argv[1]) { fprintf(stderr, "Expecting an integer parameter\n"); exit(-1); } numK = MIN(inputK, original_numK); } #ifndef __STATIC__ NK = numK; NX = numX; #endif /* Create CPU data structures */ createDataStructsCPU(&phiMag, &Qr_GPU, &Qi_GPU); ComputePhiMagCPU(phiR, phiI, phiMag); kVals = (struct kValues*)calloc(numK, sizeof (struct kValues)); int k; for (k = 0; k < numK; k++) { kVals[k].Kx = kx[k]; kVals[k].Ky = ky[k]; kVals[k].Kz = kz[k]; kVals[k].PhiMag = phiMag[k]; } fprintf(stdout, ">>\n<< Start computation on GPU... "); t_start_GPU = rtclock(); ComputeQGPU(kVals, x, y, z, Qr_GPU, Qi_GPU, NK, NX, PIx2); t_end_GPU = rtclock(); free (kx); free (ky); free (kz); free (x); free (y); free (z); free (phiR); free (phiI); free (phiMag); free (kVals); return t_end_GPU - t_start_GPU; } double mriqCPU(int argc, char *argv[]) { int numX, numK; /* Number of X and K values */ int original_numK; /* Number of K values in input file */ float *kx, *ky, *kz; /* K trajectory (3D vectors) */ float *x, *y, *z; /* X coordinates (3D vectors) */ float *phiR, *phiI; /* Phi values (complex) */ float *phiMag; /* Magnitude of Phi */ struct kValues* kVals; struct pb_Parameters *params; /* Read command line */ params = pb_ReadParameters(&argc, argv); if ((params->inpFiles[0] == NULL) || (params->inpFiles[1] != NULL)) { fprintf(stderr, "Expecting one input filename\n"); exit(-1); } /* Read in data */ inputData(params->inpFiles[0], &original_numK, &numX, &kx, &ky, &kz, &x, &y, &z, &phiR, &phiI); /* Reduce the number of k-space samples if a number is given * on the command line */ if (argc < 2) numK = original_numK; else { int inputK; char *end; inputK = strtol(argv[1], &end, 10); if (end == argv[1]) { fprintf(stderr, "Expecting an integer parameter\n"); exit(-1); } numK = MIN(inputK, original_numK); } #ifndef __STATIC__ NK = numK; NX = numX; #endif /* Create CPU data structures */ createDataStructsCPU(&phiMag, &Qr_CPU, &Qi_CPU); ComputePhiMagCPU(phiR, phiI, phiMag); kVals = (struct kValues*)calloc(numK, sizeof (struct kValues)); int k; for (k = 0; k < numK; k++) { kVals[k].Kx = kx[k]; kVals[k].Ky = ky[k]; kVals[k].Kz = kz[k]; kVals[k].PhiMag = phiMag[k]; } fprintf(stdout, "\n<< Start computation on CPU... "); t_start = rtclock(); ComputeQCPU(kVals, x, y, z, Qr_CPU, Qi_CPU); t_end = rtclock(); free (kx); free (ky); free (kz); free (x); free (y); free (z); free (phiR); free (phiI); free (phiMag); free (kVals); return t_end - t_start; } int main (int argc, char *argv[]) { double t_GPU, t_CPU; fprintf(stdout, "<< Creating the Q data structure for fast convolution-based\n"); fprintf(stdout, " Hessian multiplication for arbitrary k-space trajectories.>>\n"); fprintf(stdout, "<< Elements per Grid: 2048 >>\n\n"); fprintf(stdout, " for (indexK = 0; indexK < 2048; indexK++) \n"); fprintf(stdout, " for (indexX = 0; indexX < 262144; indexX++) { \n"); fprintf(stdout, " float expArg = PIx2 * (kVals[indexK].Kx * x[indexX] +\n"); fprintf(stdout, " kVals[indexK].Ky * y[indexX] + \n"); fprintf(stdout, " kVals[indexK].Kz * z[indexX]);\n"); fprintf(stdout, " float cosArg = cos(expArg);\n"); fprintf(stdout, " float sinArg = sin(expArg);\n"); fprintf(stdout, " float phi = kVals[indexK].PhiMag;\n"); fprintf(stdout, " Qr[indexX] += phi * cosArg;\n"); fprintf(stdout, " Qi[indexX] += phi * sinArg;\n"); fprintf(stdout, " } \n\n"); t_GPU = mriqGPU(argc, argv); fprintf(stdout, ">>\n GPU Runtime: %0.6lfs\n", t_GPU); t_CPU = mriqCPU(argc, argv); fprintf(stdout, ">>\n CPU Runtime: %0.6lfs\n", t_CPU); fprintf(stdout, "\n<< Comparing Results..."); compareResults(Qr_CPU, Qr_GPU, Qi_CPU, Qi_GPU); free(Qr_GPU); free(Qi_GPU); free(Qr_CPU); free(Qi_CPU); return 0; }
test-omp.c
#include<stdio.h> #include<omp.h> int main(void) { #pragma omp parallel { printf("Hello, I'm thread %d\n", omp_get_thread_num()); } }
ompfor-default.c
/* * default loop scheduling */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif int main(void) { int i,j; #pragma omp parallel { #pragma omp single printf ("Using %d threads.\n",omp_get_num_threads()); #pragma omp for private(j) for (i=0;i<10;i++) { j = omp_get_thread_num(); printf("Iteration %d, by thread %d\n", i, j); } } return 0; }
residualbased_elimination_builder_and_solver_with_constraints.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Vicente Mataix Ferrandiz // // #if !defined(KRATOS_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_WITH_CONSTRAINTS) #define KRATOS_RESIDUAL_BASED_ELIMINATION_BUILDER_AND_SOLVER_WITH_CONSTRAINTS /* System includes */ #include <unordered_set> #include <unordered_map> /* External includes */ /* Project includes */ #include "solving_strategies/builder_and_solvers/residualbased_elimination_builder_and_solver.h" #include "utilities/sparse_matrix_multiplication_utility.h" #include "utilities/constraint_utilities.h" #include "input_output/logger.h" #include "utilities/builtin_timer.h" #include "utilities/parallel_utilities.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class ResidualBasedEliminationBuilderAndSolverWithConstraints * @ingroup KratosCore * @brief Current class provides an implementation for standard builder and solving operations. * @details The RHS is constituted by the unbalanced loads (residual) * Degrees of freedom are reordered putting the restrained degrees of freedom at * the end of the system ordered in reverse order with respect to the DofSet. * Imposition of the dirichlet conditions is naturally dealt with as the residual already contains * this information. * Calculation of the reactions involves a cost very similiar to the calculation of the total residual * The system is build in the following manner. A T matrix is assembled and constant vector g is assembled too. The T matrix contains the relations of all the dofs of the system, even the nodes with no master/slave relation. Then the size is n_total x n_red * The relation u = T u_red * Then: * A_red = T^t A T * b_red = T^t (b - A g) * @todo There is a more efficient way to asemble the system, but more costly, which is the following. In this case T will be only a relation matrix between master and slave dofs. Then n_slave x n_master: us = T um + g * Separating into independent dofs, master ans slave dofs: * u = uu * um * us * A = Auu Aum Aus * Amu Amm Ams * Asu Asm Ass * b = bu * bm * bs * Finally: * A_red = Auu Aum + Aus T * Amu + T^t Asu Amm + T^t Ams^t + Ams T + T^t Ass T * b_red = bu - Aus g * bm - Ams g * * This system requires extra care and is more complicated and requires to compute the blocks properly * @author Vicente Mataix Ferrandiz */ template <class TSparseSpace, class TDenseSpace, class TLinearSolver > class ResidualBasedEliminationBuilderAndSolverWithConstraints : public ResidualBasedEliminationBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> { public: ///@name Type Definitions ///@{ /// Pointer definition of ResidualBasedEliminationBuilderAndSolverWithConstraints KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedEliminationBuilderAndSolverWithConstraints); /// Definition of the base class typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BuilderAndSolverBaseType; /// Definition of the base class typedef ResidualBasedEliminationBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; /// The definition of the current class typedef ResidualBasedEliminationBuilderAndSolverWithConstraints<TSparseSpace, TDenseSpace, TLinearSolver> ClassType; // The size_t types typedef std::size_t SizeType; typedef std::size_t IndexType; /// Definition of the classes from the base class typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef typename BaseType::NodeType NodeType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; /// Additional definitions typedef PointerVectorSet<Element, IndexedObject> ElementsContainerType; typedef Element::EquationIdVectorType EquationIdVectorType; typedef Element::DofsVectorType DofsVectorType; typedef boost::numeric::ublas::compressed_matrix<double> CompressedMatrixType; /// DoF types definition typedef typename NodeType::DofType DofType; typedef typename DofType::Pointer DofPointerType; /// Set definition typedef std::unordered_set<IndexType> IndexSetType; /// Map definition typedef std::unordered_map<IndexType, IndexType> IndexMapType; /// MPC definitions typedef MasterSlaveConstraint MasterSlaveConstraintType; typedef typename MasterSlaveConstraint::Pointer MasterSlaveConstraintPointerType; typedef std::vector<IndexType> VectorIndexType; typedef Vector VectorType; ///@} ///@name Enum's ///@{ ///@} ///@name Life Cycle ///@{ /** * @brief Default constructor */ explicit ResidualBasedEliminationBuilderAndSolverWithConstraints() : BaseType() { } /** * @brief Default constructor. (with parameters) */ explicit ResidualBasedEliminationBuilderAndSolverWithConstraints( typename TLinearSolver::Pointer pNewLinearSystemSolver, Parameters ThisParameters ) : BaseType(pNewLinearSystemSolver) { // Validate and assign defaults ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters()); this->AssignSettings(ThisParameters); } /** * @brief Default constructor */ explicit ResidualBasedEliminationBuilderAndSolverWithConstraints( typename TLinearSolver::Pointer pNewLinearSystemSolver, const bool CheckConstraintRelation = true, const bool ResetRelationMatrixEachIteration = false ) : BaseType(pNewLinearSystemSolver), mCheckConstraintRelation(CheckConstraintRelation), mResetRelationMatrixEachIteration(ResetRelationMatrixEachIteration) { } /** Destructor. */ ~ResidualBasedEliminationBuilderAndSolverWithConstraints() override { } /** * @brief Create method * @param pNewLinearSystemSolver The linear solver for the system of equations * @param ThisParameters The configuration parameters */ typename BuilderAndSolverBaseType::Pointer Create( typename TLinearSolver::Pointer pNewLinearSystemSolver, Parameters ThisParameters ) const override { return Kratos::make_shared<ClassType>(pNewLinearSystemSolver,ThisParameters); } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ void SetUpSystem(ModelPart& rModelPart) override { if(rModelPart.MasterSlaveConstraints().size() > 0) SetUpSystemWithConstraints(rModelPart); else BaseType::SetUpSystem(rModelPart); } /** * @brief Function to perform the build of the RHS. The vector could be sized as the total number * of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rb The RHS vector */ void Build( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rb ) override { if(rModelPart.MasterSlaveConstraints().size() > 0) BuildWithConstraints(pScheme, rModelPart, rA, rb); else BaseType::Build(pScheme, rModelPart, rA, rb); } /** * @brief Function to perform the building and solving phase at the same time. * @details It is ideally the fastest and safer function to use when it is possible to solve * just after building * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param A The LHS matrix * @param Dx The Unknowns vector * @param b The RHS vector */ void BuildAndSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) override { if(rModelPart.MasterSlaveConstraints().size() > 0) BuildAndSolveWithConstraints(pScheme, rModelPart, A, Dx, b); else BaseType::BuildAndSolve(pScheme, rModelPart, A, Dx, b); } /** * @brief Function to perform the build of the RHS. * @details The vector could be sized as the total number of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void BuildRHS( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& b) override { KRATOS_TRY if(rModelPart.MasterSlaveConstraints().size() > 0) BuildRHSWithConstraints(pScheme, rModelPart, b); else BaseType::BuildRHS(pScheme, rModelPart, b); KRATOS_CATCH("") } /** * @brief Builds the list of the DofSets involved in the problem by "asking" to each element * and condition its Dofs. * @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the * way the matrix and RHS are built * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void SetUpDofSet( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart ) override { if(rModelPart.MasterSlaveConstraints().size() > 0) SetUpDofSetWithConstraints(pScheme, rModelPart); else BaseType::SetUpDofSet(pScheme, rModelPart); } /** * @brief This method provides the defaults parameters to avoid conflicts between the different constructors * @return The default parameters */ Parameters GetDefaultParameters() const override { Parameters default_parameters = Parameters(R"( { "name" : "elimination_builder_and_solver_with_constraints", "check_constraint_relation" : true, "reset_relation_matrix_each_iteration" : true })"); // Getting base class default parameters const Parameters base_default_parameters = BaseType::GetDefaultParameters(); default_parameters.RecursivelyAddMissingParameters(base_default_parameters); return default_parameters; } /** * @brief Returns the name of the class as used in the settings (snake_case format) * @return The name of the class */ static std::string Name() { return "elimination_builder_and_solver_with_constraints"; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "ResidualBasedEliminationBuilderAndSolverWithConstraints"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << Info(); } /// Print object's data. void PrintData(std::ostream& rOStream) const override { rOStream << Info(); } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ TSystemMatrixPointerType mpTMatrix = NULL; /// This is matrix containing the global relation for the constraints TSystemMatrixPointerType mpOldAMatrix = NULL; /// This is matrix containing the old LHS structure TSystemVectorPointerType mpConstantVector = NULL; /// This is vector containing the rigid movement of the constraint TSystemVectorPointerType mpDeltaConstantVector = NULL; /// This is vector contains the effective constant displacement DofsArrayType mDoFMasterFixedSet; /// The set containing the fixed master DoF of the system DofsArrayType mDoFSlaveSet; /// The set containing the slave DoF of the system SizeType mDoFToSolveSystemSize = 0; /// Number of degrees of freedom of the problem to actually be solved IndexMapType mReactionEquationIdMap; /// In order to know the corresponding EquaionId for each component of the reaction vector bool mCheckConstraintRelation = false; /// If we do a constraint check relation bool mResetRelationMatrixEachIteration = false; /// If we reset the relation matrix at each iteration bool mComputeConstantContribution = false; /// If we compute the constant contribution of the MPC bool mCleared = true; /// If the system has been reseted ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /** * @brief This method assembles the global relation matrix (T matrix used to impose the MPC) * @param rT The global relation matrix * @param rTransformationMatrix The local transformation contribution * @param rSlaveEquationId The equation id of the slave dofs * @param rMasterEquationId The equation id of the master dofs */ void AssembleRelationMatrix( TSystemMatrixType& rT, const LocalSystemMatrixType& rTransformationMatrix, const EquationIdVectorType& rSlaveEquationId, const EquationIdVectorType& rMasterEquationId ) { const SizeType local_size_1 = rTransformationMatrix.size1(); for (IndexType i_local = 0; i_local < local_size_1; ++i_local) { IndexType i_global = rSlaveEquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { BaseType::AssembleRowContributionFreeDofs(rT, rTransformationMatrix, i_global, i_local, rMasterEquationId); } } } /** * @brief This method construcs the relationship between the DoF * @param pScheme The integration scheme * @param rA The LHS of the system * @param rModelPart The model part which defines the problem */ void ConstructMatrixStructure( typename TSchemeType::Pointer pScheme, TSystemMatrixType& rA, ModelPart& rModelPart ) override { if(rModelPart.MasterSlaveConstraints().size() > 0) ConstructMatrixStructureWithConstraints(pScheme, rA, rModelPart); else BaseType::ConstructMatrixStructure(pScheme, rA, rModelPart); } /** * @brief The same methods as the base class but with constraints * @param pScheme The pointer to the integration scheme * @param rModelPart The model part to compute * @param rA The LHS matrix of the system of equations * @param rDx The vector of unkowns * @param rb The RHS vector of the system of equations */ void BuildAndSolveWithConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) { KRATOS_TRY Timer::Start("Build"); // We apply the master/slave relationship before build ApplyMasterSlaveRelation(pScheme, rModelPart, rA, rDx, rb); // We compute the effective constant vector TSystemVectorType dummy_Dx(mDoFToSolveSystemSize); TSparseSpace::SetToZero(dummy_Dx); ComputeEffectiveConstant(pScheme, rModelPart, dummy_Dx); // We do the build (after that we resize the solution vector to avoid problems) BuildWithConstraints(pScheme, rModelPart, rA, rb); Timer::Stop("Build"); // Now we apply the BC rDx.resize(mDoFToSolveSystemSize, false); ApplyDirichletConditions(pScheme, rModelPart, rA, rDx, rb); KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() == 3)) << "Before the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl; // We solve the system of equations const auto timer = BuiltinTimer(); const double start_solve = timer.ElapsedSeconds(); Timer::Start("Solve"); SystemSolveWithPhysics(rA, rDx, rb, rModelPart); Timer::Stop("Solve"); const double stop_solve = timer.ElapsedSeconds(); // We compute the effective constant vector ComputeEffectiveConstant(pScheme, rModelPart, rDx); // We reconstruct the Unknowns vector and the residual const double start_reconstruct_slaves = timer.ElapsedSeconds(); ReconstructSlaveSolutionAfterSolve(pScheme, rModelPart, rA, rDx, rb); const double stop_reconstruct_slaves = timer.ElapsedSeconds(); KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Reconstruct slaves time: " << stop_reconstruct_slaves - start_reconstruct_slaves << std::endl; // Some verbosity KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "System solve time: " << stop_solve - start_solve << std::endl; KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nSystem Matrix = " << rA << "\nUnknowns vector = " << rDx << "\nRHS vector = " << rb << std::endl; KRATOS_CATCH("") } /** * @brief The same methods as the base class but with constraints * @param pScheme The pointer to the integration scheme * @param rModelPart The model part to compute * @param rb The RHS vector of the system of equations */ void BuildRHSWithConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& rb ) { Timer::Start("Build RHS"); // Resetting to zero the vector of reactions if(BaseType::mCalculateReactionsFlag) { TSparseSpace::SetToZero(*(BaseType::mpReactionsVector)); } // Builing without BC BuildRHSNoDirichlet(pScheme,rModelPart,rb); Timer::Stop("Build RHS"); ApplyDirichletConditionsRHS(pScheme, rModelPart, rb); // We get the global T matrix const TSystemMatrixType& rTMatrix = *mpTMatrix; // Reconstruct the RHS TSystemVectorType rb_copy = rb; rb.resize(BaseType::mEquationSystemSize, false); TSparseSpace::Mult(rTMatrix, rb_copy, rb); // Adding contribution to reactions TSystemVectorType& r_reactions_vector = *BaseType::mpReactionsVector; if (BaseType::mCalculateReactionsFlag) { for (auto& r_dof : BaseType::mDofSet) { const bool is_master_fixed = mDoFMasterFixedSet.find(r_dof) == mDoFMasterFixedSet.end() ? false : true; const bool is_slave = mDoFSlaveSet.find(r_dof) == mDoFSlaveSet.end() ? false : true; if (is_master_fixed || is_slave) { // Fixed or MPC dof const IndexType equation_id = r_dof.EquationId(); r_reactions_vector[mReactionEquationIdMap[equation_id]] += rb[equation_id]; } } } // Some verbosity KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", (this->GetEchoLevel() == 3)) << "After the solution of the system" << "\nRHS vector = " << rb << std::endl; } /** * @brief Builds the list of the DofSets involved in the problem by "asking" to each element and condition its Dofs. * @details Equivalent to the ResidualBasedEliminationBuilderAndSolver but with constraints. The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the way the matrix and RHS are built * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve */ void SetUpDofSetWithConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart ) { KRATOS_TRY; KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Setting up the dofs" << std::endl; DofsVectorType dof_list, second_dof_list; // NOTE: The second dof list is only used on constraints to include master/slave relations typedef std::unordered_set < DofPointerType, DofPointerHasher> set_type; // Declaring temporal variables DofsArrayType dof_temp_all, dof_temp_solvable, dof_temp_slave; // We assign an empty dof array to our dof sets BaseType::mDofSet = DofsArrayType(); /// This corresponds with all the DoF of the system mDoFSlaveSet = DofsArrayType(); /// This corresponds with the slave (the ones not solved after compacting the system using MPC) /** * Here we declare three sets. * - The global set: Contains all the DoF of the system * - The slave set: The DoF that are not going to be solved, due to MPC formulation */ set_type dof_global_set, dof_global_slave_set; #pragma omp parallel firstprivate(dof_list, second_dof_list) { const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // We cleate the temporal set and we reserve some space on them set_type dofs_tmp_set, dof_temp_slave_set; dofs_tmp_set.reserve(20000); dof_temp_slave_set.reserve(200); // Gets the array of elements from the modeler ElementsArrayType& r_elements_array = rModelPart.Elements(); const int number_of_elements = static_cast<int>(r_elements_array.size()); #pragma omp for schedule(guided, 512) nowait for (int i = 0; i < number_of_elements; ++i) { auto it_elem = r_elements_array.begin() + i; // Gets list of Dof involved on every element pScheme->GetDofList(*it_elem, dof_list, r_current_process_info); dofs_tmp_set.insert(dof_list.begin(), dof_list.end()); } // Gets the array of conditions from the modeler ConditionsArrayType& r_conditions_array = rModelPart.Conditions(); const int number_of_conditions = static_cast<int>(r_conditions_array.size()); #pragma omp for schedule(guided, 512) nowait for (int i = 0; i < number_of_conditions; ++i) { auto it_cond = r_conditions_array.begin() + i; // Gets list of Dof involved on every element pScheme->GetDofList(*it_cond, dof_list, r_current_process_info); dofs_tmp_set.insert(dof_list.begin(), dof_list.end()); } // Gets the array of constraints from the modeler auto& r_constraints_array = rModelPart.MasterSlaveConstraints(); const int number_of_constraints = static_cast<int>(r_constraints_array.size()); #pragma omp for schedule(guided, 512) nowait for (int i = 0; i < number_of_constraints; ++i) { auto it_const = r_constraints_array.begin() + i; // Gets list of Dof involved on every element it_const->GetDofList(dof_list, second_dof_list, r_current_process_info); dofs_tmp_set.insert(dof_list.begin(), dof_list.end()); dofs_tmp_set.insert(second_dof_list.begin(), second_dof_list.end()); dof_temp_slave_set.insert(dof_list.begin(), dof_list.end()); } // We merge all the sets in one thread #pragma omp critical { dof_global_set.insert(dofs_tmp_set.begin(), dofs_tmp_set.end()); dof_global_slave_set.insert(dof_temp_slave_set.begin(), dof_temp_slave_set.end()); } } KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2)) << "Initializing ordered array filling\n" << std::endl; /// We transfer the temporal sets to our DoF set dof_temp_all.reserve(dof_global_set.size()); for (auto p_dof : dof_global_set) { dof_temp_all.push_back( p_dof ); } dof_temp_all.Sort(); BaseType::mDofSet = dof_temp_all; dof_temp_slave.reserve(dof_global_slave_set.size()); for (auto p_dof : dof_global_slave_set) { dof_temp_slave.push_back( p_dof ); } dof_temp_slave.Sort(); mDoFSlaveSet = dof_temp_slave; // Throws an exception if there are no Degrees Of Freedom involved in the analysis KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl; KRATOS_WARNING_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", mDoFSlaveSet.size() == 0) << "No slave degrees of freedom to solve!" << std::endl; KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2)) << "Number of degrees of freedom:" << BaseType::mDofSet.size() << std::endl; BaseType::mDofSetIsInitialized = true; KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished setting up the dofs" << std::endl; #ifdef USE_LOCKS_IN_ASSEMBLY KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2)) << "Initializing lock array" << std::endl; if (BaseType::mLockArray.size() != 0) { for (int i = 0; i < static_cast<int>(BaseType::mLockArray.size()); ++i) { omp_destroy_lock(&BaseType::mLockArray[i]); } } BaseType::mLockArray.resize(BaseType::mDofSet.size()); for (int i = 0; i < static_cast<int>(BaseType::mLockArray.size()); ++i) { omp_init_lock(&BaseType::mLockArray[i]); } KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", ( this->GetEchoLevel() > 2)) << "End of setup dof set\n" << std::endl; #endif // If reactions are to be calculated, we check if all the dofs have reactions defined // This is tobe done only in debug mode #ifdef KRATOS_DEBUG if(BaseType::GetCalculateReactionsFlag()) { for(auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) { KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " << std::endl << "Node : " << dof_iterator->Id()<< std::endl << "Dof : " << (*dof_iterator) << std::endl << "Not possible to calculate reactions." << std::endl; } } #endif KRATOS_CATCH(""); } /** * @brief This is a call to the linear system solver (taking into account some physical particularities of the problem) * @param rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector * @param rModelPart The model part of the problem to solve */ void SystemSolveWithPhysics( TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb, ModelPart& rModelPart ) { KRATOS_TRY double norm_b = 0.0; if (TSparseSpace::Size(rb) > 0) norm_b = TSparseSpace::TwoNorm(rb); if (norm_b > 0.0) { // Create the auxiliar dof set DofsArrayType aux_dof_set; aux_dof_set.reserve(mDoFToSolveSystemSize); for (auto& r_dof : BaseType::mDofSet) { if (r_dof.EquationId() < BaseType::mEquationSystemSize) { auto it = mDoFSlaveSet.find(r_dof); if (it == mDoFSlaveSet.end()) aux_dof_set.push_back( &r_dof ); } } aux_dof_set.Sort(); KRATOS_ERROR_IF_NOT(aux_dof_set.size() == mDoFToSolveSystemSize) << "Inconsistency (I) in system size: " << mDoFToSolveSystemSize << " vs " << aux_dof_set.size() << "\n Size dof set " << BaseType::mDofSet.size() << " vs Size slave dof set " << mDoFSlaveSet.size() << std::endl; KRATOS_ERROR_IF_NOT(aux_dof_set.size() == rA.size1()) << "Inconsistency (II) in system size: " << rA.size1() << " vs " << aux_dof_set.size() << "\n Size dof set " << BaseType::mDofSet.size() << " vs Size slave dof set " << mDoFSlaveSet.size() << std::endl; // Provide physical data as needed if(BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded()) BaseType::mpLinearSystemSolver->ProvideAdditionalData(rA, rDx, rb, aux_dof_set, rModelPart); // Do solve BaseType::mpLinearSystemSolver->Solve(rA, rDx, rb); } else { TSparseSpace::SetToZero(rDx); KRATOS_WARNING_IF("ResidualBasedEliminationBuilderAndSolver", rModelPart.GetCommunicator().MyPID() == 0) << "ATTENTION! setting the RHS to zero!" << std::endl; } // Prints informations about the current time KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolver", this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0) << *(BaseType::mpLinearSystemSolver) << std::endl; KRATOS_CATCH("") } /** * @brief This function is exactly same as the ConstructMatrixStructure() function in base class except that the function * @details Has the call to ApplyConstraints function call once the element and conditions compute their equation ids * @todo Move this method to a common class with block builder and solver with constraints */ virtual void ConstructMatrixStructureWithConstraints( typename TSchemeType::Pointer pScheme, TSystemMatrixType& rA, ModelPart& rModelPart ) { // Filling with zero the matrix (creating the structure) Timer::Start("MatrixStructure"); // The total number of dof of the system const SizeType equation_size = BaseType::mEquationSystemSize; // This vector contains the indexes sets for all rows std::vector<IndexSetType> indices(equation_size); // We reserve some indexes on each row block_for_each(indices, [](IndexSetType& rIndices){ rIndices.reserve(40); }); /// Definition of the eqautio id vector type EquationIdVectorType ids(3, 0); EquationIdVectorType second_ids(3, 0); // NOTE: Used only on the constraints to take into account the master dofs #pragma omp parallel firstprivate(ids, second_ids) { // The process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // We repeat the same declaration for each thead std::vector<IndexSetType> temp_indexes(equation_size); #pragma omp for for (int index = 0; index < static_cast<int>(equation_size); ++index) temp_indexes[index].reserve(30); // Getting the size of the array of elements from the model const int number_of_elements = static_cast<int>(rModelPart.Elements().size()); // Element initial iterator const auto el_begin = rModelPart.ElementsBegin(); // We iterate over the elements #pragma omp for schedule(guided, 512) nowait for (int i_elem = 0; i_elem<number_of_elements; ++i_elem) { auto it_elem = el_begin + i_elem; pScheme->EquationId(*it_elem, ids, r_current_process_info); for (auto& id_i : ids) { if (id_i < BaseType::mEquationSystemSize) { auto& row_indices = temp_indexes[id_i]; for (auto& id_j : ids) { if (id_j < BaseType::mEquationSystemSize) { row_indices.insert(id_j); } } } } } // Getting the size of the array of the conditions const int number_of_conditions = static_cast<int>(rModelPart.Conditions().size()); // Condition initial iterator const auto cond_begin = rModelPart.ConditionsBegin(); // We iterate over the conditions #pragma omp for schedule(guided, 512) nowait for (int i_cond = 0; i_cond<number_of_conditions; ++i_cond) { auto it_cond = cond_begin + i_cond; pScheme->EquationId(*it_cond, ids, r_current_process_info); for (auto& id_i : ids) { if (id_i < BaseType::mEquationSystemSize) { auto& row_indices = temp_indexes[id_i]; for (auto& id_j : ids) { if (id_j < BaseType::mEquationSystemSize) { row_indices.insert(id_j); } } } } } // Getting the size of the array of the constraints const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size()); // Constraint initial iterator const auto const_begin = rModelPart.MasterSlaveConstraints().begin(); // We iterate over the constraints #pragma omp for schedule(guided, 512) nowait for (int i_const = 0; i_const < number_of_constraints; ++i_const) { auto it_const = const_begin + i_const; // Detect if the constraint is active or not. If the user did not make any choice the constraint // It is active by default bool constraint_is_active = true; if( it_const->IsDefined(ACTIVE) ) { constraint_is_active = it_const->Is(ACTIVE); } if(constraint_is_active) { it_const->EquationIdVector(ids, second_ids, r_current_process_info); // Slave DoFs for (auto& id_i : ids) { if (id_i < BaseType::mEquationSystemSize) { auto& row_indices = temp_indexes[id_i]; for (auto& id_j : ids) { if (id_j < BaseType::mEquationSystemSize) { row_indices.insert(id_j); } } } } // Master DoFs for (auto& id_i : second_ids) { if (id_i < BaseType::mEquationSystemSize) { auto& row_indices = temp_indexes[id_i]; for (auto& id_j : second_ids) { if (id_j < BaseType::mEquationSystemSize) { row_indices.insert(id_j); } } } } } } // Merging all the temporal indexes #pragma omp critical { for (int i = 0; i < static_cast<int>(temp_indexes.size()); ++i) { indices[i].insert(temp_indexes[i].begin(), temp_indexes[i].end()); } } } // Count the row sizes SizeType nnz = 0; for (IndexType i = 0; i < indices.size(); ++i) nnz += indices[i].size(); rA = CompressedMatrixType(indices.size(), indices.size(), nnz); double *Avalues = rA.value_data().begin(); IndexType *Arow_indices = rA.index1_data().begin(); IndexType *Acol_indices = rA.index2_data().begin(); // Filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Arow_indices[0] = 0; for (int i = 0; i < static_cast<int>(rA.size1()); i++) Arow_indices[i + 1] = Arow_indices[i] + indices[i].size(); IndexPartition<std::size_t>(rA.size1()).for_each([&](std::size_t Index){ const IndexType row_begin = Arow_indices[Index]; const IndexType row_end = Arow_indices[Index + 1]; IndexType k = row_begin; for (auto it = indices[Index].begin(); it != indices[Index].end(); ++it) { Acol_indices[k] = *it; Avalues[k] = 0.0; k++; } indices[Index].clear(); //deallocating the memory std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]); }); rA.set_filled(indices.size() + 1, nnz); Timer::Stop("MatrixStructure"); } /** * @brief This function is exactly same as the ConstructMatrixStructure() function in base class except that the function has the call to ApplyConstraints function call once the element and conditions compute their equation slave_ids * @param pScheme The pointer to the integration scheme * @param rT The global relation matrix * @param rModelPart The model part to compute */ virtual void ConstructRelationMatrixStructure( typename TSchemeType::Pointer pScheme, TSystemMatrixType& rT, ModelPart& rModelPart ) { // Filling with zero the matrix (creating the structure) Timer::Start("RelationMatrixStructure"); IndexMapType solvable_dof_reorder; std::unordered_map<IndexType, IndexSetType> master_indices; // Filling with "ones" typedef std::pair<IndexType, IndexType> IndexIndexPairType; typedef std::pair<IndexType, IndexSetType> IndexIndexSetPairType; IndexType counter = 0; for (auto& dof : BaseType::mDofSet) { if (dof.EquationId() < BaseType::mEquationSystemSize) { const IndexType equation_id = dof.EquationId(); auto it = mDoFSlaveSet.find(dof); if (it == mDoFSlaveSet.end()) { solvable_dof_reorder.insert(IndexIndexPairType(equation_id, counter)); master_indices.insert(IndexIndexSetPairType(equation_id, IndexSetType({counter}))); ++counter; } else { master_indices.insert(IndexIndexSetPairType(equation_id, IndexSetType({}))); } } } // The process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); /// Definition of the eqautio id vector type EquationIdVectorType ids(3, 0); EquationIdVectorType second_ids(3, 0); // NOTE: Used only on the constraints to take into account the master dofs const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size()); const auto it_const_begin = rModelPart.MasterSlaveConstraints().begin(); // TODO: OMP for (int i_const = 0; i_const < number_of_constraints; ++i_const) { auto it_const = it_const_begin + i_const; // Detect if the constraint is active or not. If the user did not make any choice the constraint // It is active by default bool constraint_is_active = true; if( it_const->IsDefined(ACTIVE) ) { constraint_is_active = it_const->Is(ACTIVE); } if(constraint_is_active) { it_const->EquationIdVector(ids, second_ids, r_current_process_info); for (auto& slave_id : ids) { if (slave_id < BaseType::mEquationSystemSize) { auto it_slave = solvable_dof_reorder.find(slave_id); if (it_slave == solvable_dof_reorder.end()) { for (auto& master_id : second_ids) { if (master_id < BaseType::mEquationSystemSize) { auto& master_row_indices = master_indices[slave_id]; master_row_indices.insert(solvable_dof_reorder[master_id]); } } } } } } } KRATOS_DEBUG_ERROR_IF_NOT(BaseType::mEquationSystemSize == master_indices.size()) << "Inconsistency in the dofs size: " << BaseType::mEquationSystemSize << "\t vs \t" << master_indices.size() << std::endl; // Count the row sizes SizeType nnz = 0; for (IndexType i = 0; i < BaseType::mEquationSystemSize; ++i) { nnz += master_indices[i].size(); } rT = CompressedMatrixType(BaseType::mEquationSystemSize, mDoFToSolveSystemSize, nnz); double *Tvalues = rT.value_data().begin(); IndexType *Trow_indices = rT.index1_data().begin(); IndexType *Tcol_indices = rT.index2_data().begin(); // Filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP! Trow_indices[0] = 0; for (IndexType i = 0; i < BaseType::mEquationSystemSize; ++i) Trow_indices[i + 1] = Trow_indices[i] + master_indices[i].size(); KRATOS_DEBUG_ERROR_IF_NOT(Trow_indices[BaseType::mEquationSystemSize] == nnz) << "Nonzero values does not coincide with the row index definition: " << Trow_indices[BaseType::mEquationSystemSize] << " vs " << nnz << std::endl; IndexPartition<std::size_t>(rT.size1()).for_each([&](std::size_t Index){ const IndexType row_begin = Trow_indices[Index]; const IndexType row_end = Trow_indices[Index + 1]; IndexType k = row_begin; for (auto it = master_indices[Index].begin(); it != master_indices[Index].end(); ++it) { Tcol_indices[k] = *it; Tvalues[k] = 0.0; k++; } master_indices[Index].clear(); //deallocating the memory std::sort(&Tcol_indices[row_begin], &Tcol_indices[row_end]); }); rT.set_filled(BaseType::mEquationSystemSize + 1, nnz); // Setting ones for (auto& solv_dof : solvable_dof_reorder) { rT(solv_dof.first, solv_dof.second) = 1.0; } Timer::Stop("RelationMatrixStructure"); } /** * @brief This function is exactly same as the Build() function in base class except that the function * @details It has the call to ApplyConstraints function call once the LHS or RHS are computed by elements and conditions * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rb The RHS vector * @param UseBaseBuild If the abse Build function will be used */ void BuildWithConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rb, const bool UseBaseBuild = true ) { KRATOS_TRY // We build the original system if (UseBaseBuild) BaseType::Build(pScheme, rModelPart, rA, rb); else BuildWithoutConstraints(pScheme, rModelPart, rA, rb); // Assemble the constraints const auto timer = BuiltinTimer(); // We get the global T matrix const TSystemMatrixType& rTMatrix = *mpTMatrix; // We compute only once (or if cleared) if (mCleared) { mCleared = false; ComputeConstraintContribution(pScheme, rModelPart, true, mComputeConstantContribution); } else if (mResetRelationMatrixEachIteration) { ResetConstraintSystem(); ComputeConstraintContribution(pScheme, rModelPart, mResetRelationMatrixEachIteration, mComputeConstantContribution); } // We compute the transposed matrix of the global relation matrix TSystemMatrixType T_transpose_matrix(mDoFToSolveSystemSize, BaseType::mEquationSystemSize); SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(T_transpose_matrix, rTMatrix, 1.0); // The proper way to include the constants is in the RHS as T^t(f - A * g) TSystemVectorType rb_copy = rb; if (mComputeConstantContribution) { // We get the g constant vector TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector; TSystemVectorType aux_constant_vector(rDeltaConstantVector); TSparseSpace::Mult(rA, rDeltaConstantVector, aux_constant_vector); TSparseSpace::UnaliasedAdd(rb_copy, -1.0, aux_constant_vector); } // The auxiliar matrix to store the intermediate matrix multiplication TSystemMatrixType auxiliar_A_matrix(mDoFToSolveSystemSize, BaseType::mEquationSystemSize); SparseMatrixMultiplicationUtility::MatrixMultiplication(T_transpose_matrix, rA, auxiliar_A_matrix); // We do a backup of the matrix before apply the constraints if (mpOldAMatrix == NULL) { // If the pointer is not initialized initialize it to an empty matrix TSystemMatrixPointerType pNewOldAMatrix = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); mpOldAMatrix.swap(pNewOldAMatrix); } (*mpOldAMatrix).swap(rA); // We resize of system of equations rA.resize(mDoFToSolveSystemSize, mDoFToSolveSystemSize, false); rb.resize(mDoFToSolveSystemSize, false); // Final multiplication SparseMatrixMultiplicationUtility::MatrixMultiplication(auxiliar_A_matrix, rTMatrix, rA); TSparseSpace::Mult(T_transpose_matrix, rb_copy, rb); // Cleaning up memory auxiliar_A_matrix.resize(0, 0, false); T_transpose_matrix.resize(0, 0, false); KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", this->GetEchoLevel() >= 1) << "Constraint relation build time and multiplication: " << timer.ElapsedSeconds() << std::endl; KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", this->GetEchoLevel() > 2) << "Finished parallel building with constraints" << std::endl; KRATOS_CATCH("") } /** * @brief Function to perform the build of the RHS. * @details The vector could be sized as the total number of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rb The RHS of the system */ void BuildRHSNoDirichlet( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& rb ) { KRATOS_TRY // Assemble the constraints const auto timer = BuiltinTimer(); // We get the global T matrix const TSystemMatrixType& rTMatrix = *mpTMatrix; // We compute only once (or if cleared) if (mCleared) { mCleared = false; ComputeConstraintContribution(pScheme, rModelPart, true, mComputeConstantContribution); } else if (mResetRelationMatrixEachIteration) { ResetConstraintSystem(); ComputeConstraintContribution(pScheme, rModelPart, mResetRelationMatrixEachIteration, mComputeConstantContribution); } // We compute the transposed matrix of the global relation matrix TSystemMatrixType T_transpose_matrix(mDoFToSolveSystemSize, BaseType::mEquationSystemSize); SparseMatrixMultiplicationUtility::TransposeMatrix<TSystemMatrixType, TSystemMatrixType>(T_transpose_matrix, rTMatrix, 1.0); // We build the original system TSystemMatrixType A; // Dummy auxiliar matrix we ned to build anyway because are needed to impose the rigid displacements if (mComputeConstantContribution) { A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false); ConstructMatrixStructure(pScheme, A, rModelPart); BuildWithoutConstraints(pScheme, rModelPart, A, rb); } else { BuildRHSNoDirichletWithoutConstraints(pScheme, rModelPart, rb); } // The proper way to include the constants is in the RHS as T^t(f - A * g) TSystemVectorType rb_copy = rb; if (mComputeConstantContribution) { // We get the g constant vector TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector; TSystemVectorType aux_constant_vector(rDeltaConstantVector); TSparseSpace::Mult(A, rDeltaConstantVector, aux_constant_vector); TSparseSpace::UnaliasedAdd(rb_copy, -1.0, aux_constant_vector); } rb.resize(mDoFToSolveSystemSize, false); // Final multiplication TSparseSpace::Mult(T_transpose_matrix, rb_copy, rb); KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", this->GetEchoLevel() >= 1) << "Constraint relation build time and multiplication: " << timer.ElapsedSeconds() << std::endl; KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", this->GetEchoLevel() > 2) << "Finished parallel building with constraints" << std::endl; KRATOS_CATCH("") } /** * @brief This method resize and initializes the system of euqations * @details Additionally what is done in the base class the constraints are initialized * @param pA The pointer to the LHS matrix * @param pDx The pointer to the vector of Unknowns * @param pb The pointer to the RHS vector * @param rModelPart The model part to be computed */ void ResizeAndInitializeVectors( typename TSchemeType::Pointer pScheme, TSystemMatrixPointerType& pA, TSystemVectorPointerType& pDx, TSystemVectorPointerType& pb, ModelPart& rModelPart ) override { // We resize the basic system BaseType::ResizeAndInitializeVectors(pScheme, pA, pDx, pb, rModelPart); // If needed resize the vector for the calculation of reactions if (BaseType::mCalculateReactionsFlag) { const SizeType reactions_vector_size = BaseType::mDofSet.size() - mDoFToSolveSystemSize + mDoFMasterFixedSet.size(); TSystemVectorType& rReactionsVector = *(BaseType::mpReactionsVector); if (rReactionsVector.size() != reactions_vector_size) rReactionsVector.resize(reactions_vector_size, false); } // Now we resize the relation matrix used on the MPC solution if(rModelPart.MasterSlaveConstraints().size() > 0) { if (mpTMatrix == NULL) { // If the pointer is not initialized initialize it to an empty matrix TSystemMatrixPointerType pNewT = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); mpTMatrix.swap(pNewT); } // The rigid movement if (mpConstantVector == NULL) { // If the pointer is not initialized initialize it to an empty vector TSystemVectorPointerType pNewConstantVector = TSystemVectorPointerType(new TSystemVectorType(0)); mpConstantVector.swap(pNewConstantVector); } // The effective rigid movement if (mpDeltaConstantVector == NULL) { // If the pointer is not initialized initialize it to an empty vector TSystemVectorPointerType pNewConstantVector = TSystemVectorPointerType(new TSystemVectorType(0)); mpDeltaConstantVector.swap(pNewConstantVector); } // System matrices/vectors TSystemMatrixType& rTMatrix = *mpTMatrix; TSystemVectorType& rConstantVector = *mpConstantVector; TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector; // Resizing the system matrix if (rTMatrix.size1() == 0 || BaseType::GetReshapeMatrixFlag() || mCleared) { // If the matrix is not initialized rTMatrix.resize(BaseType::mEquationSystemSize, mDoFToSolveSystemSize, false); ConstructRelationMatrixStructure(pScheme, rTMatrix, rModelPart); } else { if (rTMatrix.size1() != BaseType::mEquationSystemSize || rTMatrix.size2() != mDoFToSolveSystemSize) { KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl; rTMatrix.resize(BaseType::mEquationSystemSize, mDoFToSolveSystemSize, false); ConstructRelationMatrixStructure(pScheme, rTMatrix, rModelPart); } } // Resizing the system vector // The rigid movement if (rConstantVector.size() != BaseType::mEquationSystemSize || BaseType::GetReshapeMatrixFlag() || mCleared) { rConstantVector.resize(BaseType::mEquationSystemSize, false); mComputeConstantContribution = ComputeConstraintContribution(pScheme, rModelPart); } else { if (rConstantVector.size() != BaseType::mEquationSystemSize) { KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl; rConstantVector.resize(BaseType::mEquationSystemSize, false); mComputeConstantContribution = ComputeConstraintContribution(pScheme, rModelPart); } } // The effective rigid movement if (mComputeConstantContribution) { if (rDeltaConstantVector.size() != BaseType::mEquationSystemSize || BaseType::GetReshapeMatrixFlag() || mCleared) { rDeltaConstantVector.resize(BaseType::mEquationSystemSize, false); } else { if (rDeltaConstantVector.size() != BaseType::mEquationSystemSize) { KRATOS_ERROR <<"The equation system size has changed during the simulation. This is not permited."<<std::endl; rDeltaConstantVector.resize(BaseType::mEquationSystemSize, false); } } } } } /** * @brief It computes the reactions of the system * @param pScheme The pointer to the integration scheme * @param rModelPart The model part to compute * @param rA The LHS matrix of the system of equations * @param rDx The vector of unkowns * @param rb The RHS vector of the system of equations */ void CalculateReactions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { KRATOS_TRY // Refresh RHS to have the correct reactions BuildRHS(pScheme, rModelPart, rb); // Adding contribution to reactions TSystemVectorType& r_reactions_vector = *BaseType::mpReactionsVector; // Updating variables for (auto& r_dof : BaseType::mDofSet) { if ((r_dof.IsFixed()) || mDoFSlaveSet.find(r_dof) != mDoFSlaveSet.end()) { r_dof.GetSolutionStepReactionValue() = -r_reactions_vector[mReactionEquationIdMap[r_dof.EquationId()]]; } } KRATOS_CATCH("ResidualBasedEliminationBuilderAndSolverWithConstraints::CalculateReactions failed .."); } /** * @brief Applies the dirichlet conditions. This operation may be very heavy or completely unexpensive depending on the implementation choosen and on how the System Matrix is built. * @details In the base ResidualBasedEliminationBuilderAndSolver does nothing, due to the fact that the BC are automatically managed with the elimination. But in the constrints approach the slave DoF depending on fixed DoFs must be reconstructed * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rDx The Unknowns vector * @param rb The RHS vector */ void ApplyDirichletConditions( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { KRATOS_TRY; if (mDoFMasterFixedSet.size() > 0) { // We apply the same method as in the block builder and solver but instead of fixing the fixed Dofs, we just fix the master fixed Dofs std::vector<double> scaling_factors (mDoFToSolveSystemSize, 0.0); // NOTE: Dofs are assumed to be numbered consecutively const auto it_dof_begin = BaseType::mDofSet.begin(); IndexType counter = 0; for (IndexType i = 0; i < BaseType::mDofSet.size(); ++i) { auto it_dof = it_dof_begin + i; const IndexType equation_id = it_dof->EquationId(); if (equation_id < BaseType::mEquationSystemSize ) { auto it_first_check = mDoFSlaveSet.find(*it_dof); if (it_first_check == mDoFSlaveSet.end()) { auto it_second_check = mDoFSlaveSet.find(*it_dof); if (it_second_check == mDoFSlaveSet.end()) { if(mDoFMasterFixedSet.find(*it_dof) == mDoFMasterFixedSet.end()) { scaling_factors[counter] = 1.0; } } counter += 1; } } } double* Avalues = rA.value_data().begin(); IndexType* Arow_indices = rA.index1_data().begin(); IndexType* Acol_indices = rA.index2_data().begin(); // Detect if there is a line of all zeros and set the diagonal to a 1 if this happens #pragma omp parallel for for(int k = 0; k < static_cast<int>(mDoFToSolveSystemSize); ++k) { const IndexType col_begin = Arow_indices[k]; const IndexType col_end = Arow_indices[k+1]; bool empty = true; for (IndexType j = col_begin; j < col_end; ++j) { if(Avalues[j] != 0.0) { empty = false; break; } } if(empty) { rA(k,k) = 1.0; rb[k] = 0.0; } } IndexPartition<std::size_t>(mDoFToSolveSystemSize).for_each([&](std::size_t Index){ const IndexType col_begin = Arow_indices[Index]; const IndexType col_end = Arow_indices[Index+1]; const double k_factor = scaling_factors[Index]; if (k_factor == 0) { // Zero out the whole row, except the diagonal for (IndexType j = col_begin; j < col_end; ++j) if (Acol_indices[j] != Index ) Avalues[j] = 0.0; // Zero out the RHS rb[Index] = 0.0; } else { // Zero out the column which is associated with the zero'ed row for (IndexType j = col_begin; j < col_end; ++j) { if(scaling_factors[ Acol_indices[j] ] == 0 ) { Avalues[j] = 0.0; } } } }); } KRATOS_CATCH(""); } /** * @brief This function is intended to be called at the end of the solution step to clean up memory storage not needed */ void Clear() override { BaseType::Clear(); // Reseting auxiliar set of dofs mDoFMasterFixedSet = DofsArrayType(); mDoFSlaveSet = DofsArrayType(); // Clearing the relation map mReactionEquationIdMap.clear(); // Clear constraint system if (mpTMatrix != nullptr) TSparseSpace::Clear(mpTMatrix); if (mpConstantVector != nullptr) TSparseSpace::Clear(mpConstantVector); if (mpDeltaConstantVector != nullptr) TSparseSpace::Clear(mpDeltaConstantVector); // Set the flag mCleared = true; KRATOS_INFO_IF("ResidualBasedEliminationBuilderAndSolverWithConstraints", this->GetEchoLevel() > 1) << "Clear Function called" << std::endl; } /** * @brief This method assigns settings to member variables * @param ThisParameters Parameters that are assigned to the member variables */ void AssignSettings(const Parameters ThisParameters) override { BaseType::AssignSettings(ThisParameters); mCheckConstraintRelation = ThisParameters["check_constraint_relation"].GetBool(); mResetRelationMatrixEachIteration = ThisParameters["reset_relation_matrix_each_iteration"].GetBool(); } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ /** * @brief This method computes the equivalent coounter part of the SetUpSystem when using constraints * @param rModelPart The model part of the problem to solve */ void SetUpSystemWithConstraints(ModelPart& rModelPart) { KRATOS_TRY // First we set up the system of equations without constraints // Set equation id for degrees of freedom the free degrees of freedom are positioned at the beginning of the system, while the fixed one are at the end (in opposite order). // // That means that if the EquationId is greater than "mEquationSystemSize" the pointed degree of freedom is restrained // This is almost the same SetUpSystem from ResidualBasedEliminationBuilderAndSolver, but we don't discard from the system the fixed dofs that are part of a constraint at the same time /// First we detect the master fixed DoFs /// // The current process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Vector containing the localization in the system of the different terms DofsVectorType slave_dof_list, master_dof_list; // Declaring temporal variables DofsArrayType dof_temp_fixed_master; typedef std::unordered_set < DofPointerType, DofPointerHasher> set_type; set_type dof_global_fixed_master_set; // Iterate over constraints const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size()); const auto it_const_begin = rModelPart.MasterSlaveConstraints().begin(); #pragma omp parallel firstprivate(slave_dof_list, master_dof_list) { // We cleate the temporal set and we reserve some space on them set_type dof_temp_fixed_master_set; dof_temp_fixed_master_set.reserve(2000); #pragma omp for schedule(guided, 512) nowait for (int i_const = 0; i_const < number_of_constraints; ++i_const) { auto it_const = it_const_begin + i_const; // Detect if the constraint is active or not. If the user did not make any choice the constraint // It is active by default bool constraint_is_active = true; if (it_const->IsDefined(ACTIVE)) constraint_is_active = it_const->Is(ACTIVE); if (constraint_is_active) { it_const->GetDofList(slave_dof_list, master_dof_list, r_current_process_info); // Filling the set of dofs master and fixed at the same time for (auto& master_dof : master_dof_list) { if (master_dof->IsFixed()) { dof_temp_fixed_master_set.insert(master_dof); } } } } // We merge all the sets in one thread #pragma omp critical { dof_global_fixed_master_set.insert(dof_temp_fixed_master_set.begin(), dof_temp_fixed_master_set.end()); } } dof_temp_fixed_master.reserve(dof_global_fixed_master_set.size()); for (auto p_dof : dof_global_fixed_master_set) { dof_temp_fixed_master.push_back( p_dof ); } dof_temp_fixed_master.Sort(); mDoFMasterFixedSet = dof_temp_fixed_master; /// Now we compute as expected /// int free_id = 0; int fix_id = BaseType::mDofSet.size(); for (auto& dof : BaseType::mDofSet) { if (dof.IsFixed()) { auto it = mDoFMasterFixedSet.find(dof); if (it == mDoFMasterFixedSet.end()) { dof.SetEquationId(--fix_id); } else { dof.SetEquationId(free_id++); } } else { dof.SetEquationId(free_id++); } } BaseType::mEquationSystemSize = fix_id; // Add the computation of the global ids of the solvable dofs IndexType counter = 0; for (auto& dof : BaseType::mDofSet) { if (dof.EquationId() < BaseType::mEquationSystemSize) { auto it = mDoFSlaveSet.find(dof); if (it == mDoFSlaveSet.end()) { ++counter; } } } // The total system of equations to be solved mDoFToSolveSystemSize = counter; // Finally we build the relation between the EquationID and the component of the reaction counter = 0; for (auto& r_dof : BaseType::mDofSet) { const bool is_master_fixed = mDoFMasterFixedSet.find(r_dof) == mDoFMasterFixedSet.end() ? false : true; const bool is_slave = mDoFSlaveSet.find(r_dof) == mDoFSlaveSet.end() ? false : true; if (is_master_fixed || is_slave) { // Fixed or MPC dof mReactionEquationIdMap.insert({r_dof.EquationId(), counter}); ++counter; } } KRATOS_CATCH("ResidualBasedEliminationBuilderAndSolverWithConstraints::SetUpSystemWithConstraints failed .."); } /** * @brief This method initializes the DoF using the master/slave relationship * @param pScheme The pointer to the integration scheme * @param rModelPart The model part to compute * @param rA The LHS matrix of the system of equations * @param rDx The vector of unkowns * @param rb The RHS vector of the system of equations */ void ApplyMasterSlaveRelation( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) { KRATOS_TRY // First we reset the slave dofs ConstraintUtilities::ResetSlaveDofs(rModelPart); // Now we apply the constraints ConstraintUtilities::ApplyConstraints(rModelPart); KRATOS_CATCH(""); } /** * @brief This method checks that the master/slave relation is properly set * @param pScheme The pointer to the integration scheme * @param rModelPart The model part to compute * @param rDx The vector of unkowns * @param rDxSolved The vector of unkowns actually solved */ bool CheckMasterSlaveRelation( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& rDx, TSystemVectorType& rDxSolved ) { KRATOS_TRY // Auxiliar values const auto it_dof_begin = BaseType::mDofSet.begin(); TSystemVectorType current_solution(mDoFToSolveSystemSize); TSystemVectorType updated_solution(BaseType::mEquationSystemSize); TSystemVectorType residual_solution(BaseType::mEquationSystemSize); // Get current values IndexType counter = 0; for (IndexType i = 0; i < BaseType::mDofSet.size(); ++i) { auto it_dof = it_dof_begin + i; const IndexType equation_id = it_dof->EquationId(); if (equation_id < BaseType::mEquationSystemSize ) { auto it = mDoFSlaveSet.find(*it_dof); if (it == mDoFSlaveSet.end()) { current_solution[counter] = it_dof->GetSolutionStepValue() + rDxSolved[counter]; counter += 1; } } } block_for_each(BaseType::mDofSet, [&, this](Dof<double>& rDof){ const IndexType equation_id = rDof.EquationId(); if (equation_id < this->mEquationSystemSize ) { residual_solution[equation_id] = rDof.GetSolutionStepValue() + rDx[equation_id]; } }); // Apply master slave constraints const TSystemMatrixType& rTMatrix = *mpTMatrix; TSparseSpace::Mult(rTMatrix, current_solution, updated_solution); if (mComputeConstantContribution) { ComputeConstraintContribution(pScheme, rModelPart, false, true); const TSystemVectorType& rConstantVector = *mpConstantVector; TSparseSpace::UnaliasedAdd(updated_solution, 1.0, rConstantVector); } TSparseSpace::UnaliasedAdd(residual_solution, -1.0, updated_solution); // Check database for(int k = 0; k < static_cast<int>(BaseType::mEquationSystemSize); ++k) { if (std::abs(residual_solution[k]) > std::numeric_limits<double>::epsilon()) return false; } return true; KRATOS_CATCH(""); } /** * @brief This method reconstructs the slave solution after Solving. * @param pScheme The pointer to the integration scheme * @param rModelPart Reference to the ModelPart containing the problem. * @param rA System matrix * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual) */ void ReconstructSlaveSolutionAfterSolve( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) { KRATOS_TRY // We get the global T matrix and the constant vector const TSystemMatrixType& rTMatrix = *mpTMatrix; // We reconstruct the complete vector of Unknowns TSystemVectorType Dx_copy = rDx; rDx.resize(BaseType::mEquationSystemSize); TSparseSpace::Mult(rTMatrix, Dx_copy, rDx); // Add the constant vector if (mComputeConstantContribution) { const TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector; TSparseSpace::UnaliasedAdd(rDx, 1.0, rDeltaConstantVector); } // We check the solution if (mCheckConstraintRelation) { KRATOS_ERROR_IF_NOT(CheckMasterSlaveRelation(pScheme, rModelPart, rDx, Dx_copy)) << "The relation between master/slave dofs is not respected" << std::endl; } // Simply restore old LHS (rA).swap(*mpOldAMatrix); mpOldAMatrix = NULL; // Reconstruct the RHS TSystemVectorType rb_copy = rb; rb.resize(BaseType::mEquationSystemSize, false); TSparseSpace::Mult(rTMatrix, rb_copy, rb); KRATOS_CATCH("ResidualBasedEliminationBuilderAndSolverWithConstraints::ReconstructSlaveSolutionAfterSolve failed .."); } /** * @brief Function to perform the build the system without constraints * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rA The LHS matrix * @param rb The RHS vector */ void BuildWithoutConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemMatrixType& rA, TSystemVectorType& rb ) { // The current process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Getting the array of elements ElementsArrayType& r_elements_array = rModelPart.Elements(); // Getting the array of the conditions ConditionsArrayType& r_conditons_array = rModelPart.Conditions(); // Contributions to the system LocalSystemMatrixType lhs_contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType rhs_contribution = LocalSystemVectorType(0); // Vector containing the localization in the system of the different terms Element::EquationIdVectorType equation_id; // Assemble all elements and conditions #pragma omp parallel firstprivate( lhs_contribution, rhs_contribution, equation_id) { // Elements const auto it_elem_begin = r_elements_array.begin(); const int nelements = static_cast<int>(r_elements_array.size()); #pragma omp for schedule(guided, 512) nowait for (int i = 0; i<nelements; ++i) { auto it_elem = it_elem_begin + i; // Detect if the element is active or not. If the user did not make any choice the element is active by default bool element_is_active = true; if (it_elem->IsDefined(ACTIVE)) element_is_active = it_elem->Is(ACTIVE); if (element_is_active) { // Calculate elemental contribution pScheme->CalculateSystemContributions(*it_elem, lhs_contribution, rhs_contribution, equation_id, r_current_process_info); // Assemble the elemental contribution AssembleWithoutConstraints(rA, rb, lhs_contribution, rhs_contribution, equation_id); } } // Conditions const auto it_cond_begin = r_conditons_array.begin(); const int nconditions = static_cast<int>(r_conditons_array.size()); #pragma omp for schedule(guided, 512) for (int i = 0; i<nconditions; ++i) { auto it_cond = it_cond_begin + i; // Detect if the element is active or not. If the user did not make any choice the element is active by default bool condition_is_active = true; if (it_cond->IsDefined(ACTIVE)) condition_is_active = it_cond->Is(ACTIVE); if (condition_is_active) { // Calculate elemental contribution pScheme->CalculateSystemContributions(*it_cond, lhs_contribution, rhs_contribution, equation_id, r_current_process_info); // Assemble the elemental contribution AssembleWithoutConstraints(rA, rb, lhs_contribution, rhs_contribution, equation_id); } } } } /** * @brief Function to perform the build of the RHS without constraints * @details The vector could be sized as the total number of dofs or as the number of unrestrained ones * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param rb The RHS of the system */ void BuildRHSNoDirichletWithoutConstraints( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& rb ) { // The current process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Getting the array of elements ElementsArrayType& r_elements_array = rModelPart.Elements(); // Getting the array of the conditions ConditionsArrayType& r_conditons_array = rModelPart.Conditions(); // Contributions to the system LocalSystemVectorType rhs_contribution = LocalSystemVectorType(0); // Vector containing the localization in the system of the different terms Element::EquationIdVectorType equation_id; // Assemble all elements and conditions #pragma omp parallel firstprivate( rhs_contribution, equation_id) { // Elements const auto it_elem_begin = r_elements_array.begin(); const int nelements = static_cast<int>(r_elements_array.size()); #pragma omp for schedule(guided, 512) nowait for (int i = 0; i<nelements; ++i) { auto it_elem = it_elem_begin + i; // Detect if the element is active or not. If the user did not make any choice the element is active by default bool element_is_active = true; if (it_elem->IsDefined(ACTIVE)) element_is_active = it_elem->Is(ACTIVE); if (element_is_active) { // Calculate elemental Right Hand Side Contribution pScheme->CalculateRHSContribution(*it_elem, rhs_contribution, equation_id, r_current_process_info); // Assemble the elemental contribution AssembleRHSWithoutConstraints(rb, rhs_contribution, equation_id); } } // Conditions const auto it_cond_begin = r_conditons_array.begin(); const int nconditions = static_cast<int>(r_conditons_array.size()); #pragma omp for schedule(guided, 512) for (int i = 0; i<nconditions; ++i) { auto it_cond = it_cond_begin + i; // Detect if the element is active or not. If the user did not make any choice the element is active by default bool condition_is_active = true; if (it_cond->IsDefined(ACTIVE)) condition_is_active = it_cond->Is(ACTIVE); if (condition_is_active) { // Calculate elemental contribution pScheme->CalculateRHSContribution(*it_cond, rhs_contribution, equation_id, r_current_process_info); // Assemble the elemental contribution AssembleRHSWithoutConstraints(rb, rhs_contribution, equation_id); } } } } /** * @brief This function does the assembling of the LHS and RHS * @note The main difference respect the block builder and solver is the fact that the fixed DoFs are not considered on the assembling */ void AssembleWithoutConstraints( TSystemMatrixType& rA, TSystemVectorType& rb, const LocalSystemMatrixType& rLHSContribution, const LocalSystemVectorType& rRHSContribution, const Element::EquationIdVectorType& rEquationId ) { const SizeType local_size = rLHSContribution.size1(); // Assemble RHS AssembleRHSWithoutConstraints(rb, rRHSContribution, rEquationId); // Assemble LHS for (IndexType i_local = 0; i_local < local_size; ++i_local) { const IndexType i_global = rEquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { BaseType::AssembleRowContributionFreeDofs(rA, rLHSContribution, i_global, i_local, rEquationId); } } } /** * @brief Assembling local contribution of nodes and elements in the RHS * @param rb The RHS vector */ void AssembleRHSWithoutConstraints( TSystemVectorType& rb, const LocalSystemVectorType& rRHSContribution, const Element::EquationIdVectorType& rEquationId ) { const SizeType local_size = rRHSContribution.size(); if (!BaseType::mCalculateReactionsFlag) { for (IndexType i_local = 0; i_local < local_size; ++i_local) { const IndexType i_global = rEquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { // free dof // ASSEMBLING THE SYSTEM VECTOR double& r_b_value = rb[i_global]; const double rhs_value = rRHSContribution[i_local]; AtomicAdd(r_b_value, rhs_value); } } } else { TSystemVectorType& r_reactions_vector = *BaseType::mpReactionsVector; for (IndexType i_local = 0; i_local < local_size; ++i_local) { const IndexType i_global = rEquationId[i_local]; auto it_dof = BaseType::mDofSet.begin() + i_global; const bool is_master_fixed = mDoFMasterFixedSet.find(*it_dof) == mDoFMasterFixedSet.end() ? false : true; const bool is_slave = mDoFSlaveSet.find(*it_dof) == mDoFSlaveSet.end() ? false : true; if (is_master_fixed || is_slave) { // Fixed or MPC dof double& r_b_value = r_reactions_vector[mReactionEquationIdMap[i_global]]; const double rhs_value = rRHSContribution[i_local]; AtomicAdd(r_b_value, rhs_value); } else if (it_dof->IsFree()) { // Free dof not in the MPC // ASSEMBLING THE SYSTEM VECTOR double& r_b_value = rb[i_global]; const double& rhs_value = rRHSContribution[i_local]; AtomicAdd(r_b_value, rhs_value); } } } } /** * @brief This method set to zero the relation matrix */ void ResetConstraintSystem() { TSystemMatrixType& rTMatrix = *mpTMatrix; double *Tvalues = rTMatrix.value_data().begin(); IndexPartition<std::size_t>(rTMatrix.nnz()).for_each([&Tvalues](std::size_t Index){ Tvalues[Index] = 0.0; }); IndexMapType solvable_dof_reorder; // Filling with "ones" typedef std::pair<IndexType, IndexType> IndexIndexPairType; IndexType counter = 0; for (auto& dof : BaseType::mDofSet) { if (dof.EquationId() < BaseType::mEquationSystemSize) { const IndexType equation_id = dof.EquationId(); auto it = mDoFSlaveSet.find(dof); if (it == mDoFSlaveSet.end()) { solvable_dof_reorder.insert(IndexIndexPairType(equation_id, counter)); ++counter; } } } // Setting ones for (auto& solv_dof : solvable_dof_reorder) { rTMatrix(solv_dof.first, solv_dof.second) = 1.0; } if (mComputeConstantContribution) { TSystemVectorType& rConstantVector = *mpConstantVector; TSparseSpace::SetToZero(rConstantVector); } } /** * @brief This method applies the BC, only in the RHS * @param pScheme The pointer to the integration scheme * @param rModelPart The model part to compute * @param rb The RHS vector of the system of equations */ void ApplyDirichletConditionsRHS( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& rb ) { KRATOS_TRY; if (mDoFMasterFixedSet.size() > 0) { // NOTE: dofs are assumed to be numbered consecutively const auto it_dof_begin = BaseType::mDofSet.begin(); IndexPartition<std::size_t>(mDoFToSolveSystemSize).for_each([&, this](std::size_t Index){ auto it_dof = it_dof_begin + Index; if (Index < this->mEquationSystemSize) { auto it = mDoFSlaveSet.find(*it_dof); if (it == mDoFSlaveSet.end()) { if(mDoFMasterFixedSet.find(*it_dof) != mDoFMasterFixedSet.end()) { rb[Index] = 0.0; } } } }); } KRATOS_CATCH(""); } /** * @brief This method computes the absolute constant contribution of the MPC * @param pScheme The integration scheme considered * @param rModelPart The model part of the problem to solve * @param ComputeTranslationMatrix If the translation matrix will be assembled * @param ComputeConstantVector If the constant vector will be assembled * @return If there are constant constraints */ bool ComputeConstraintContribution( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, const bool ComputeTranslationMatrix = false, const bool ComputeConstantVector = false ) { KRATOS_TRY; // We build the global T matrix and the g constant vector TSystemMatrixType& rTMatrix = *mpTMatrix; TSystemVectorType& rConstantVector = *mpConstantVector; // Filling constant vector if (ComputeConstantVector) { IndexPartition<std::size_t>(this->mEquationSystemSize).for_each([&rConstantVector](std::size_t Index){ rConstantVector[Index] = 0.0; }); } // Auxiliar set to reorder master DoFs IndexMapType solvable_dof_reorder; // Filling with "ones" typedef std::pair<IndexType, IndexType> IndexIndexPairType; IndexType counter = 0; for (auto& dof : BaseType::mDofSet) { if (dof.EquationId() < BaseType::mEquationSystemSize) { const IndexType equation_id = dof.EquationId(); auto it = mDoFSlaveSet.find(dof); if (it == mDoFSlaveSet.end()) { solvable_dof_reorder.insert(IndexIndexPairType(equation_id, counter)); ++counter; } } } // The current process info const ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo(); // Initialize the constant vector double aux_constant_value = 0.0; // Contributions to the system LocalSystemMatrixType transformation_matrix = LocalSystemMatrixType(0, 0); LocalSystemVectorType constant_vector = LocalSystemVectorType(0); // Vector containing the localization in the system of the different terms EquationIdVectorType slave_equation_id, master_equation_id; const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size()); std::unordered_set<IndexType> auxiliar_constant_equations_ids; #pragma omp parallel firstprivate(transformation_matrix, constant_vector, slave_equation_id, master_equation_id) { std::unordered_set<IndexType> auxiliar_temp_constant_equations_ids; auxiliar_temp_constant_equations_ids.reserve(2000); #pragma omp for schedule(guided, 512) for (int i_const = 0; i_const < number_of_constraints; ++i_const) { auto it_const = rModelPart.MasterSlaveConstraints().begin() + i_const; // Detect if the constraint is active or not. If the user did not make any choice the constraint // It is active by default bool constraint_is_active = true; if (it_const->IsDefined(ACTIVE)) constraint_is_active = it_const->Is(ACTIVE); if (constraint_is_active) { it_const->CalculateLocalSystem(transformation_matrix, constant_vector, r_current_process_info); it_const->EquationIdVector(slave_equation_id, master_equation_id, r_current_process_info); // Reassign reordered dofs to the master side for (auto& id : master_equation_id) { id = solvable_dof_reorder[id]; } if (ComputeConstantVector) { for (IndexType i = 0; i < slave_equation_id.size(); ++i) { const IndexType i_global = slave_equation_id[i]; if (i_global < BaseType::mEquationSystemSize) { const double constant_value = constant_vector[i]; if (std::abs(constant_value) > 0.0) { auxiliar_temp_constant_equations_ids.insert(i_global); double& r_value = rConstantVector[i_global]; AtomicAdd(r_value, constant_value); } } } } else { for (IndexType i = 0; i < slave_equation_id.size(); ++i) { const IndexType i_global = slave_equation_id[i]; if (i_global < BaseType::mEquationSystemSize) { const double constant_value = constant_vector[i]; AtomicAdd(aux_constant_value, std::abs(constant_value)); } } } if (ComputeTranslationMatrix) { // Assemble the constraint contribution AssembleRelationMatrix(rTMatrix, transformation_matrix, slave_equation_id, master_equation_id); } } } // We merge all the sets in one thread #pragma omp critical { auxiliar_constant_equations_ids.insert(auxiliar_temp_constant_equations_ids.begin(), auxiliar_temp_constant_equations_ids.end()); } } return aux_constant_value > std::numeric_limits<double>::epsilon() ? true : false; KRATOS_CATCH(""); } /** * @brief This method computes the efective constant * @param pScheme The pointer to the integration scheme * @param rModelPart The model part to compute * @param rDxSolved The vector of unkowns actually solved */ void ComputeEffectiveConstant( typename TSchemeType::Pointer pScheme, ModelPart& rModelPart, TSystemVectorType& rDxSolved ) { if (mComputeConstantContribution) { // We get const TSystemMatrixType& rTMatrix = *mpTMatrix; TSystemVectorType& rConstantVector = *mpConstantVector; TSystemVectorType& rDeltaConstantVector = *mpDeltaConstantVector; TSparseSpace::Copy(rConstantVector, rDeltaConstantVector); // We reconstruct the complete vector of Unknowns TSystemVectorType Dx(BaseType::mEquationSystemSize); TSparseSpace::Mult(rTMatrix, rDxSolved, Dx); // Compute the effective constant vector // Auxiliar initial dof iterator const auto it_dof_begin = BaseType::mDofSet.begin(); TSystemVectorType u(BaseType::mEquationSystemSize); block_for_each(BaseType::mDofSet, [&, this](Dof<double>& rDof){ const IndexType equation_id = rDof.EquationId(); if (equation_id < this->mEquationSystemSize ) { u[equation_id] = rDof.GetSolutionStepValue() + Dx[equation_id]; } }); TSystemVectorType u_bar(mDoFToSolveSystemSize); IndexType counter = 0; for (IndexType i = 0; i < BaseType::mDofSet.size(); ++i) { auto it_dof = it_dof_begin + i; const IndexType equation_id = it_dof->EquationId(); if (equation_id < BaseType::mEquationSystemSize ) { auto it = mDoFSlaveSet.find(*it_dof); if (it == mDoFSlaveSet.end()) { u_bar[counter] = it_dof->GetSolutionStepValue() + rDxSolved[counter]; counter += 1; } } } TSystemVectorType u_bar_complete(BaseType::mEquationSystemSize); TSparseSpace::Mult(rTMatrix, u_bar, u_bar_complete); TSparseSpace::UnaliasedAdd(rDeltaConstantVector, 1.0, u_bar_complete); TSparseSpace::UnaliasedAdd(rDeltaConstantVector, -1.0, u); } } ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class ResidualBasedEliminationBuilderAndSolverWithConstraints */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER defined */
Example_udr.2.c
/* * @@name: udr.2.c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success * @@version: omp_4.0 */ #include <stdio.h> #include <limits.h> struct point { int x; int y; }; #pragma omp declare reduction(min : struct point : \ omp_out.x = omp_in.x > omp_out.x ? omp_out.x : omp_in.x, \ omp_out.y = omp_in.y > omp_out.y ? omp_out.y : omp_in.y ) \ initializer( omp_priv = { INT_MAX, INT_MAX } ) #pragma omp declare reduction(max : struct point : \ omp_out.x = omp_in.x < omp_out.x ? omp_out.x : omp_in.x, \ omp_out.y = omp_in.y < omp_out.y ? omp_out.y : omp_in.y ) \ initializer( omp_priv = { 0, 0 } ) void find_enclosing_rectangle ( int n, struct point points[] ) { struct point minp = { INT_MAX, INT_MAX }, maxp = {0,0}; int i; #pragma omp parallel for reduction(min:minp) reduction(max:maxp) for ( i = 0; i < n; i++ ) { if ( points[i].x < minp.x ) minp.x = points[i].x; if ( points[i].y < minp.y ) minp.y = points[i].y; if ( points[i].x > maxp.x ) maxp.x = points[i].x; if ( points[i].y > maxp.y ) maxp.y = points[i].y; } printf("min = (%d, %d)\n", minp.x, minp.y); printf("max = (%d, %d)\n", maxp.x, maxp.y); }
THTensorMath.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "internal/THTensorMath.c" #else #ifndef NAN #define NAN (nan(NULL)) #endif #ifdef _OPENMP #include <omp.h> #endif #define TH_OMP_OVERHEAD_THRESHOLD 100000 #ifdef _OPENMP #ifndef _WIN32 #define PRAGMA(P) _Pragma(#P) #else #ifdef __GNUC__ #define PRAGMA(P) _Pragma(#P) #else #define PRAGMA(P) __pragma(P) //for msvc #endif #endif #define TH_TENSOR_APPLY_CONTIG(TYPE, TENSOR, CODE) \ { \ ptrdiff_t TH_TENSOR_size = THTensor_(nElement)(TENSOR); \ PRAGMA(omp parallel if (TH_TENSOR_size > TH_OMP_OVERHEAD_THRESHOLD)) \ { \ size_t num_threads = omp_get_num_threads(); \ size_t tid = omp_get_thread_num(); \ ptrdiff_t TH_TENSOR_offset = tid * (TH_TENSOR_size / num_threads); \ ptrdiff_t TH_TENSOR_end = tid == num_threads - 1 ? TH_TENSOR_size : \ TH_TENSOR_offset + TH_TENSOR_size / num_threads; \ ptrdiff_t TENSOR##_len = TH_TENSOR_end - TH_TENSOR_offset; \ TYPE *TENSOR##_data = THTensor_(data)(TENSOR) + TH_TENSOR_offset; \ CODE \ } \ } #else #define TH_TENSOR_APPLY_CONTIG(TYPE, TENSOR, CODE) \ { \ TYPE *TENSOR##_data = THTensor_(data)(TENSOR); \ ptrdiff_t TENSOR##_len = THTensor_(nElement)(TENSOR); \ CODE \ } #endif #ifdef _OPENMP #define TH_TENSOR_APPLY2_CONTIG(TYPE1, TENSOR1, TYPE2, TENSOR2, CODE) \ { \ ptrdiff_t TH_TENSOR_size = THTensor_(nElement)(TENSOR1); \ PRAGMA(omp parallel if (TH_TENSOR_size > TH_OMP_OVERHEAD_THRESHOLD)) \ { \ size_t num_threads = omp_get_num_threads(); \ size_t tid = omp_get_thread_num(); \ ptrdiff_t TH_TENSOR_offset = tid * (TH_TENSOR_size / num_threads); \ ptrdiff_t TH_TENSOR_end = tid == num_threads - 1 ? TH_TENSOR_size : \ TH_TENSOR_offset + TH_TENSOR_size / num_threads; \ ptrdiff_t TENSOR1##_len = TH_TENSOR_end - TH_TENSOR_offset; \ TYPE1 *TENSOR1##_data = THTensor_(data)(TENSOR1) + TH_TENSOR_offset; \ TYPE2 *TENSOR2##_data = THTensor_(data)(TENSOR2) + TH_TENSOR_offset; \ CODE \ } \ } #else #define TH_TENSOR_APPLY2_CONTIG(TYPE1, TENSOR1, TYPE2, TENSOR2, CODE) \ { \ TYPE1 *TENSOR1##_data = THTensor_(data)(TENSOR1); \ TYPE2 *TENSOR2##_data = THTensor_(data)(TENSOR2); \ ptrdiff_t TENSOR1##_len = THTensor_(nElement)(TENSOR1); \ CODE \ } #endif #ifdef _OPENMP #define TH_TENSOR_APPLY3_CONTIG(TYPE1, TENSOR1, TYPE2, TENSOR2, TYPE3, TENSOR3, CODE) \ { \ ptrdiff_t TH_TENSOR_size = THTensor_(nElement)(TENSOR1); \ PRAGMA(omp parallel if (TH_TENSOR_size > TH_OMP_OVERHEAD_THRESHOLD)) \ { \ size_t num_threads = omp_get_num_threads(); \ size_t tid = omp_get_thread_num(); \ ptrdiff_t TH_TENSOR_offset = tid * (TH_TENSOR_size / num_threads); \ ptrdiff_t TH_TENSOR_end = tid == num_threads - 1 ? TH_TENSOR_size : \ TH_TENSOR_offset + TH_TENSOR_size / num_threads; \ ptrdiff_t TENSOR1##_len = TH_TENSOR_end - TH_TENSOR_offset; \ TYPE1 *TENSOR1##_data = THTensor_(data)(TENSOR1) + TH_TENSOR_offset; \ TYPE2 *TENSOR2##_data = THTensor_(data)(TENSOR2) + TH_TENSOR_offset; \ TYPE3 *TENSOR3##_data = THTensor_(data)(TENSOR3) + TH_TENSOR_offset; \ CODE \ } \ } #else #define TH_TENSOR_APPLY3_CONTIG(TYPE1, TENSOR1, TYPE2, TENSOR2, TYPE3, TENSOR3, CODE) \ { \ TYPE1 *TENSOR1##_data = THTensor_(data)(TENSOR1); \ TYPE2 *TENSOR2##_data = THTensor_(data)(TENSOR2); \ TYPE3 *TENSOR3##_data = THTensor_(data)(TENSOR3); \ ptrdiff_t TENSOR1##_len = THTensor_(nElement)(TENSOR1); \ CODE \ } #endif void THTensor_(fill)(THTensor *r_, real value) { if (THTensor_(isContiguous)(r_) || THTensor_(isTransposed)(r_)) { TH_TENSOR_APPLY_CONTIG(real, r_, THVector_(fill)(r__data, value, r__len);); } else { TH_TENSOR_APPLY(real, r_, if (r__stride == 1) { THVector_(fill)(r__data, value, r__size); r__i = r__size; r__data += r__stride * r__size; break; } else { *r__data = value; } ); } } void THTensor_(zero)(THTensor *r_) { THTensor_(fill)(r_, 0); } void THTensor_(maskedFill)(THTensor *tensor, THByteTensor *mask, real value) { TH_TENSOR_APPLY2(real, tensor, unsigned char, mask, if (*mask_data > 1) { THFree(mask_counter); THFree(tensor_counter); THError("Mask tensor can take 0 and 1 values only"); } else if (*mask_data == 1) { *tensor_data = value; }); } void THTensor_(maskedCopy)(THTensor *tensor, THByteTensor *mask, THTensor* src ) { THTensor *srct = THTensor_(newContiguous)(src); real *src_data = THTensor_(data)(srct); ptrdiff_t cntr = 0; ptrdiff_t nelem = THTensor_(nElement)(srct); if (THTensor_(nElement)(tensor) != THByteTensor_nElement(mask)) { THTensor_(free)(srct); THError("Number of elements of destination tensor != Number of elements in mask"); } TH_TENSOR_APPLY2(real, tensor, unsigned char, mask, if (*mask_data > 1) { THTensor_(free)(srct); THFree(mask_counter); THFree(tensor_counter); THError("Mask tensor can take 0 and 1 values only"); } else if (*mask_data == 1) { if (cntr == nelem) { THTensor_(free)(srct); THFree(mask_counter); THFree(tensor_counter); THError("Number of elements of src < number of ones in mask"); } *tensor_data = *src_data; src_data++; cntr++; }); THTensor_(free)(srct); } void THTensor_(maskedSelect)(THTensor *tensor, THTensor *src, THByteTensor *mask) { ptrdiff_t numel = THByteTensor_sumall(mask); real *tensor_data; #ifdef DEBUG THAssert(numel <= LONG_MAX); #endif THTensor_(resize1d)(tensor,numel); tensor_data = THTensor_(data)(tensor); TH_TENSOR_APPLY2(real, src, unsigned char, mask, if (*mask_data > 1) { THFree(mask_counter); THFree(src_counter); THError("Mask tensor can take 0 and 1 values only"); } else if (*mask_data == 1) { *tensor_data = *src_data; tensor_data++; }); } // Finds non-zero elements of a tensor and returns their subscripts void THTensor_(nonzero)(THLongTensor *subscript, THTensor *tensor) { ptrdiff_t numel = 0; long *subscript_data; long i = 0; long dim; long div = 1; #ifdef TH_REAL_IS_HALF #define IS_NONZERO(val) ((val.x & 0x7fff) != 0) #else #define IS_NONZERO(val) ((val)!=0) #endif /* First Pass to determine size of subscripts */ TH_TENSOR_APPLY(real, tensor, if IS_NONZERO(*tensor_data) { ++numel; }); #ifdef DEBUG THAssert(numel <= LONG_MAX); #endif THLongTensor_resize2d(subscript, numel, tensor->nDimension); /* Second pass populates subscripts */ subscript_data = THLongTensor_data(subscript); TH_TENSOR_APPLY(real, tensor, if IS_NONZERO(*tensor_data) { div = 1; for (dim = tensor->nDimension - 1; dim >= 0; dim--) { *(subscript_data + dim) = (i/div) % tensor->size[dim]; div *= tensor->size[dim]; } subscript_data += tensor->nDimension; } ++i;); } void THTensor_(indexSelect)(THTensor *tensor, THTensor *src, int dim, THLongTensor *index) { ptrdiff_t i, numel; THLongStorage *newSize; THTensor *tSlice, *sSlice; long *index_data; real *tensor_data, *src_data; THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < src->nDimension, 4,"Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE); THArgCheck(src->nDimension > 0,2,"Source tensor is empty"); numel = THLongTensor_nElement(index); newSize = THLongStorage_newWithSize(src->nDimension); THLongStorage_rawCopy(newSize,src->size); #ifdef DEBUG THAssert(numel <= LONG_MAX); #endif newSize->data[dim] = numel; THTensor_(resize)(tensor,newSize,NULL); THLongStorage_free(newSize); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); if (dim == 0 && THTensor_(isContiguous)(src) && THTensor_(isContiguous)(tensor)) { tensor_data = THTensor_(data)(tensor); src_data = THTensor_(data)(src); ptrdiff_t rowsize = THTensor_(nElement)(src) / src->size[0]; // check that the indices are within range long max = src->size[0] - 1 + TH_INDEX_BASE; for (i=0; i<numel; i++) { if (index_data[i] < TH_INDEX_BASE || index_data[i] > max) { THLongTensor_free(index); THError("index out of range"); } } if (src->nDimension == 1) { #pragma omp parallel for if(numel > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<numel; i++) tensor_data[i] = src_data[index_data[i] - TH_INDEX_BASE]; } else { #pragma omp parallel for if(numel*rowsize > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<numel; i++) memcpy(tensor_data + i*rowsize, src_data + (index_data[i] - TH_INDEX_BASE)*rowsize, rowsize*sizeof(real)); } } else if (src->nDimension == 1) { for (i=0; i<numel; i++) THTensor_(set1d)(tensor,i,THTensor_(get1d)(src,index_data[i] - TH_INDEX_BASE)); } else { for (i=0; i<numel; i++) { tSlice = THTensor_(new)(); sSlice = THTensor_(new)(); THTensor_(select)(tSlice, tensor, dim, i); THTensor_(select)(sSlice, src, dim, index_data[i] - TH_INDEX_BASE); THTensor_(copy)(tSlice, sSlice); THTensor_(free)(tSlice); THTensor_(free)(sSlice); } } THLongTensor_free(index); } void THTensor_(indexCopy)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src) { ptrdiff_t i, numel; THTensor *tSlice, *sSlice; long *index_data; numel = THLongTensor_nElement(index); THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < src->nDimension, 4, "Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE); THArgCheck(numel == src->size[dim],4,"Number of indices should be equal to source:size(dim)"); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); if (tensor->nDimension > 1 ) { tSlice = THTensor_(new)(); sSlice = THTensor_(new)(); for (i=0; i<numel; i++) { THTensor_(select)(tSlice, tensor, dim, index_data[i] - TH_INDEX_BASE); THTensor_(select)(sSlice, src, dim, i); THTensor_(copy)(tSlice, sSlice); } THTensor_(free)(tSlice); THTensor_(free)(sSlice); } else { for (i=0; i<numel; i++) { THTensor_(set1d)(tensor, index_data[i] - TH_INDEX_BASE, THTensor_(get1d)(src,i)); } } THLongTensor_free(index); } void THTensor_(indexAdd)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src) { ptrdiff_t i, numel; THTensor *tSlice, *sSlice; long *index_data; numel = THLongTensor_nElement(index); THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < src->nDimension, 4,"Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE); THArgCheck(numel == src->size[dim],4,"Number of indices should be equal to source:size(dim)"); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); if (tensor->nDimension > 1) { tSlice = THTensor_(new)(); sSlice = THTensor_(new)(); for (i=0; i<numel; i++) { THTensor_(select)(tSlice, tensor, dim, index_data[i] - TH_INDEX_BASE); THTensor_(select)(sSlice, src, dim, i); THTensor_(cadd)(tSlice, tSlice, 1.0, sSlice); } THTensor_(free)(tSlice); THTensor_(free)(sSlice); } else { for (i=0; i<numel; i++) { THTensor_(set1d)(tensor, index_data[i] - TH_INDEX_BASE, THTensor_(get1d)(src,i) + THTensor_(get1d)(tensor,index_data[i] - TH_INDEX_BASE)); } } THLongTensor_free(index); } void THTensor_(indexFill)(THTensor *tensor, int dim, THLongTensor *index, real val) { ptrdiff_t i, numel; THTensor *tSlice; long *index_data; numel = THLongTensor_nElement(index); THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < tensor->nDimension, 4,"Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); for (i=0; i<numel; i++) { if (tensor->nDimension > 1) { tSlice = THTensor_(new)(); THTensor_(select)(tSlice, tensor,dim,index_data[i] - TH_INDEX_BASE); THTensor_(fill)(tSlice, val); THTensor_(free)(tSlice); } else { THTensor_(set1d)(tensor, index_data[i] - TH_INDEX_BASE, val); } } THLongTensor_free(index); } void THTensor_(gather)(THTensor *tensor, THTensor *src, int dim, THLongTensor *index) { long elems_per_row, i, idx; THArgCheck(THTensor_(nDimension)(src) == THTensor_(nDimension)(tensor), 2, "Input tensor must have same dimensions as output tensor"); THArgCheck(dim < THTensor_(nDimension)(tensor), 3, "Index dimension is out of bounds"); THArgCheck(THLongTensor_nDimension(index) == THTensor_(nDimension)(src), 4, "Index tensor must have same dimensions as input tensor"); elems_per_row = THLongTensor_size(index, dim); TH_TENSOR_DIM_APPLY3(real, tensor, real, src, long, index, dim, for (i = 0; i < elems_per_row; ++i) { idx = *(index_data + i*index_stride); if (idx < TH_INDEX_BASE || idx >= src_size + TH_INDEX_BASE) { THFree(TH_TENSOR_DIM_APPLY_counter); THError("Invalid index in gather"); } *(tensor_data + i*tensor_stride) = src_data[(idx - TH_INDEX_BASE) * src_stride]; }) } void THTensor_(scatter)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src) { long elems_per_row, i, idx; THArgCheck(dim < THTensor_(nDimension)(tensor), 2, "Index dimension is out of bounds"); THArgCheck(THLongTensor_nDimension(index) == THTensor_(nDimension)(tensor), 3, "Index tensor must have same dimensions as output tensor"); THArgCheck(THTensor_(nDimension)(src) == THTensor_(nDimension)(tensor), 4, "Input tensor must have same dimensions as output tensor"); elems_per_row = THLongTensor_size(index, dim); TH_TENSOR_DIM_APPLY3(real, tensor, real, src, long, index, dim, for (i = 0; i < elems_per_row; ++i) { idx = *(index_data + i*index_stride); if (idx < TH_INDEX_BASE || idx >= tensor_size + TH_INDEX_BASE) { THFree(TH_TENSOR_DIM_APPLY_counter); THError("Invalid index in scatter"); } tensor_data[(idx - TH_INDEX_BASE) * tensor_stride] = *(src_data + i*src_stride); }) } void THTensor_(scatterAdd)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src) { long elems_per_row, i, idx; THArgCheck(dim < THTensor_(nDimension)(tensor), 2, "Index dimension is out of bounds"); THArgCheck(THLongTensor_nDimension(index) == THTensor_(nDimension)(tensor), 3, "Index tensor must have same dimensions as output tensor"); THArgCheck(THTensor_(nDimension)(src) == THTensor_(nDimension)(tensor), 4, "Input tensor must have same dimensions as output tensor"); elems_per_row = THLongTensor_size(index, dim); TH_TENSOR_DIM_APPLY3(real, tensor, real, src, long, index, dim, for (i = 0; i < elems_per_row; ++i) { idx = *(index_data + i*index_stride); if (idx < TH_INDEX_BASE || idx >= tensor_size + TH_INDEX_BASE) { THFree(TH_TENSOR_DIM_APPLY_counter); THError("Invalid index in scatterAdd"); } tensor_data[(idx - TH_INDEX_BASE) * tensor_stride] += *(src_data + i*src_stride); }) } void THTensor_(scatterFill)(THTensor *tensor, int dim, THLongTensor *index, real val) { long elems_per_row, i, idx; THArgCheck(dim < THTensor_(nDimension)(tensor), 2, "Index dimension is out of bounds"); THArgCheck(THLongTensor_nDimension(index) == THTensor_(nDimension)(tensor), 3, "Index tensor must have same dimensions as output tensor"); elems_per_row = THLongTensor_size(index, dim); TH_TENSOR_DIM_APPLY2(real, tensor, long, index, dim, for (i = 0; i < elems_per_row; ++i) { idx = *(index_data + i*index_stride); if (idx < TH_INDEX_BASE || idx >= tensor_size + TH_INDEX_BASE) { THFree(TH_TENSOR_DIM_APPLY_counter); THError("Invalid index in scatter"); } tensor_data[(idx - TH_INDEX_BASE) * tensor_stride] = val; }) } accreal THTensor_(dot)(THTensor *tensor, THTensor *src) { accreal sum = 0; /* we use a trick here. careful with that. */ TH_TENSOR_APPLY2(real, tensor, real, src, long sz = (tensor_size-tensor_i < src_size-src_i ? tensor_size-tensor_i : src_size-src_i); sum += THBlas_(dot)(sz, src_data, src_stride, tensor_data, tensor_stride); tensor_i += sz; src_i += sz; tensor_data += sz*tensor_stride; src_data += sz*src_stride; break;); return sum; } #undef th_isnan #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) #define th_isnan(val) \ (isnan(val)) #else #define th_isnan(val) (0) #endif #undef th_isnan_break #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) #define th_isnan_break(val) \ if (isnan(val)) break; #else #define th_isnan_break(val) #endif real THTensor_(minall)(THTensor *tensor) { real theMin; real value; THArgCheck(tensor->nDimension > 0, 1, "tensor must have one dimension"); theMin = THTensor_(data)(tensor)[0]; TH_TENSOR_APPLY(real, tensor, value = *tensor_data; /* This is not the same as value<theMin in the case of NaNs */ if(!(value >= theMin)) { theMin = value; th_isnan_break(value) }); return theMin; } real THTensor_(maxall)(THTensor *tensor) { real theMax; real value; THArgCheck(tensor->nDimension > 0, 1, "tensor must have one dimension"); theMax = THTensor_(data)(tensor)[0]; TH_TENSOR_APPLY(real, tensor, value = *tensor_data; /* This is not the same as value>theMax in the case of NaNs */ if(!(value <= theMax)) { theMax = value; th_isnan_break(value) }); return theMax; } static void THTensor_(quickselectnoidx)(real *arr, long k, long elements, long stride); real THTensor_(medianall)(THTensor *tensor) { THArgCheck(tensor->nDimension > 0, 1, "tensor must have one dimension"); real theMedian; ptrdiff_t numel; long k; THTensor *temp_; real *temp__data; numel = THTensor_(nElement)(tensor); k = (numel-1) >> 1; temp_ = THTensor_(newClone)(tensor); temp__data = THTensor_(data)(temp_); THTensor_(quickselectnoidx)(temp__data, k, numel, 1); theMedian = temp__data[k]; THTensor_(free)(temp_); return theMedian; } accreal THTensor_(sumall)(THTensor *tensor) { accreal sum = 0; TH_TENSOR_APPLY(real, tensor, sum += *tensor_data;); return sum; } accreal THTensor_(prodall)(THTensor *tensor) { accreal prod = 1; TH_TENSOR_APPLY(real, tensor, prod *= *tensor_data;); return prod; } void THTensor_(add)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { TH_TENSOR_APPLY2_CONTIG(real, r_, real, t, THVector_(adds)(r__data, t_data, value, r__len);); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data + value;); } } void THTensor_(sub)(THTensor *r_, THTensor *t, real value) { THTensor_(add)(r_, t, -value); } void THTensor_(mul)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { TH_TENSOR_APPLY2_CONTIG(real, r_, real, t, THVector_(muls)(r__data, t_data, value, r__len);); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data * value;); } } void THTensor_(div)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { TH_TENSOR_APPLY2_CONTIG(real, r_, real, t, THVector_(divs)(r__data, t_data, value, r__len);); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data / value;); } } void THTensor_(lshift)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) return THTensor_(mul)(r_, t, powf(2, value)); #elif defined(TH_REAL_IS_DOUBLE) return THTensor_(mul)(r_, t, pow(2, value)); #elif defined(TH_REAL_IS_HALF) return THError("lshift is not supported for torch.HalfTensor"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_BYTE) rp[i] = ((real) tp[i]) << value; #else rp[i] = ((unsigned real) tp[i]) << value; #endif } } else { #if defined(TH_REAL_IS_BYTE) TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((real) *t_data) << value);); #else TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((unsigned real) *t_data) << value);); #endif } #endif } void THTensor_(rshift)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) return THTensor_(div)(r_, t, powf(2, value)); #elif defined(TH_REAL_IS_DOUBLE) return THTensor_(div)(r_, t, pow(2, value)); #elif defined(TH_REAL_IS_HALF) return THError("rshift is not supported for torch.HalfTensor"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_BYTE) rp[i] = ((real) tp[i]) >> value; #else rp[i] = ((unsigned real) tp[i]) >> value; #endif } } else { #if defined(TH_REAL_IS_BYTE) TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((real) *t_data) >> value);); #else TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((unsigned real) *t_data) >> value);); #endif } #endif } void THTensor_(fmod)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) rp[i] = fmod(tp[i], value); #else rp[i] = tp[i] % value; #endif } } else { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY2(real, r_, real, t, *r__data = fmod(*t_data, value);); #else TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (*t_data % value);); #endif } } void THTensor_(remainder)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) rp[i] = (value == 0)? NAN : tp[i] - value * floor(tp[i] / value); #else // There is no NAN for integers rp[i] = tp[i] % value; if (rp[i] * value < 0) rp[i] += value; #endif } } else { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (value == 0)? NAN : *t_data - value * floor(*t_data / value);); #else // There is no NAN for integers TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data % value; if (*r__data * value < 0) *r__data += value;); #endif } } void THTensor_(bitand)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("bitand is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] & value; } } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data & value;); } #endif } void THTensor_(bitor)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("bitor is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] | value; } } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data | value;); } #endif } void THTensor_(bitxor)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("bitxor is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] ^ value; } } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data ^ value;); } #endif } void THTensor_(clamp)(THTensor *r_, THTensor *t, real min_value, real max_value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); /* real t_val; */ ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = (tp[i] < min_value) ? min_value : (tp[i] > max_value ? max_value : tp[i]); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (*t_data < min_value) ? min_value : (*t_data > max_value ? max_value : *t_data);); } } void THTensor_(cadd)(THTensor *r_, THTensor *t, real value, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { if(r_ == t) { THBlas_(axpy)(THTensor_(nElement)(t), value, THTensor_(data)(src), 1, THTensor_(data)(r_), 1); } else { TH_TENSOR_APPLY3_CONTIG(real, r_, real, t, real, src, THVector_(cadd)(r__data, t_data, src_data, value, r__len);); } } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data + value * *src_data;); } } void THTensor_(csub)(THTensor *r_, THTensor *t, real value,THTensor *src) { THTensor_(cadd)(r_, t, -value, src); } void THTensor_(cmul)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { TH_TENSOR_APPLY3_CONTIG(real, r_, real, t, real, src, THVector_(cmul)(r__data, t_data, src_data, r__len);); } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data * *src_data;); } } void THTensor_(cpow)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = pow(tp[i], sp[i]); } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = pow(*t_data, *src_data);); } } void THTensor_(cdiv)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { TH_TENSOR_APPLY3_CONTIG(real, r_, real, t, real, src, THVector_(cdiv)(r__data, t_data, src_data, r__len);); } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data / *src_data;); } } void THTensor_(clshift)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_HALF) return THError("clshift is not supported for torch.HalfTensor"); #endif THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) rp[i] = tp[i] * powf(2, sp[i]); #elif defined(TH_REAL_IS_DOUBLE) rp[i] = tp[i] * pow(2, sp[i]); #elif defined(TH_REAL_IS_BYTE) rp[i] = ((real) tp[i]) << sp[i]; #else rp[i] = ((unsigned real) tp[i]) << sp[i]; #endif } } else { #if defined(TH_REAL_IS_FLOAT) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data * powf(2, *src_data);); #elif defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data * pow(2, *src_data);); #elif defined(TH_REAL_IS_BYTE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = ((real)*t_data) << *src_data;); #else TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = ((unsigned real)*t_data) << *src_data;); #endif } } void THTensor_(crshift)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_HALF) return THError("crshift is not supported for torch.HalfTensor"); #endif THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) rp[i] = tp[i] / powf(2, sp[i]); #elif defined(TH_REAL_IS_DOUBLE) rp[i] = tp[i] / pow(2, sp[i]); #elif defined(TH_REAL_IS_BYTE) rp[i] = ((real) tp[i]) >> sp[i]; #else rp[i] = ((unsigned real) tp[i]) >> sp[i]; #endif } } else { #if defined(TH_REAL_IS_FLOAT) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data / powf(2, *src_data);); #elif defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data / pow(2, *src_data);); #elif defined(TH_REAL_IS_BYTE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = ((real)*t_data) >> *src_data;); #else TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = ((unsigned real)*t_data) >> *src_data;); #endif } } void THTensor_(cfmod)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) rp[i] = fmod(tp[i], sp[i]); #else rp[i] = tp[i] % sp[i]; #endif } } else { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = fmod(*t_data, *src_data);); #else TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = (*t_data % *src_data);); #endif } } void THTensor_(cremainder)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) rp[i] = (sp[i] == 0)? NAN : tp[i] - sp[i] * floor(tp[i] / sp[i]); #else // There is no NAN for integers rp[i] = tp[i] % sp[i]; if (rp[i] * sp[i] < 0) rp[i] += sp[i]; #endif } } else { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = (*src_data == 0)? NAN : *t_data - *src_data * floor(*t_data / *src_data);); #else // There is no NAN for integers TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data % *src_data; if (*r__data * *src_data < 0) *r__data += *src_data;); #endif } } void THTensor_(cbitand)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("cbitand is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] & sp[i]; } } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data & *src_data;); } #endif } void THTensor_(cbitor)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("cbitor is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] | sp[i]; } } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data | *src_data;); } #endif } void THTensor_(cbitxor)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("cbitxor is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] ^ sp[i]; } } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data ^ *src_data;); } #endif } void THTensor_(tpow)(THTensor *r_, real value, THTensor *t) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = pow(value, tp[i]); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = pow(value, *t_data);); } } void THTensor_(addcmul)(THTensor *r_, THTensor *t, real value, THTensor *src1, THTensor *src2) { if(r_ != t) { THTensor_(resizeAs)(r_, t); THTensor_(copy)(r_, t); } TH_TENSOR_APPLY3(real, r_, real, src1, real, src2, *r__data += value * *src1_data * *src2_data;); } void THTensor_(addcdiv)(THTensor *r_, THTensor *t, real value, THTensor *src1, THTensor *src2) { if(r_ != t) { THTensor_(resizeAs)(r_, t); THTensor_(copy)(r_, t); } TH_TENSOR_APPLY3(real, r_, real, src1, real, src2, *r__data += value * *src1_data / *src2_data;); } void THTensor_(addmv)(THTensor *r_, real beta, THTensor *t, real alpha, THTensor *mat, THTensor *vec) { if( (mat->nDimension != 2) || (vec->nDimension != 1) ) THError("matrix and vector expected, got %dD, %dD", mat->nDimension, vec->nDimension); if( mat->size[1] != vec->size[0] ) { THDescBuff bm = THTensor_(sizeDesc)(mat); THDescBuff bv = THTensor_(sizeDesc)(vec); THError("size mismatch, %s, %s", bm.str, bv.str); } if(t->nDimension != 1) THError("vector expected, got t: %dD", t->nDimension); if(t->size[0] != mat->size[0]) { THDescBuff bt = THTensor_(sizeDesc)(t); THDescBuff bm = THTensor_(sizeDesc)(mat); THError("size mismatch, t: %s, mat: %s", bt.str, bm.str); } if(r_ != t) { THTensor_(resizeAs)(r_, t); THTensor_(copy)(r_, t); } if(mat->stride[0] == 1) { THBlas_(gemv)('n', mat->size[0], mat->size[1], alpha, THTensor_(data)(mat), mat->stride[1], THTensor_(data)(vec), vec->stride[0], beta, THTensor_(data)(r_), r_->stride[0]); } else if(mat->stride[1] == 1) { THBlas_(gemv)('t', mat->size[1], mat->size[0], alpha, THTensor_(data)(mat), mat->stride[0], THTensor_(data)(vec), vec->stride[0], beta, THTensor_(data)(r_), r_->stride[0]); } else { THTensor *cmat = THTensor_(newContiguous)(mat); THBlas_(gemv)('t', mat->size[1], mat->size[0], alpha, THTensor_(data)(cmat), cmat->stride[0], THTensor_(data)(vec), vec->stride[0], beta, THTensor_(data)(r_), r_->stride[0]); THTensor_(free)(cmat); } } void THTensor_(match)(THTensor *r_, THTensor *m1, THTensor *m2, real gain) { long N1 = m1->size[0]; long N2 = m2->size[0]; long dim; real *m1_p; real *m2_p; real *r_p; long i; THTensor_(resize2d)(r_, N1, N2); m1 = THTensor_(newContiguous)(m1); m2 = THTensor_(newContiguous)(m2); THTensor_(resize2d)(m1, N1, THTensor_(nElement)(m1) / N1); THTensor_(resize2d)(m2, N2, THTensor_(nElement)(m2) / N2); dim = m1->size[1]; THArgCheck(m1->size[1] == m2->size[1], 3, "m1 and m2 must have the same inner vector dim"); m1_p = THTensor_(data)(m1); m2_p = THTensor_(data)(m2); r_p = THTensor_(data)(r_); #pragma omp parallel for private(i) for (i=0; i<N1; i++) { long j,k; for (j=0; j<N2; j++) { real sum = 0; for (k=0; k<dim; k++) { real term = m1_p[ i*dim + k ] - m2_p[ j*dim + k ]; sum += term*term; } r_p[ i*N2 + j ] = gain * sum; } } THTensor_(free)(m1); THTensor_(free)(m2); } void THTensor_(addmm)(THTensor *r_, real beta, THTensor *t, real alpha, THTensor *m1, THTensor *m2) { char transpose_r, transpose_m1, transpose_m2; THTensor *r__, *m1_, *m2_; if( (m1->nDimension != 2) || (m2->nDimension != 2)) THError("matrices expected, got %dD, %dD tensors", m1->nDimension, m2->nDimension); if(m1->size[1] != m2->size[0]) { THDescBuff bm1 = THTensor_(sizeDesc)(m1); THDescBuff bm2 = THTensor_(sizeDesc)(m2); THError("size mismatch, m1: %s, m2: %s", bm1.str, bm2.str); } if( t->nDimension != 2 ) THError("matrix expected, got %dD tensor for t", t->nDimension); if( (t->size[0] != m1->size[0]) || (t->size[1] != m2->size[1]) ) { THDescBuff bt = THTensor_(sizeDesc)(t); THDescBuff bm1 = THTensor_(sizeDesc)(m1); THDescBuff bm2 = THTensor_(sizeDesc)(m2); THError("size mismatch, t: %s, m1: %s, m2: %s", bt.str, bm1.str, bm2.str); } if(t != r_) { THTensor_(resizeAs)(r_, t); if (beta != 0.0) { THTensor_(copy)(r_, t); } } /* r_ */ if(r_->stride[0] == 1 && r_->stride[1] != 0) { transpose_r = 'n'; r__ = r_; } else if(r_->stride[1] == 1 && r_->stride[0] != 0) { THTensor *swap = m2; m2 = m1; m1 = swap; transpose_r = 't'; r__ = r_; } else { transpose_r = 'n'; THTensor *transp_r_ = THTensor_(newTranspose)(r_, 0, 1); r__ = THTensor_(newClone)(transp_r_); THTensor_(free)(transp_r_); THTensor_(transpose)(r__, NULL, 0, 1); } /* m1 */ if(m1->stride[(transpose_r == 'n' ? 0 : 1)] == 1 && m1->stride[(transpose_r == 'n' ? 1 : 0)] != 0) { transpose_m1 = 'n'; m1_ = m1; } else if(m1->stride[(transpose_r == 'n' ? 1 : 0)] == 1 && m1->stride[(transpose_r == 'n' ? 0 : 1)] != 0) { transpose_m1 = 't'; m1_ = m1; } else { transpose_m1 = (transpose_r == 'n' ? 't' : 'n'); m1_ = THTensor_(newContiguous)(m1); } /* m2 */ if(m2->stride[(transpose_r == 'n' ? 0 : 1)] == 1 && m2->stride[(transpose_r == 'n' ? 1 : 0)] != 0) { transpose_m2 = 'n'; m2_ = m2; } else if(m2->stride[(transpose_r == 'n' ? 1 : 0)] == 1 && m2->stride[(transpose_r == 'n' ? 0 : 1)] != 0) { transpose_m2 = 't'; m2_ = m2; } else { transpose_m2 = (transpose_r == 'n' ? 't' : 'n'); m2_ = THTensor_(newContiguous)(m2); } #pragma omp critical(blasgemm) /* do the operation */ THBlas_(gemm)(transpose_m1, transpose_m2, r__->size[(transpose_r == 'n' ? 0 : 1)], r__->size[(transpose_r == 'n' ? 1 : 0)], m1_->size[(transpose_r == 'n' ? 1 : 0)], alpha, THTensor_(data)(m1_), (transpose_m1 == 'n' ? m1_->stride[(transpose_r == 'n' ? 1 : 0)] : m1_->stride[(transpose_r == 'n' ? 0 : 1)]), THTensor_(data)(m2_), (transpose_m2 == 'n' ? m2_->stride[(transpose_r == 'n' ? 1 : 0)] : m2_->stride[(transpose_r == 'n' ? 0 : 1)]), beta, THTensor_(data)(r__), r__->stride[(transpose_r == 'n' ? 1 : 0)]); /* free intermediate variables */ if(m1_ != m1) THTensor_(free)(m1_); if(m2_ != m2) THTensor_(free)(m2_); if(r__ != r_) THTensor_(freeCopyTo)(r__, r_); } void THTensor_(addr)(THTensor *r_, real beta, THTensor *t, real alpha, THTensor *vec1, THTensor *vec2) { if( (vec1->nDimension != 1) || (vec2->nDimension != 1) ) THError("vector and vector expected, got %dD, %dD tensors", vec1->nDimension, vec2->nDimension); if(t->nDimension != 2) THError("expected matrix, got %dD tensor for t", t->nDimension); if( (t->size[0] != vec1->size[0]) || (t->size[1] != vec2->size[0]) ) { THDescBuff bt = THTensor_(sizeDesc)(t); THDescBuff bv1 = THTensor_(sizeDesc)(vec1); THDescBuff bv2 = THTensor_(sizeDesc)(vec2); THError("size mismatch, t: %s, vec1: %s, vec2: %s", bt.str, bv1.str, bv2.str); } if(r_ != t) { THTensor_(resizeAs)(r_, t); THTensor_(copy)(r_, t); } if(beta == 0) { THTensor_(zero)(r_); } else if(beta != 1) THTensor_(mul)(r_, r_, beta); if(r_->stride[0] == 1) { THBlas_(ger)(vec1->size[0], vec2->size[0], alpha, THTensor_(data)(vec1), vec1->stride[0], THTensor_(data)(vec2), vec2->stride[0], THTensor_(data)(r_), r_->stride[1]); } else if(r_->stride[1] == 1) { THBlas_(ger)(vec2->size[0], vec1->size[0], alpha, THTensor_(data)(vec2), vec2->stride[0], THTensor_(data)(vec1), vec1->stride[0], THTensor_(data)(r_), r_->stride[0]); } else { THTensor *cr = THTensor_(newClone)(r_); THBlas_(ger)(vec2->size[0], vec1->size[0], alpha, THTensor_(data)(vec2), vec2->stride[0], THTensor_(data)(vec1), vec1->stride[0], THTensor_(data)(cr), cr->stride[0]); THTensor_(freeCopyTo)(cr, r_); } } void THTensor_(addbmm)(THTensor *result, real beta, THTensor *t, real alpha, THTensor *batch1, THTensor *batch2) { long batch; THArgCheck(THTensor_(nDimension)(batch1) == 3, 1, "expected 3D tensor"); THArgCheck(THTensor_(nDimension)(batch2) == 3, 2, "expected 3D tensor"); THArgCheck(THTensor_(size)(batch1, 0) == THTensor_(size)(batch2, 0), 2, "equal number of batches expected, got %d, %d", THTensor_(size)(batch1, 0), THTensor_(size)(batch2, 0)); THArgCheck(THTensor_(size)(batch1, 2) == THTensor_(size)(batch2, 1), 2, "wrong matrix size, batch1: %dx%d, batch2: %dx%d", THTensor_(size)(batch1, 1), THTensor_(size)(batch1,2), THTensor_(size)(batch2, 1), THTensor_(size)(batch2,2)); long dim1 = THTensor_(size)(batch1, 1); long dim2 = THTensor_(size)(batch2, 2); THArgCheck(THTensor_(size)(t, 0) == dim1, 1, "output tensor of incorrect size"); THArgCheck(THTensor_(size)(t, 1) == dim2, 1, "output tensor of incorrect size"); if (t != result) { THTensor_(resizeAs)(result, t); if (beta != 0.0) { THTensor_(copy)(result, t); } } THTensor *matrix1 = THTensor_(new)(); THTensor *matrix2 = THTensor_(new)(); for (batch = 0; batch < THTensor_(size)(batch1, 0); ++batch) { THTensor_(select)(matrix1, batch1, 0, batch); THTensor_(select)(matrix2, batch2, 0, batch); THTensor_(addmm)(result, beta, result, alpha, matrix1, matrix2); beta = 1; // accumulate output once } THTensor_(free)(matrix1); THTensor_(free)(matrix2); } void THTensor_(baddbmm)(THTensor *result, real beta, THTensor *t, real alpha, THTensor *batch1, THTensor *batch2) { long batch; THArgCheck(THTensor_(nDimension)(batch1) == 3, 1, "expected 3D tensor, got %dD", THTensor_(nDimension)(batch1)); THArgCheck(THTensor_(nDimension)(batch2) == 3, 2, "expected 3D tensor, got %dD", THTensor_(nDimension)(batch2)); THArgCheck(THTensor_(size)(batch1, 0) == THTensor_(size)(batch2, 0), 2, "equal number of batches expected, got %d, %d", THTensor_(size)(batch1, 0), THTensor_(size)(batch2, 0)); THArgCheck(THTensor_(size)(batch1, 2) == THTensor_(size)(batch2, 1), 2, "wrong matrix size, batch1: %dx%d, batch2: %dx%d", THTensor_(size)(batch1, 1), THTensor_(size)(batch1, 2), THTensor_(size)(batch2, 1), THTensor_(size)(batch2, 2)); long bs = THTensor_(size)(batch1, 0); long dim1 = THTensor_(size)(batch1, 1); long dim2 = THTensor_(size)(batch2, 2); THArgCheck(THTensor_(size)(t, 0) == bs, 1, "output tensor of incorrect size"); THArgCheck(THTensor_(size)(t, 1) == dim1, 1, "output tensor of incorrect size"); THArgCheck(THTensor_(size)(t, 2) == dim2, 1, "output tensor of incorrect size"); if (t != result) { THTensor_(resizeAs)(result, t); if (beta != 0.0) { THTensor_(copy)(result, t); } } THTensor *matrix1 = THTensor_(new)(); THTensor *matrix2 = THTensor_(new)(); THTensor *result_matrix = THTensor_(new)(); for (batch = 0; batch < THTensor_(size)(batch1, 0); ++batch) { THTensor_(select)(matrix1, batch1, 0, batch); THTensor_(select)(matrix2, batch2, 0, batch); THTensor_(select)(result_matrix, result, 0, batch); THTensor_(addmm)(result_matrix, beta, result_matrix, alpha, matrix1, matrix2); } THTensor_(free)(matrix1); THTensor_(free)(matrix2); THTensor_(free)(result_matrix); } ptrdiff_t THTensor_(numel)(THTensor *t) { return THTensor_(nElement)(t); } void THTensor_(max)(THTensor *values_, THLongTensor *indices_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); // two implementations optimized for data locality if (t->stride[dimension] == 1) { real theMax; real value; long theIndex; long i; TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, theMax = t_data[0]; theIndex = 0; for(i = 0; i < t_size; i++) { value = t_data[i*t_stride]; /* This is not the same as value>theMax in the case of NaNs */ if(!(value <= theMax)) { theIndex = i; theMax = value; th_isnan_break(value) } } *indices__data = theIndex; *values__data = theMax;); } else { if (THTensor_(nDimension)(t) > 1) { THTensor *t0 = THTensor_(newSelect)(t, dimension, 0); THTensor_(copy)(values_, t0); THTensor_(free)(t0); } else { THTensor_(fill)(values_, THTensor_(get1d)(t, 0)); } THLongTensor_zero(indices_); if(t->size[dimension] == 1) { if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } return; } THTensor *tempValues_ = THTensor_(newWithTensor)(values_); // tempValues_.expand_as(t) tempValues_->size[dimension] = t->size[dimension]; tempValues_->stride[dimension] = 0; THLongTensor *tempIndices_ = THLongTensor_newWithTensor(indices_); // tempIndices_.expand_as(t) tempIndices_->size[dimension] = t->size[dimension]; tempIndices_->stride[dimension] = 0; TH_TENSOR_APPLY3_D(real, t, real, tempValues_, long, tempIndices_, dimension, if(!(*t_data <= *tempValues__data) && !th_isnan(*tempValues__data)) { *tempValues__data = *t_data; *tempIndices__data = *tempIndices__dimOffset; }); THTensor_(free)(tempValues_); THLongTensor_free(tempIndices_); } if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } } void THTensor_(min)(THTensor *values_, THLongTensor *indices_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); // two implementations optimized for data locality if (t->stride[dimension] == 1) { real theMax; real value; long theIndex; long i; TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, theMax = t_data[0]; theIndex = 0; for(i = 0; i < t_size; i++) { value = t_data[i*t_stride]; /* This is not the same as value>theMax in the case of NaNs */ if(!(value >= theMax)) { theIndex = i; theMax = value; th_isnan_break(value) } } *indices__data = theIndex; *values__data = theMax;); } else { if (THTensor_(nDimension)(t) > 1) { THTensor *t0 = THTensor_(newSelect)(t, dimension, 0); THTensor_(copy)(values_, t0); THTensor_(free)(t0); } else { THTensor_(fill)(values_, THTensor_(get1d)(t, 0)); } THLongTensor_zero(indices_); if(t->size[dimension] == 1) { if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } return; } THTensor *tempValues_ = THTensor_(newWithTensor)(values_); // tempValues_.expand_as(t) tempValues_->size[dimension] = t->size[dimension]; tempValues_->stride[dimension] = 0; THLongTensor *tempIndices_ = THLongTensor_newWithTensor(indices_); // tempIndices_.expand_as(t) tempIndices_->size[dimension] = t->size[dimension]; tempIndices_->stride[dimension] = 0; TH_TENSOR_APPLY3_D(real, t, real, tempValues_, long, tempIndices_, dimension, if(!(*t_data >= *tempValues__data) && !th_isnan(*tempValues__data)) { *tempValues__data = *t_data; *tempIndices__data = *tempIndices__dimOffset; }); } if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } } void THTensor_(sum)(THTensor *r_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); // two implementations optimized for data locality if (t->stride[dimension] == 1) { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) sum += t_data[i*t_stride]; *r__data = (real)sum;); } else { THTensor_(zero)(r_); THTensor *temp_ = THTensor_(newWithTensor)(r_); // r_.expand_as(t) temp_->size[dimension] = t->size[dimension]; temp_->stride[dimension] = 0; TH_TENSOR_APPLY2(real, temp_, real, t, *temp__data = *temp__data + *t_data;); THTensor_(free)(temp_); } if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } void THTensor_(prod)(THTensor *r_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); // two implementations optimized for data locality if (t->stride[dimension] == 1) { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal prod = 1; long i; for(i = 0; i < t_size; i++) prod *= t_data[i*t_stride]; *r__data = (real)prod;); } else { THTensor_(fill)(r_, 1); THTensor *temp_ = THTensor_(newWithTensor)(r_); // r_.expand_as(t) temp_->size[dimension] = t->size[dimension]; temp_->stride[dimension] = 0; TH_TENSOR_APPLY2(real, temp_, real, t, *temp__data = *temp__data * *t_data;); THTensor_(free)(temp_); } if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } void THTensor_(cumsum)(THTensor *r_, THTensor *t, int dimension) { THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); THTensor_(resizeAs)(r_, t); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal cumsum = 0; long i; for(i = 0; i < t_size; i++) { cumsum += t_data[i*t_stride]; r__data[i*r__stride] = (real)cumsum; }); } void THTensor_(cumprod)(THTensor *r_, THTensor *t, int dimension) { THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); THTensor_(resizeAs)(r_, t); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal cumprod = 1; long i; for(i = 0; i < t_size; i++) { cumprod *= t_data[i*t_stride]; r__data[i*r__stride] = (real)cumprod; }); } void THTensor_(sign)(THTensor *r_, THTensor *t) { THTensor_(resizeAs)(r_, t); #if defined (TH_REAL_IS_BYTE) TH_TENSOR_APPLY2(real, r_, real, t, if (*t_data > 0) *r__data = 1; else *r__data = 0;); #else TH_TENSOR_APPLY2(real, r_, real, t, if (*t_data > 0) *r__data = 1; else if (*t_data < 0) *r__data = -1; else *r__data = 0;); #endif } accreal THTensor_(trace)(THTensor *t) { real *t_data = THTensor_(data)(t); accreal sum = 0; long i = 0; long t_stride_0, t_stride_1, t_diag_size; THArgCheck(THTensor_(nDimension)(t) == 2, 1, "expected a matrix"); t_stride_0 = THTensor_(stride)(t, 0); t_stride_1 = THTensor_(stride)(t, 1); t_diag_size = THMin(THTensor_(size)(t, 0), THTensor_(size)(t, 1)); while(i < t_diag_size) { sum += t_data[i*(t_stride_0+t_stride_1)]; i++; } return sum; } void THTensor_(cross)(THTensor *r_, THTensor *a, THTensor *b, int dimension) { int i; if(THTensor_(nDimension)(a) != THTensor_(nDimension)(b)) THError("inconsistent tensor dimension %dD, %dD", THTensor_(nDimension)(a), THTensor_(nDimension)(b)); for(i = 0; i < THTensor_(nDimension)(a); i++) { if(THTensor_(size)(a, i) != THTensor_(size)(b, i)) { THDescBuff ba = THTensor_(sizeDesc)(a); THDescBuff bb = THTensor_(sizeDesc)(b); THError("inconsistent tensor sizes %s, %s", ba.str, bb.str); } } if(dimension < 0) { for(i = 0; i < THTensor_(nDimension)(a); i++) { if(THTensor_(size)(a, i) == 3) { dimension = i; break; } } if(dimension < 0) { THDescBuff ba = THTensor_(sizeDesc)(a); THError("no dimension of size 3 in a: %s", ba.str); } } THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(a), 3, "dimension %d out of range", dimension + TH_INDEX_BASE); THArgCheck(THTensor_(size)(a, dimension) == 3, 3, "dimension %d does not have size 3", dimension + TH_INDEX_BASE); THTensor_(resizeAs)(r_, a); TH_TENSOR_DIM_APPLY3(real, a, real, b, real, r_, dimension, r__data[0*r__stride] = a_data[1*a_stride]*b_data[2*b_stride] - a_data[2*a_stride]*b_data[1*b_stride]; r__data[1*r__stride] = a_data[2*a_stride]*b_data[0*b_stride] - a_data[0*a_stride]*b_data[2*b_stride]; r__data[2*r__stride] = a_data[0*a_stride]*b_data[1*b_stride] - a_data[1*a_stride]*b_data[0*b_stride];); } void THTensor_(cmax)(THTensor *r, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r, t); TH_TENSOR_APPLY3(real, r, real, t, real, src, *r_data = *t_data > *src_data ? *t_data : *src_data;); } void THTensor_(cmin)(THTensor *r, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r, t); TH_TENSOR_APPLY3(real, r, real, t, real, src, *r_data = *t_data < *src_data ? *t_data : *src_data;); } void THTensor_(cmaxValue)(THTensor *r, THTensor *t, real value) { THTensor_(resizeAs)(r, t); TH_TENSOR_APPLY2(real, r, real, t, *r_data = *t_data > value ? *t_data : value;); } void THTensor_(cminValue)(THTensor *r, THTensor *t, real value) { THTensor_(resizeAs)(r, t); TH_TENSOR_APPLY2(real, r, real, t, *r_data = *t_data < value ? *t_data : value;); } void THTensor_(zeros)(THTensor *r_, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(zero)(r_); } void THTensor_(zerosLike)(THTensor *r_, THTensor *input) { THTensor_(resizeAs)(r_, input); THTensor_(zero)(r_); } void THTensor_(onesLike)(THTensor *r_, THTensor *input) { THTensor_(resizeAs)(r_, input); THTensor_(fill)(r_, 1); } void THTensor_(ones)(THTensor *r_, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(fill)(r_, 1); } void THTensor_(diag)(THTensor *r_, THTensor *t, int k) { THArgCheck(THTensor_(nDimension)(t) == 1 || THTensor_(nDimension)(t) == 2, 1, "matrix or a vector expected"); if(THTensor_(nDimension)(t) == 1) { real *t_data = THTensor_(data)(t); long t_stride_0 = THTensor_(stride)(t, 0); long t_size = THTensor_(size)(t, 0); long sz = t_size + (k >= 0 ? k : -k); real *r__data; long r__stride_0; long r__stride_1; long i; THTensor_(resize2d)(r_, sz, sz); THTensor_(zero)(r_); r__data = THTensor_(data)(r_); r__stride_0 = THTensor_(stride)(r_, 0); r__stride_1 = THTensor_(stride)(r_, 1); r__data += (k >= 0 ? k*r__stride_1 : -k*r__stride_0); for(i = 0; i < t_size; i++) r__data[i*(r__stride_0+r__stride_1)] = t_data[i*t_stride_0]; } else { real *t_data = THTensor_(data)(t); long t_stride_0 = THTensor_(stride)(t, 0); long t_stride_1 = THTensor_(stride)(t, 1); long sz; real *r__data; long r__stride_0; long i; if(k >= 0) sz = THMin(THTensor_(size)(t, 0), THTensor_(size)(t, 1)-k); else sz = THMin(THTensor_(size)(t, 0)+k, THTensor_(size)(t, 1)); THTensor_(resize1d)(r_, sz); r__data = THTensor_(data)(r_); r__stride_0 = THTensor_(stride)(r_, 0); t_data += (k >= 0 ? k*t_stride_1 : -k*t_stride_0); for(i = 0; i < sz; i++) r__data[i*r__stride_0] = t_data[i*(t_stride_0+t_stride_1)]; } } void THTensor_(eye)(THTensor *r_, long n, long m) { real *r__data; long i, sz; THArgCheck(n > 0, 1, "invalid argument"); if(m <= 0) m = n; THTensor_(resize2d)(r_, n, m); THTensor_(zero)(r_); i = 0; r__data = THTensor_(data)(r_); sz = THMin(THTensor_(size)(r_, 0), THTensor_(size)(r_, 1)); for(i = 0; i < sz; i++) r__data[i*(r_->stride[0]+r_->stride[1])] = 1; } void THTensor_(range)(THTensor *r_, accreal xmin, accreal xmax, accreal step) { ptrdiff_t size; real i = 0; THArgCheck(step > 0 || step < 0, 3, "step must be a non-null number"); THArgCheck(((step > 0) && (xmax >= xmin)) || ((step < 0) && (xmax <= xmin)) , 2, "upper bound and larger bound incoherent with step sign"); size = (ptrdiff_t) (((xmax - xmin) / step) + 1); if (THTensor_(nElement)(r_) != size) { THTensor_(resize1d)(r_, size); } TH_TENSOR_APPLY(real, r_, *r__data = xmin + (i++)*step;); } void THTensor_(arange)(THTensor *r_, accreal xmin, accreal xmax, accreal step) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) int m = fmod(xmax - xmin,step) == 0; #else int m = (xmax - xmin) % step == 0; #endif if (m) xmax -= step; THTensor_(range)(r_,xmin,xmax,step); } void THTensor_(randperm)(THTensor *r_, THGenerator *_generator, long n) { real *r__data; long r__stride_0; long i; THArgCheck(n > 0, 1, "must be strictly positive"); THTensor_(resize1d)(r_, n); r__data = THTensor_(data)(r_); r__stride_0 = THTensor_(stride)(r_,0); for(i = 0; i < n; i++) r__data[i*r__stride_0] = (real)(i); for(i = 0; i < n-1; i++) { long z = THRandom_random(_generator) % (n-i); real sav = r__data[i*r__stride_0]; r__data[i*r__stride_0] = r__data[(z+i)*r__stride_0]; r__data[(z+i)*r__stride_0] = sav; } } void THTensor_(reshape)(THTensor *r_, THTensor *t, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(copy)(r_, t); } /* I cut and pasted (slightly adapted) the quicksort code from Sedgewick's 1978 "Implementing Quicksort Programs" article http://www.csie.ntu.edu.tw/~b93076/p847-sedgewick.pdf It is the state of the art existing implementation. The macros are here to make as close a match as possible to the pseudocode of Program 2 p.851 Note that other partition schemes exist, and are typically presented in textbook, but those are less efficient. See e.g. http://cs.stackexchange.com/questions/11458/quicksort-partitioning-hoare-vs-lomuto Julien, November 12th 2013 */ #define MAX_LEVELS 300 #define M_SMALL 10 /* Limit for small subfiles */ #define ARR(III) arr[(III)*stride] #define IDX(III) idx[(III)*stride] #define LONG_SWAP(AAA, BBB) swap = AAA; AAA = BBB; BBB = swap #define REAL_SWAP(AAA, BBB) rswap = AAA; AAA = BBB; BBB = rswap #define ARR_SWAP(III, JJJ) \ REAL_SWAP(ARR(III), ARR(JJJ)); #define BOTH_SWAP(III, JJJ) \ REAL_SWAP(ARR(III), ARR(JJJ)); \ LONG_SWAP(IDX(III), IDX(JJJ)) static void THTensor_(quicksortascend)(real *arr, long *idx, long elements, long stride) { long beg[MAX_LEVELS], end[MAX_LEVELS], i, j, L, R, P, swap, pid, stack = 0, sz_right, sz_left; real rswap, piv; unsigned char done = 0; /* beg[0]=0; end[0]=elements; */ stack = 0; L = 0; R = elements-1; done = elements-1 <= M_SMALL; while(!done) { /* Use median of three for pivot choice */ P=(L+R)>>1; BOTH_SWAP(P, L+1); if (ARR(L+1) > ARR(R)) { BOTH_SWAP(L+1, R); } if (ARR(L) > ARR(R)) { BOTH_SWAP(L, R); } if (ARR(L+1) > ARR(L)) { BOTH_SWAP(L+1, L); } i = L+1; j = R; piv = ARR(L); pid = IDX(L); do { do { i = i+1; } while(ARR(i) < piv); do { j = j-1; } while(ARR(j) > piv); if (j < i) break; BOTH_SWAP(i, j); } while(1); BOTH_SWAP(L, j); /* Left subfile is (L, j-1) */ /* Right subfile is (i, R) */ sz_left = j-L; sz_right = R-i+1; if (sz_left <= M_SMALL && sz_right <= M_SMALL) { /* both subfiles are small */ /* if stack empty */ if (stack == 0) { done = 1; } else { stack--; L = beg[stack]; R = end[stack]; } } else if (sz_left <= M_SMALL || sz_right <= M_SMALL) { /* exactly one of the subfiles is small */ /* (L,R) = large subfile */ if (sz_left > sz_right) { /* Implicit: L = L; */ R = j-1; } else { L = i; /* Implicit: R = R; */ } } else { /* none of the subfiles is small */ /* push large subfile */ /* (L,R) = small subfile */ if (sz_left > sz_right) { beg[stack] = L; end[stack] = j-1; stack++; L = i; /* Implicit: R = R */ } else { beg[stack] = i; end[stack] = R; stack++; /* Implicit: L = L; */ R = j-1; } } } /* while not done */ /* Now insertion sort on the concatenation of subfiles */ for(i=elements-2; i>=0; i--) { if (ARR(i) > ARR(i+1)) { piv = ARR(i); pid = IDX(i); j = i+1; do { ARR(j-1) = ARR(j); IDX(j-1) = IDX(j); j = j+1; } while(j < elements && ARR(j) < piv); ARR(j-1) = piv; IDX(j-1) = pid; } } } static void THTensor_(quicksortdescend)(real *arr, long *idx, long elements, long stride) { long beg[MAX_LEVELS], end[MAX_LEVELS], i, j, L, R, P, swap, pid, stack = 0, sz_right, sz_left; real rswap, piv; unsigned char done = 0; /* beg[0]=0; end[0]=elements; */ stack = 0; L = 0; R = elements-1; done = elements-1 <= M_SMALL; while(!done) { /* Use median of three for pivot choice */ P=(L+R)>>1; BOTH_SWAP(P, L+1); if (ARR(L+1) < ARR(R)) { BOTH_SWAP(L+1, R); } if (ARR(L) < ARR(R)) { BOTH_SWAP(L, R); } if (ARR(L+1) < ARR(L)) { BOTH_SWAP(L+1, L); } i = L+1; j = R; piv = ARR(L); pid = IDX(L); do { do { i = i+1; } while(ARR(i) > piv); do { j = j-1; } while(ARR(j) < piv); if (j < i) break; BOTH_SWAP(i, j); } while(1); BOTH_SWAP(L, j); /* Left subfile is (L, j-1) */ /* Right subfile is (i, R) */ sz_left = j-L; sz_right = R-i+1; if (sz_left <= M_SMALL && sz_right <= M_SMALL) { /* both subfiles are small */ /* if stack empty */ if (stack == 0) { done = 1; } else { stack--; L = beg[stack]; R = end[stack]; } } else if (sz_left <= M_SMALL || sz_right <= M_SMALL) { /* exactly one of the subfiles is small */ /* (L,R) = large subfile */ if (sz_left > sz_right) { /* Implicit: L = L; */ R = j-1; } else { L = i; /* Implicit: R = R; */ } } else { /* none of the subfiles is small */ /* push large subfile */ /* (L,R) = small subfile */ if (sz_left > sz_right) { beg[stack] = L; end[stack] = j-1; stack++; L = i; /* Implicit: R = R */ } else { beg[stack] = i; end[stack] = R; stack++; /* Implicit: L = L; */ R = j-1; } } } /* while not done */ /* Now insertion sort on the concatenation of subfiles */ for(i=elements-2; i>=0; i--) { if (ARR(i) < ARR(i+1)) { piv = ARR(i); pid = IDX(i); j = i+1; do { ARR(j-1) = ARR(j); IDX(j-1) = IDX(j); j = j+1; } while(j < elements && ARR(j) > piv); ARR(j-1) = piv; IDX(j-1) = pid; } } } #undef MAX_LEVELS #undef M_SMALL void THTensor_(sort)(THTensor *rt_, THLongTensor *ri_, THTensor *t, int dimension, int descendingOrder) { THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "invalid dimension %d", dimension + TH_INDEX_BASE); THTensor_(resizeAs)(rt_, t); THTensor_(copy)(rt_, t); { THLongStorage *size = THTensor_(newSizeOf)(t); THLongTensor_resize(ri_, size, NULL); THLongStorage_free(size); } if(descendingOrder) { TH_TENSOR_DIM_APPLY2(real, rt_, long, ri_, dimension, long i; for(i = 0; i < ri__size; i++) ri__data[i*ri__stride] = i; THTensor_(quicksortdescend)(rt__data, ri__data, rt__size, rt__stride);) } else { TH_TENSOR_DIM_APPLY2(real, rt_, long, ri_, dimension, long i; for(i = 0; i < ri__size; i++) ri__data[i*ri__stride] = i; THTensor_(quicksortascend)(rt__data, ri__data, rt__size, rt__stride);) } } /* Implementation of the Quickselect algorithm, based on Nicolas Devillard's public domain implementation at http://ndevilla.free.fr/median/median/ Adapted similarly to the above Quicksort algorithm. This version does not produce indices along with values. */ static void THTensor_(quickselectnoidx)(real *arr, long k, long elements, long stride) { long P, L, R, i, j, swap; real rswap, piv; L = 0; R = elements-1; do { if (R <= L) /* One element only */ return; if (R == L+1) { /* Two elements only */ if (ARR(L) > ARR(R)) { ARR_SWAP(L, R); } return; } /* Use median of three for pivot choice */ P=(L+R)>>1; ARR_SWAP(P, L+1); if (ARR(L+1) > ARR(R)) { ARR_SWAP(L+1, R); } if (ARR(L) > ARR(R)) { ARR_SWAP(L, R); } if (ARR(L+1) > ARR(L)) { ARR_SWAP(L+1, L); } i = L+1; j = R; piv = ARR(L); do { do i++; while(ARR(i) < piv); do j--; while(ARR(j) > piv); if (j < i) break; ARR_SWAP(i, j); } while(1); ARR_SWAP(L, j); /* Re-set active partition */ if (j <= k) L=i; if (j >= k) R=j-1; } while(1); } /* Implementation of the Quickselect algorithm, based on Nicolas Devillard's public domain implementation at http://ndevilla.free.fr/median/median/ Adapted similarly to the above Quicksort algorithm. */ static void THTensor_(quickselect)(real *arr, long *idx, long k, long elements, long stride) { long P, L, R, i, j, swap, pid; real rswap, piv; L = 0; R = elements-1; do { if (R <= L) /* One element only */ return; if (R == L+1) { /* Two elements only */ if (ARR(L) > ARR(R)) { BOTH_SWAP(L, R); } return; } /* Use median of three for pivot choice */ P=(L+R)>>1; BOTH_SWAP(P, L+1); if (ARR(L+1) > ARR(R)) { BOTH_SWAP(L+1, R); } if (ARR(L) > ARR(R)) { BOTH_SWAP(L, R); } if (ARR(L+1) > ARR(L)) { BOTH_SWAP(L+1, L); } i = L+1; j = R; piv = ARR(L); pid = IDX(L); do { do i++; while(ARR(i) < piv); do j--; while(ARR(j) > piv); if (j < i) break; BOTH_SWAP(i, j); } while(1); BOTH_SWAP(L, j); /* Re-set active partition */ if (j <= k) L=i; if (j >= k) R=j-1; } while(1); } #undef ARR #undef IDX #undef LONG_SWAP #undef REAL_SWAP #undef BOTH_SWAP void THTensor_(mode)(THTensor *values_, THLongTensor *indices_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THTensor *temp_; THLongTensor *tempi_; real *temp__data; long *tempi__data; long t_size_dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "dimension out of range"); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); t_size_dim = THTensor_(size)(t, dimension); temp_ = THTensor_(new)(); THTensor_(resize1d)(temp_, t_size_dim); temp__data = THTensor_(data)(temp_); tempi_ = THLongTensor_new(); THLongTensor_resize1d(tempi_, t_size_dim); tempi__data = THLongTensor_data(tempi_); TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, long i; real mode = 0; long modei = 0; long temp_freq = 0; long max_freq = 0; for(i = 0; i < t_size_dim; i++) temp__data[i] = t_data[i*t_stride]; for(i = 0; i < t_size_dim; i++) tempi__data[i] = i; THTensor_(quicksortascend)(temp__data, tempi__data, t_size_dim, 1); for(i = 0; i < t_size_dim; i++) { temp_freq++; if ((i == t_size_dim - 1) || (temp__data[i] != temp__data[i+1])) { if (temp_freq > max_freq) { mode = temp__data[i]; modei = tempi__data[i]; max_freq = temp_freq; } temp_freq = 0; } } *values__data = mode; *indices__data = modei;); THTensor_(free)(temp_); THLongTensor_free(tempi_); if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } } void THTensor_(kthvalue)(THTensor *values_, THLongTensor *indices_, THTensor *t, long k, int dimension, int keepdim) { THLongStorage *dim; THTensor *temp_; THLongTensor *tempi_; real *temp__data; long *tempi__data; long t_size_dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "dimension out of range"); THArgCheck(k > 0 && k <= t->size[dimension], 2, "selected index out of range"); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); t_size_dim = THTensor_(size)(t, dimension); temp_ = THTensor_(new)(); THTensor_(resize1d)(temp_, t_size_dim); temp__data = THTensor_(data)(temp_); tempi_ = THLongTensor_new(); THLongTensor_resize1d(tempi_, t_size_dim); tempi__data = THLongTensor_data(tempi_); TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, long i; for(i = 0; i < t_size_dim; i++) temp__data[i] = t_data[i*t_stride]; for(i = 0; i < t_size_dim; i++) tempi__data[i] = i; THTensor_(quickselect)(temp__data, tempi__data, k - 1, t_size_dim, 1); *values__data = temp__data[k-1]; *indices__data = tempi__data[k-1];); THTensor_(free)(temp_); THLongTensor_free(tempi_); if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } } void THTensor_(median)(THTensor *values_, THLongTensor *indices_, THTensor *t, int dimension, int keepdim) { long t_size_dim, k; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "dimension out of range"); t_size_dim = THTensor_(size)(t, dimension); k = (t_size_dim-1) >> 1; /* take middle or one-before-middle element */ THTensor_(kthvalue)(values_, indices_, t, k+1, dimension, keepdim); } void THTensor_(topk)(THTensor *rt_, THLongTensor *ri_, THTensor *t, long k, int dim, int dir, int sorted) { int numDims = THTensor_(nDimension)(t); THArgCheck(dim >= 0 && dim < numDims, 3, "dim not in range"); long sliceSize = THTensor_(size)(t, dim); THArgCheck(k > 0 && k <= sliceSize, 2, "k not in range for dimension"); THTensor *tmpResults = THTensor_(new)(); THTensor_(resize1d)(tmpResults, sliceSize); real *tmp__data = THTensor_(data)(tmpResults); THLongTensor *tmpIndices = THLongTensor_new(); THLongTensor_resize1d(tmpIndices, sliceSize); long *tmpi__data = THLongTensor_data(tmpIndices); THLongStorage *topKSize = THTensor_(newSizeOf)(t); THLongStorage_set(topKSize, dim, k); THTensor_(resize)(rt_, topKSize, NULL); THLongTensor_resize(ri_, topKSize, NULL); THLongStorage_free(topKSize); if (dir) { /* k largest elements, descending order (optional: see sorted) */ long K = sliceSize - k; TH_TENSOR_DIM_APPLY3(real, t, real, rt_, long, ri_, dim, long i; for(i = 0; i < sliceSize; i++) { tmp__data[i] = t_data[i*t_stride]; tmpi__data[i] = i; } if (K > 0) THTensor_(quickselect)(tmp__data, tmpi__data, K - 1, sliceSize, 1); if (sorted) THTensor_(quicksortdescend)(tmp__data + K, tmpi__data + K, k, 1); for(i = 0; i < k; i++) { rt__data[i*rt__stride] = tmp__data[i + K]; ri__data[i*ri__stride] = tmpi__data[i + K]; }) } else { /* k smallest elements, ascending order (optional: see sorted) */ TH_TENSOR_DIM_APPLY3(real, t, real, rt_, long, ri_, dim, long i; for(i = 0; i < sliceSize; i++) { tmp__data[i] = t_data[i*t_stride]; tmpi__data[i] = i; } THTensor_(quickselect)(tmp__data, tmpi__data, k - 1, sliceSize, 1); if (sorted) THTensor_(quicksortascend)(tmp__data, tmpi__data, k - 1, 1); for(i = 0; i < k; i++) { rt__data[i*rt__stride] = tmp__data[i]; ri__data[i*ri__stride] = tmpi__data[i]; }) } THTensor_(free)(tmpResults); THLongTensor_free(tmpIndices); } void THTensor_(tril)(THTensor *r_, THTensor *t, long k) { long t_size_0, t_size_1; long t_stride_0, t_stride_1; long r__stride_0, r__stride_1; real *t_data, *r__data; long r, c; THArgCheck(THTensor_(nDimension)(t) == 2, 1, "expected a matrix"); THTensor_(resizeAs)(r_, t); t_size_0 = THTensor_(size)(t, 0); t_size_1 = THTensor_(size)(t, 1); t_stride_0 = THTensor_(stride)(t, 0); t_stride_1 = THTensor_(stride)(t, 1); r__stride_0 = THTensor_(stride)(r_, 0); r__stride_1 = THTensor_(stride)(r_, 1); r__data = THTensor_(data)(r_); t_data = THTensor_(data)(t); for(r = 0; r < t_size_0; r++) { long sz = THMin(r+k+1, t_size_1); for(c = THMax(0, r+k+1); c < t_size_1; c++) r__data[r*r__stride_0+c*r__stride_1] = 0; for(c = 0; c < sz; c++) r__data[r*r__stride_0+c*r__stride_1] = t_data[r*t_stride_0+c*t_stride_1]; } } void THTensor_(triu)(THTensor *r_, THTensor *t, long k) { long t_size_0, t_size_1; long t_stride_0, t_stride_1; long r__stride_0, r__stride_1; real *t_data, *r__data; long r, c; THArgCheck(THTensor_(nDimension)(t) == 2, 1, "expected a matrix"); THTensor_(resizeAs)(r_, t); t_size_0 = THTensor_(size)(t, 0); t_size_1 = THTensor_(size)(t, 1); t_stride_0 = THTensor_(stride)(t, 0); t_stride_1 = THTensor_(stride)(t, 1); r__stride_0 = THTensor_(stride)(r_, 0); r__stride_1 = THTensor_(stride)(r_, 1); r__data = THTensor_(data)(r_); t_data = THTensor_(data)(t); for(r = 0; r < t_size_0; r++) { long sz = THMin(r+k, t_size_1); for(c = THMax(0, r+k); c < t_size_1; c++) r__data[r*r__stride_0+c*r__stride_1] = t_data[r*t_stride_0+c*t_stride_1]; for(c = 0; c < sz; c++) r__data[r*r__stride_0+c*r__stride_1] = 0; } } void THTensor_(cat)(THTensor *r_, THTensor *ta, THTensor *tb, int dimension) { THTensor* inputs[2]; inputs[0] = ta; inputs[1] = tb; THTensor_(catArray)(r_, inputs, 2, dimension); } void THTensor_(catArray)(THTensor *result, THTensor **inputs, int numInputs, int dimension) { THLongStorage *size; int i, j; long offset; int maxDim = dimension + 1; int allEmpty = 1; int allContiguous = 1; // cat_dimension is the actual dimension we cat along int cat_dimension = dimension; for (i = 0; i < numInputs; i++) { maxDim = THMax(maxDim, inputs[i]->nDimension); } // When the user input dimension is -1 (i.e. -2 in C) // Then we pick the maximum last dimension across all tensors. if ( dimension + TH_INDEX_BASE == -1 ) { cat_dimension = maxDim?(maxDim-1):0; } THArgCheck(numInputs > 0, 3, "invalid number of inputs %d", numInputs); THArgCheck(cat_dimension >= 0, 4, "invalid dimension %d", dimension + TH_INDEX_BASE); size = THLongStorage_newWithSize(maxDim); for(i = 0; i < maxDim; i++) { // dimSize is either the size of the dim if it exists, either 1 if #dim > 0, otherwise 0 long dimSize = i < inputs[0]->nDimension ? inputs[0]->size[i] : THMin(inputs[0]->nDimension, 1); if (i == cat_dimension) { for (j = 1; j < numInputs; j++) { // accumulate the size over the dimension we want to cat on. // Empty tensors are allowed dimSize += i < inputs[j]->nDimension ? inputs[j]->size[i] : THMin(inputs[j]->nDimension, 1); } } else { for (j = 1; j < numInputs; j++) { long sz = (i < inputs[j]->nDimension ? inputs[j]->size[i] : THMin(inputs[j]->nDimension, 1)); // If it's a dimension we're not catting on // Then fail if sizes are different AND > 0 if (dimSize != sz && dimSize && sz) { THLongStorage_free(size); THError("inconsistent tensor sizes"); } else if(!dimSize) { dimSize = sz; } } } allEmpty = allEmpty && !dimSize; size->data[i] = dimSize; } // Initiate catting and resizing // If at least one of the input is not empty if (!allEmpty) { THTensor_(resize)(result, size, NULL); // Check contiguity of all inputs and result for (i = 0; i < numInputs; i++) { if(inputs[i]->nDimension) { allContiguous = allContiguous && THTensor_(isContiguous)(inputs[i]); } } allContiguous = allContiguous && THTensor_(isContiguous)(result); // First path is for contiguous inputs along dim 1 // Second path for non-contiguous if (cat_dimension == 0 && allContiguous) { real* result_data = result->storage->data + result->storageOffset; offset = 0; for (j = 0; j < numInputs; j++) { if (inputs[j]->nDimension) { THTensor* input0 = inputs[j]; real* input0_data = input0->storage->data + input0->storageOffset; long input0_size = THTensor_(nElement)(input0); memcpy(result_data + offset, input0_data, input0_size*sizeof(real)); offset += input0_size; } } } else { offset = 0; for (j = 0; j < numInputs; j++) { if (inputs[j]->nDimension) { long dimSize = cat_dimension < inputs[j]->nDimension ? inputs[j]->size[cat_dimension] : 1; THTensor *nt = THTensor_(newWithTensor)(result); THTensor_(narrow)(nt, NULL, cat_dimension, offset, dimSize); THTensor_(copy)(nt, inputs[j]); THTensor_(free)(nt); offset += dimSize; } } } } THLongStorage_free(size); } int THTensor_(equal)(THTensor *ta, THTensor* tb) { int equal = 1; if(!THTensor_(isSameSizeAs)(ta, tb)) return 0; if (THTensor_(isContiguous)(ta) && THTensor_(isContiguous)(tb)) { real *tap = THTensor_(data)(ta); real *tbp = THTensor_(data)(tb); ptrdiff_t sz = THTensor_(nElement)(ta); ptrdiff_t i; for (i=0; i<sz; ++i){ if(tap[i] != tbp[i]) return 0; } } else { // Short-circuit the apply function on inequality TH_TENSOR_APPLY2(real, ta, real, tb, if (equal && *ta_data != *tb_data) { equal = 0; TH_TENSOR_APPLY_hasFinished = 1; break; }) } return equal; } #define TENSOR_IMPLEMENT_LOGICAL(NAME,OP) \ void THTensor_(NAME##Value)(THByteTensor *r_, THTensor* t, real value) \ { \ THByteTensor_resizeNd(r_, t->nDimension, t->size, NULL); \ TH_TENSOR_APPLY2(unsigned char, r_, real, t, \ *r__data = (*t_data OP value) ? 1 : 0;); \ } \ void THTensor_(NAME##ValueT)(THTensor* r_, THTensor* t, real value) \ { \ THTensor_(resizeNd)(r_, t->nDimension, t->size, NULL); \ TH_TENSOR_APPLY2(real, r_, real, t, \ *r__data = (*t_data OP value) ? 1 : 0;); \ } \ void THTensor_(NAME##Tensor)(THByteTensor *r_, THTensor *ta, THTensor *tb) \ { \ THByteTensor_resizeNd(r_, ta->nDimension, ta->size, NULL); \ TH_TENSOR_APPLY3(unsigned char, r_, real, ta, real, tb, \ *r__data = (*ta_data OP *tb_data) ? 1 : 0;); \ } \ void THTensor_(NAME##TensorT)(THTensor *r_, THTensor *ta, THTensor *tb) \ { \ THTensor_(resizeNd)(r_, ta->nDimension, ta->size, NULL); \ TH_TENSOR_APPLY3(real, r_, real, ta, real, tb, \ *r__data = (*ta_data OP *tb_data) ? 1 : 0;); \ } \ TENSOR_IMPLEMENT_LOGICAL(lt,<) TENSOR_IMPLEMENT_LOGICAL(gt,>) TENSOR_IMPLEMENT_LOGICAL(le,<=) TENSOR_IMPLEMENT_LOGICAL(ge,>=) TENSOR_IMPLEMENT_LOGICAL(eq,==) TENSOR_IMPLEMENT_LOGICAL(ne,!=) #define LAB_IMPLEMENT_BASIC_FUNCTION(NAME, CFUNC) \ void THTensor_(NAME)(THTensor *r_, THTensor *t) \ { \ THTensor_(resizeAs)(r_, t); \ TH_TENSOR_APPLY2(real, t, real, r_, *r__data = CFUNC(*t_data);); \ } \ #if defined(TH_REAL_IS_LONG) LAB_IMPLEMENT_BASIC_FUNCTION(abs,labs) LAB_IMPLEMENT_BASIC_FUNCTION(neg,-) #endif /* long only part */ #if defined(TH_REAL_IS_SHORT) || defined(TH_REAL_IS_INT) LAB_IMPLEMENT_BASIC_FUNCTION(abs,abs) LAB_IMPLEMENT_BASIC_FUNCTION(neg,-) #endif /* int only part */ #if defined(TH_REAL_IS_BYTE) #define TENSOR_IMPLEMENT_LOGICAL_SUM(NAME, OP, INIT_VALUE) \ int THTensor_(NAME)(THTensor *tensor) \ { \ THArgCheck(tensor->nDimension > 0, 1, "empty Tensor"); \ int sum = INIT_VALUE; \ TH_TENSOR_APPLY(real, tensor, sum = sum OP *tensor_data;); \ return sum; \ } TENSOR_IMPLEMENT_LOGICAL_SUM(logicalall, &&, 1) TENSOR_IMPLEMENT_LOGICAL_SUM(logicalany, ||, 0) #endif /* Byte only part */ /* floating point only now */ #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) #if defined (TH_REAL_IS_FLOAT) #define TH_MATH_NAME(fn) fn##f #else #define TH_MATH_NAME(fn) fn #endif LAB_IMPLEMENT_BASIC_FUNCTION(log,TH_MATH_NAME(log)) LAB_IMPLEMENT_BASIC_FUNCTION(lgamma,TH_MATH_NAME(lgamma)) LAB_IMPLEMENT_BASIC_FUNCTION(log1p,TH_MATH_NAME(log1p)) LAB_IMPLEMENT_BASIC_FUNCTION(sigmoid,TH_MATH_NAME(TH_sigmoid)) LAB_IMPLEMENT_BASIC_FUNCTION(exp,TH_MATH_NAME(exp)) LAB_IMPLEMENT_BASIC_FUNCTION(cos,TH_MATH_NAME(cos)) LAB_IMPLEMENT_BASIC_FUNCTION(acos,TH_MATH_NAME(acos)) LAB_IMPLEMENT_BASIC_FUNCTION(cosh,TH_MATH_NAME(cosh)) LAB_IMPLEMENT_BASIC_FUNCTION(sin,TH_MATH_NAME(sin)) LAB_IMPLEMENT_BASIC_FUNCTION(asin,TH_MATH_NAME(asin)) LAB_IMPLEMENT_BASIC_FUNCTION(sinh,TH_MATH_NAME(sinh)) LAB_IMPLEMENT_BASIC_FUNCTION(tan,TH_MATH_NAME(tan)) LAB_IMPLEMENT_BASIC_FUNCTION(atan,TH_MATH_NAME(atan)) LAB_IMPLEMENT_BASIC_FUNCTION(tanh,TH_MATH_NAME(tanh)) LAB_IMPLEMENT_BASIC_FUNCTION(sqrt,TH_MATH_NAME(sqrt)) LAB_IMPLEMENT_BASIC_FUNCTION(rsqrt,TH_MATH_NAME(TH_rsqrt)) LAB_IMPLEMENT_BASIC_FUNCTION(ceil,TH_MATH_NAME(ceil)) LAB_IMPLEMENT_BASIC_FUNCTION(floor,TH_MATH_NAME(floor)) LAB_IMPLEMENT_BASIC_FUNCTION(round,TH_MATH_NAME(round)) LAB_IMPLEMENT_BASIC_FUNCTION(abs,TH_MATH_NAME(fabs)) LAB_IMPLEMENT_BASIC_FUNCTION(trunc,TH_MATH_NAME(trunc)) LAB_IMPLEMENT_BASIC_FUNCTION(frac,TH_MATH_NAME(TH_frac)) LAB_IMPLEMENT_BASIC_FUNCTION(neg,-) LAB_IMPLEMENT_BASIC_FUNCTION(cinv, TH_MATH_NAME(1.0) / ) void THTensor_(pow)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if(value == 1){ THTensor_(copy)(r_, t); } else if(value == 2){ THTensor_(cmul)(r_, t, t); } else if(value == 3){ TH_TENSOR_APPLY2(real, t, real, r_, *r__data = *t_data * *t_data * *t_data;); } else if(value == 0.5){ THTensor_(sqrt)(r_, t); } else if(value == -0.5){ THTensor_(rsqrt)(r_, t); } else if(value == -1){ THTensor_(cinv)(r_, t); } else if(value == -2){ TH_TENSOR_APPLY2(real, t, real, r_, *r__data = TH_MATH_NAME(1.0) / (*t_data * *t_data);); } else{ TH_TENSOR_APPLY2(real, t, real, r_, *r__data = TH_MATH_NAME(pow)(*t_data, value);); } } void THTensor_(atan2)(THTensor *r_, THTensor *tx, THTensor *ty) { THTensor_(resizeAs)(r_, tx); TH_TENSOR_APPLY3(real, r_, real, tx, real, ty, *r__data = TH_MATH_NAME(atan2)(*tx_data,*ty_data);); } void THTensor_(lerp)(THTensor *r_, THTensor *a, THTensor *b, real weight) { THArgCheck(THTensor_(nElement)(a) == THTensor_(nElement)(b), 2, "sizes do not match"); THTensor_(resizeAs)(r_, a); TH_TENSOR_APPLY3(real, r_, real, a, real, b, *r__data = TH_MATH_NAME(TH_lerp)(*a_data, *b_data, weight);); } void THTensor_(mean)(THTensor *r_, THTensor *t, int dimension, int keepdim) { THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "invalid dimension %d", dimension + TH_INDEX_BASE); THTensor_(sum)(r_, t, dimension, keepdim); THTensor_(div)(r_, r_, t->size[dimension]); } void THTensor_(std)(THTensor *r_, THTensor *t, int dimension, int biased, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "invalid dimension %d", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; accreal sum2 = 0; long i; for(i = 0; i < t_size; i++) { real z = t_data[i*t_stride]; sum += z; sum2 += z*z; } if(biased) { sum /= t_size; sum2 /= t_size; sum2 -= sum*sum; sum2 = (sum2 < 0 ? 0 : sum2); *r__data = (real)TH_MATH_NAME(sqrt)(sum2); } else { sum /= t_size; sum2 /= t_size-1; sum2 -= ((real)t_size)/((real)(t_size-1))*sum*sum; sum2 = (sum2 < 0 ? 0 : sum2); *r__data = (real)TH_MATH_NAME(sqrt)(sum2); }); if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } void THTensor_(var)(THTensor *r_, THTensor *t, int dimension, int biased, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "invalid dimension %d", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; accreal sum2 = 0; long i; for(i = 0; i < t_size; i++) { real z = t_data[i*t_stride]; sum += z; sum2 += z*z; } if(biased) { sum /= t_size; sum2 /= t_size; sum2 -= sum*sum; sum2 = (sum2 < 0 ? 0 : sum2); *r__data = sum2; } else { sum /= t_size; sum2 /= t_size-1; sum2 -= ((real)t_size)/((real)(t_size-1))*sum*sum; sum2 = (sum2 < 0 ? 0 : sum2); *r__data = (real)sum2; }); if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } void THTensor_(norm)(THTensor *r_, THTensor *t, real value, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "invalid dimension %d", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); if(value == 0) { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) sum += t_data[i*t_stride] != 0.0; *r__data = sum;) } else { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) { sum += TH_MATH_NAME(pow)( TH_MATH_NAME(fabs)(t_data[i*t_stride]), value); } *r__data = TH_MATH_NAME(pow)(sum, 1.0/value);) } if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } accreal THTensor_(normall)(THTensor *tensor, real value) { accreal sum = 0; if(value == 0) { TH_TENSOR_APPLY(real, tensor, sum += *tensor_data != 0.0;); return sum; } else if(value == 1) { TH_TENSOR_APPLY(real, tensor, sum += TH_MATH_NAME(fabs)(*tensor_data);); return sum; } else if(value == 2) { TH_TENSOR_APPLY(real, tensor, accreal z = *tensor_data; sum += z*z;); return sqrt(sum); } else { TH_TENSOR_APPLY(real, tensor, sum += TH_MATH_NAME(pow)(TH_MATH_NAME(fabs)(*tensor_data), value);); return TH_MATH_NAME(pow)(sum, 1.0/value); } } void THTensor_(renorm)(THTensor *res, THTensor *src, real value, int dimension, real maxnorm) { int i; THTensor *rowR, *rowS; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(src), 3, "invalid dimension %d", dimension + TH_INDEX_BASE); THArgCheck(value > 0, 2, "non-positive-norm not supported"); THArgCheck(THTensor_(nDimension)(src) > 1, 1, "need at least 2 dimensions, got %d dimensions", THTensor_(nDimension)(src)); rowR = THTensor_(new)(); rowS = THTensor_(new)(); THTensor_(resizeAs)(res, src); for (i=0; i<src->size[dimension]; i++) { real norm = 0; real new_norm; THTensor_(select)(rowS, src, dimension, i); THTensor_(select)(rowR, res, dimension, i); if (value == 1) { TH_TENSOR_APPLY(real, rowS, norm += fabs(*rowS_data);); } else if (value == 2) { TH_TENSOR_APPLY(real, rowS, accreal z = *rowS_data; norm += z*z;); } else { TH_TENSOR_APPLY(real, rowS, norm += TH_MATH_NAME(pow)(TH_MATH_NAME(fabs)(*rowS_data), value);); } norm = pow(norm, 1/value); if (norm > maxnorm) { new_norm = maxnorm / (norm + 1e-7); TH_TENSOR_APPLY2( real, rowR, real, rowS, *rowR_data = (*rowS_data) * new_norm; ) } else THTensor_(copy)(rowR, rowS); } THTensor_(free)(rowR); THTensor_(free)(rowS); } accreal THTensor_(dist)(THTensor *tensor, THTensor *src, real value) { real sum = 0; TH_TENSOR_APPLY2(real, tensor, real, src, sum += TH_MATH_NAME(pow)( TH_MATH_NAME(fabs)(*tensor_data - *src_data), value);); return TH_MATH_NAME(pow)(sum, 1.0/value); } accreal THTensor_(meanall)(THTensor *tensor) { THArgCheck(tensor->nDimension > 0, 1, "empty Tensor"); return THTensor_(sumall)(tensor)/THTensor_(nElement)(tensor); } accreal THTensor_(varall)(THTensor *tensor, int biased) { accreal mean = THTensor_(meanall)(tensor); accreal sum = 0; TH_TENSOR_APPLY(real, tensor, sum += (*tensor_data - mean)*(*tensor_data - mean);); sum /= THTensor_(nElement)(tensor) - (biased ? 0 : 1); return sum; } accreal THTensor_(stdall)(THTensor *tensor, int biased) { return sqrt(THTensor_(varall)(tensor, biased)); } void THTensor_(linspace)(THTensor *r_, real a, real b, long n) { real i = 0; THArgCheck(n > 1 || (n == 1 && (a == b)), 3, "invalid number of points"); if (THTensor_(nElement)(r_) != n) { THTensor_(resize1d)(r_, n); } if(n == 1) { THTensor_(set1d)(r_, 0, a); } else { TH_TENSOR_APPLY(real, r_, *r__data = a + i*(b-a)/((real)(n-1)); i++; ); } } void THTensor_(logspace)(THTensor *r_, real a, real b, long n) { real i = 0; THArgCheck(n > 1 || (n == 1 && (a == b)), 3, "invalid number of points"); if (THTensor_(nElement)(r_) != n) { THTensor_(resize1d)(r_, n); } if(n == 1) { THTensor_(set1d)(r_, 0, TH_MATH_NAME(pow)(10.0, a)); } else { TH_TENSOR_APPLY(real, r_, *r__data = TH_MATH_NAME(pow)(10.0, a + i*(b-a)/((real)(n-1))); i++; ); } } void THTensor_(rand)(THTensor *r_, THGenerator *_generator, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(uniform)(r_, _generator, 0, 1); } void THTensor_(randn)(THTensor *r_, THGenerator *_generator, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(normal)(r_, _generator, 0, 1); } void THTensor_(histc)(THTensor *hist, THTensor *tensor, long nbins, real minvalue, real maxvalue) { real minval; real maxval; real *h_data; THTensor_(resize1d)(hist, nbins); THTensor_(zero)(hist); minval = minvalue; maxval = maxvalue; if (minval == maxval) { minval = THTensor_(minall)(tensor); maxval = THTensor_(maxall)(tensor); } if (minval == maxval) { minval = minval - 1; maxval = maxval + 1; } h_data = THTensor_(data)(hist); TH_TENSOR_APPLY(real, tensor, if (*tensor_data >= minval && *tensor_data <= maxval) { const int bin = (int)((*tensor_data-minval) / (maxval-minval) * nbins); h_data[THMin(bin, nbins-1)] += 1; } ); } void THTensor_(bhistc)(THTensor *hist, THTensor *tensor, long nbins, real minvalue, real maxvalue) { THArgCheck(THTensor_(nDimension)(tensor) < 3, 2, "invalid dimension %d, the input must be a 2d tensor", THTensor_(nDimension)(tensor)); int dimension = 1; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(tensor), 2, "invalid dimension %d", dimension + TH_INDEX_BASE); real minval; real maxval; real *h_data; THTensor_(resize2d)(hist, tensor->size[0], nbins); THTensor_(zero)(hist); minval = minvalue; maxval = maxvalue; if (minval == maxval) { minval = THTensor_(minall)(tensor); maxval = THTensor_(maxall)(tensor); } if (minval == maxval) { minval = minval - 1; maxval = maxval + 1; } TH_TENSOR_DIM_APPLY2(real, tensor, real, hist, dimension, long i; for(i = 0; i < tensor_size; i++) { if(tensor_data[i*tensor_stride] >= minval && tensor_data[i*tensor_stride] <= maxval) { const int bin = (int)((tensor_data[i*tensor_stride]-minval) / (maxval-minval) * nbins); hist_data[THMin(bin, nbins-1)] += 1; } } ); } #undef TH_MATH_NAME #endif /* floating point only part */ #undef IS_NONZERO #endif
laplace2d-02.c
#include <math.h> #include <string.h> #include <stdio.h> #include <omp.h> #define NN 4096 #define NM 4096 __attribute__((target(mic))) double A[NN][NM]; __attribute__((target(mic))) double Anew[NN][NM]; int main(int argc, char** argv) { const int n = NN; const int m = NM; const int iter_max = 200; const double tol = 1.0e-6; double error = 1.0; memset(A, 0, n * m * sizeof(double)); memset(Anew, 0, n * m * sizeof(double)); for (int j = 0; j < n; j++) { A[j][0] = 1.0; Anew[j][0] = 1.0; } printf("Jacobi relaxation Calculation: %d x %d mesh\n", n, m); double st = omp_get_wtime(); int iter = 0; while ( error > tol && iter < iter_max ) { error = 0.0; #pragma omp target map(alloc:Anew) map(A) { #pragma omp parallel for reduction(max:error) for( int j = 1; j < n-1; j++) { for( int i = 1; i < m-1; i++ ) { Anew[j][i] = 0.25 * ( A[j][i+1] + A[j][i-1] + A[j-1][i] + A[j+1][i]); error = fmax( error, fabs(Anew[j][i] - A[j][i])); } } #pragma omp parallel for for( int j = 1; j < n-1; j++) { for( int i = 1; i < m-1; i++ ) { A[j][i] = Anew[j][i]; } } } // OMP TARGET if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error); iter++; } double et = omp_get_wtime(); printf(" total: %f s\n", (et - st)); return 0; }
GB_binop__ge_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__ge_uint64 // A.*B function (eWiseMult): GB_AemultB__ge_uint64 // A*D function (colscale): GB_AxD__ge_uint64 // D*A function (rowscale): GB_DxB__ge_uint64 // C+=B function (dense accum): GB_Cdense_accumB__ge_uint64 // C+=b function (dense accum): GB_Cdense_accumb__ge_uint64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__ge_uint64 // C=scalar+B GB_bind1st__ge_uint64 // C=scalar+B' GB_bind1st_tran__ge_uint64 // C=A+scalar GB_bind2nd__ge_uint64 // C=A'+scalar GB_bind2nd_tran__ge_uint64 // C type: bool // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij >= bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x >= y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_GE || GxB_NO_UINT64 || GxB_NO_GE_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__ge_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__ge_uint64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__ge_uint64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__ge_uint64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__ge_uint64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__ge_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__ge_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__ge_uint64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = Bx [p] ; Cx [p] = (x >= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__ge_uint64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = Ax [p] ; Cx [p] = (aij >= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (x >= aij) ; \ } GrB_Info GB_bind1st_tran__ge_uint64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (aij >= y) ; \ } GrB_Info GB_bind2nd_tran__ge_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_dense_subassign_25_template.c
//------------------------------------------------------------------------------ // GB_dense_subassign_25_template: C<M> = A where C is empty and A is dense //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // C<M> = A where C starts as empty, M is structural, and A is dense. The // pattern of C is an exact copy of M. { //-------------------------------------------------------------------------- // get C, M, and A //-------------------------------------------------------------------------- GB_CTYPE *GB_RESTRICT Cx = (GB_CTYPE *) C->x ; const int64_t *GB_RESTRICT Mp = M->p ; const int64_t *GB_RESTRICT Mh = M->h ; const int64_t *GB_RESTRICT Mi = M->i ; const GB_ATYPE *GB_RESTRICT Ax = (GB_ATYPE *) A->x ; const int64_t avlen = A->vlen ; //-------------------------------------------------------------------------- // C<M> = A //-------------------------------------------------------------------------- int taskid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (taskid = 0 ; taskid < ntasks ; taskid++) { // if kfirst > klast then taskid does no work at all int64_t kfirst = kfirst_slice [taskid] ; int64_t klast = klast_slice [taskid] ; //---------------------------------------------------------------------- // C<M(:,kfirst:klast)> = A(:,kfirst:klast) //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // find the part of M(:,k) to be operated on by this task //------------------------------------------------------------------ int64_t j = (Mh == NULL) ? k : Mh [k] ; int64_t pM_start, pM_end ; GB_get_pA_and_pC (&pM_start, &pM_end, NULL, taskid, k, kfirst, klast, pstart_slice, NULL, NULL, Mp) ; // pA points to the start of A(:,j) since A is dense int64_t pA = j * avlen ; //------------------------------------------------------------------ // C<M(:,j)> = A(:,j) //------------------------------------------------------------------ GB_PRAGMA_SIMD_VECTORIZE for (int64_t pM = pM_start ; pM < pM_end ; pM++) { int64_t p = pA + Mi [pM] ; GB_COPY_A_TO_C (Cx, pM, Ax, p) ; // Cx [pM] = Ax [p] } } } }
ast-dump-openmp-target.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test(void) { #pragma omp target ; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: `-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-target.c:3:1, line:6:1> line:3:6 test 'void (void)' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:17, line:6:1> // CHECK-NEXT: `-OMPTargetDirective {{.*}} <line:4:1, col:19> // CHECK-NEXT: `-CapturedStmt {{.*}} <line:5:3> // CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: |-CapturedStmt {{.*}} <col:3> // CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-NullStmt {{.*}} <col:3> // CHECK-NEXT: | `-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target.c:4:1) *const restrict' // CHECK-NEXT: |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .global_tid. 'const int' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target.c:4:1) *const restrict' // CHECK-NEXT: |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition // CHECK-NEXT: | `-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: |-NullStmt {{.*}} <line:5:3> // CHECK-NEXT: `-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target.c:4:1) *const restrict'
GB_concat_full_template.c
//------------------------------------------------------------------------------ // GB_concat_full_template: concatenate an full tile into a full matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ { //-------------------------------------------------------------------------- // get C and the tile A //-------------------------------------------------------------------------- const GB_CTYPE *restrict Ax = (GB_CTYPE *) A->x ; GB_CTYPE *restrict Cx = (GB_CTYPE *) C->x ; int64_t pA ; #pragma omp parallel for num_threads(A_nthreads) schedule(static) for (pA = 0 ; pA < anz ; pA++) { int64_t i = pA % avlen ; int64_t j = pA / avlen ; int64_t iC = cistart + i ; int64_t jC = cvstart + j ; int64_t pC = iC + jC * cvlen ; // Cx [pC] = Ax [pA] ; GB_COPY (pC, pA) ; } done = true ; } #undef GB_CTYPE
GB_resize.c
//------------------------------------------------------------------------------ // GB_resize: change the size of a matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ #include "GB_select.h" #define GB_FREE_ALL GB_PHIX_FREE (A) ; GrB_Info GB_resize // change the size of a matrix ( GrB_Matrix A, // matrix to modify const GrB_Index nrows_new, // new number of rows in matrix const GrB_Index ncols_new, // new number of columns in matrix GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; ASSERT_MATRIX_OK (A, "A to resize", GB0) ; //-------------------------------------------------------------------------- // handle the CSR/CSC format //-------------------------------------------------------------------------- int64_t vdim_old = A->vdim ; int64_t vlen_old = A->vlen ; int64_t vlen_new, vdim_new ; if (A->is_csc) { vlen_new = nrows_new ; vdim_new = ncols_new ; } else { vlen_new = ncols_new ; vdim_new = nrows_new ; } //-------------------------------------------------------------------------- // determine the max # of threads to use here //-------------------------------------------------------------------------- // GB_selector (RESIZE) will use a different # of threads GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (vdim_new - vdim_old, chunk, nthreads_max) ; //-------------------------------------------------------------------------- // delete any lingering zombies and assemble any pending tuples //-------------------------------------------------------------------------- // only do so if either dimension is shrinking, or if pending tuples exist // and vdim_old <= 1 and vdim_new > 1, since in that case, Pending->j has // not been allocated yet, but would be required in the resized matrix. if (vdim_new < vdim_old || vlen_new < vlen_old || (GB_PENDING (A) && vdim_old <= 1 && vdim_new > 1)) { GB_MATRIX_WAIT (A) ; ASSERT_MATRIX_OK (A, "A to resize, wait", GB0) ; } //-------------------------------------------------------------------------- // check for early conversion to hypersparse //-------------------------------------------------------------------------- // If the # of vectors grows very large, it is costly to reallocate enough // space for the non-hypersparse A->p component. So convert the matrix to // hypersparse if that happens. if (A->nvec_nonempty < 0) { A->nvec_nonempty = GB_nvec_nonempty (A, Context) ; } if (GB_to_hyper_test (A, A->nvec_nonempty, vdim_new)) { GB_OK (GB_to_hyper (A, Context)) ; } //-------------------------------------------------------------------------- // resize the number of sparse vectors //-------------------------------------------------------------------------- bool ok = true ; int64_t *GB_RESTRICT Ah = A->h ; int64_t *GB_RESTRICT Ap = A->p ; A->vdim = vdim_new ; if (A->is_hyper) { //---------------------------------------------------------------------- // A is hypersparse: decrease size of A->p and A->h only if needed //---------------------------------------------------------------------- if (vdim_new < A->plen) { // reduce the size of A->p and A->h; this cannot fail info = GB_hyper_realloc (A, vdim_new, Context) ; ASSERT (info == GrB_SUCCESS) ; Ap = A->p ; Ah = A->h ; } if (vdim_new < vdim_old) { // descrease A->nvec to delete the vectors outside the range // 0...vdim_new-1. int64_t pleft = 0 ; int64_t pright = GB_IMIN (A->nvec, vdim_new) - 1 ; bool found ; GB_SPLIT_BINARY_SEARCH (vdim_new, Ah, pleft, pright, found) ; A->nvec = pleft ; } } else { //---------------------------------------------------------------------- // A is not hypersparse: change size of A->p to match the new vdim //---------------------------------------------------------------------- if (vdim_new != vdim_old) { // change the size of A->p A->p = GB_REALLOC (A->p, vdim_new+1, vdim_old+1, int64_t, &ok) ; if (!ok) { // out of memory GB_FREE_ALL ; return (GB_OUT_OF_MEMORY) ; } Ap = A->p ; A->plen = vdim_new ; } if (vdim_new > vdim_old) { // number of vectors is increasing, extend the vector pointers int64_t anz = GB_NNZ (A) ; int64_t j ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (j = vdim_old + 1 ; j <= vdim_new ; j++) { Ap [j] = anz ; } // A->nvec_nonempty does not change } A->nvec = vdim_new ; } if (vdim_new < vdim_old) { // number of vectors is decreasing, need to count the new number of // non-empty vectors, unless it is done during pruning, just below. A->nvec_nonempty = -1 ; // compute when needed } //-------------------------------------------------------------------------- // resize the length of each vector //-------------------------------------------------------------------------- // if vlen is shrinking, delete entries outside the new matrix if (vlen_new < vlen_old) { GB_OK (GB_selector (NULL, GB_RESIZE_opcode, NULL, false, A, vlen_new-1, NULL, Context)) ; } //-------------------------------------------------------------------------- // vlen has been resized //-------------------------------------------------------------------------- A->vlen = vlen_new ; ASSERT_MATRIX_OK (A, "A vlen resized", GB0) ; //-------------------------------------------------------------------------- // check for conversion to hypersparse or to non-hypersparse //-------------------------------------------------------------------------- return (GB_to_hyper_conform (A, Context)) ; }
mish_ref.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2020, OPEN AI LAB * Author: 942002795@qq.com */ #include <math.h> #include "sys_port.h" #include "module.h" #include "tengine_errno.h" #include "tengine_log.h" #include "tengine_ir.h" #include "../../cpu_node_ops.h" #include "tengine_op.h" int ref_mish_uint8(struct ir_tensor *input_tensor, struct ir_tensor *output_tensor, int num_thread) { int w = input_tensor->dims[3]; int h = output_tensor->dims[2]; int channels = input_tensor->dims[1]; int batch = input_tensor->dims[0]; int size = h * w; int c_step = h * w; int batch_step = c_step * channels; int total_size = batch_step * batch; // dequant uint8_t* input_uint8 = input_tensor->data; uint8_t* output_uint8 = output_tensor->data; float input_scale = input_tensor->scale; float output_scale = output_tensor->scale; int32_t input_zero = input_tensor->zero_point; int32_t output_zero = output_tensor->zero_point; float* data_fp32 = sys_malloc(total_size * sizeof(float)); for(int i = 0; i < total_size; i++) data_fp32[i] = ((float) input_uint8[i] - (float)input_zero) * input_scale; for (int n = 0; n < batch; n++) { //#pragma omp parallel for num_threads(num_thread) for (int q = 0; q < channels; q++) { float* src = data_fp32 + batch_step * n + c_step * q; float* dst = data_fp32 + batch_step * n + c_step * q; for (int i = 0; i < size; i++) { dst[i] = src[i] * tanhf(log(1 + exp(src[i]))); } } } // quant for(int i=0; i<total_size; i++) { int udata = round(data_fp32[i] / output_scale + output_zero); if (udata > 255) udata = 255; else if (udata < 0) udata = 0; output_uint8[i] = udata; } sys_free(data_fp32); return 0; } int ref_mish_fp32(struct ir_tensor* input_tensor, struct ir_tensor* output_tensor, int num_thread) { int w = input_tensor->dims[3]; int h = output_tensor->dims[2]; int channels = input_tensor->dims[1]; int size = h * w; int c_step = h * w; float* input_data = input_tensor->data; float* out_data = output_tensor->data; #pragma omp parallel for num_threads(num_thread) for (int q = 0; q < channels; q++) { float* src = input_data + c_step * q; float* dst = out_data + c_step * q; for (int i = 0; i < size; i++) { dst[i] = src[i] * tanhf(log(1 + exp(src[i]))); } } return 0; } static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { return 0; } static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { return 0; } static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* ir_node = exec_node->ir_node; struct ir_graph* ir_graph = ir_node->graph; struct ir_tensor* input_tensor; struct ir_tensor* output_tensor; input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]); output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]); int ret = -1; if(input_tensor->data_type == TENGINE_DT_FP32) ret = ref_mish_fp32(input_tensor, output_tensor, exec_graph->num_thread); else if(input_tensor->data_type == TENGINE_DT_UINT8) ret = ref_mish_uint8(input_tensor, output_tensor, exec_graph->num_thread); return ret; } static int reshape(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct ir_node* node = exec_node->ir_node; struct ir_graph* ir_graph = node->graph; struct ir_tensor* input = get_ir_graph_tensor(ir_graph, node->input_tensors[0]); struct ir_tensor* output = get_ir_graph_tensor(ir_graph, node->output_tensors[0]); int ret = set_ir_tensor_shape(output, input->dims, input->dim_num); return ret; } static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct ir_node* exec_node) { return OPS_SCORE_CANDO; } static struct node_ops hcl_node_ops = {.prerun = NULL, .run = run, .reshape = reshape, .postrun = NULL, .init_node = init_node, .release_node = release_node, .score = score}; static int reg_mish_hcl_ops(void* arg) { return register_builtin_node_ops(OP_MISH, &hcl_node_ops); } static int unreg_mish_hcl_ops(void* arg) { return unregister_builtin_node_ops(OP_MISH, &hcl_node_ops); } AUTO_REGISTER_OPS(reg_mish_hcl_ops); AUTO_UNREGISTER_OPS(unreg_mish_hcl_ops);
raytracer.h
#pragma once #include "resource.h" #include <linalg.h> #include <memory> #include <omp.h> #include <random> #include <time.h> using namespace linalg::aliases; namespace cg::renderer { struct ray { ray(float3 position, float3 direction) : position(position) { this->direction = normalize(direction); } float3 position; float3 direction; }; struct payload { float t; float3 bary; cg::color color; }; template<typename VB> struct triangle { triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c); float3 a; float3 b; float3 c; float3 ba; float3 ca; float3 na; float3 nb; float3 nc; float3 ambient; float3 diffuse; float3 emissive; }; template<typename VB> inline triangle<VB>::triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c) { a = float3{ vertex_a.x, vertex_a.y, vertex_a.z }; b = float3{ vertex_b.x, vertex_b.y, vertex_b.z }; c = float3{ vertex_c.x, vertex_c.y, vertex_c.z }; ba = b - a; ca = c - a; na = float3{ vertex_a.nx, vertex_a.ny, vertex_a.nz }; nb = float3{ vertex_b.nx, vertex_b.ny, vertex_b.nz }; nc = float3{ vertex_c.nx, vertex_c.ny, vertex_c.nz }; ambient = { vertex_a.ambient_r, vertex_a.ambient_g, vertex_a.ambient_b, }; diffuse = { vertex_a.diffuse_r, vertex_a.diffuse_g, vertex_a.diffuse_b, }; emissive = { vertex_a.emissive_r, vertex_a.emissive_g, vertex_a.emissive_b, }; } template<typename VB> class aabb { public: void add_triangle(const triangle<VB> triangle); const std::vector<triangle<VB>>& get_traingles() const; bool aabb_test(const ray& ray) const; protected: std::vector<triangle<VB>> triangles; float3 aabb_min; float3 aabb_max; }; struct light { float3 position; float3 color; }; template<typename VB, typename RT> class raytracer { public: raytracer(){}; ~raytracer(){}; void set_render_target(std::shared_ptr<resource<RT>> in_render_target); void clear_render_target(const RT& in_clear_value); void set_viewport(size_t in_width, size_t in_height); void set_per_shape_vertex_buffer( std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer); void build_acceleration_structure(); std::vector<aabb<VB>> acceleration_structures; void ray_generation(float3 position, float3 direction, float3 right, float3 up); payload trace_ray(const ray& ray, size_t depth, float max_t = 1000.f, float min_t = 0.001f) const; payload intersection_shader(const triangle<VB>& triangle, const ray& ray) const; std::function<payload(const ray& ray)> miss_shader = nullptr; std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> closest_hit_shader = nullptr; std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> any_hit_shader = nullptr; protected: std::shared_ptr<cg::resource<RT>> render_target; std::vector<std::shared_ptr<cg::resource<VB>>> per_shape_vertex_buffer; float get_random(const int thread_num, float range = 0.1f) const; size_t width = 1920; size_t height = 1080; }; template<typename VB, typename RT> inline void raytracer<VB, RT>::set_render_target(std::shared_ptr<resource<RT>> in_render_target) { render_target = in_render_target; } template<typename VB, typename RT> inline void raytracer<VB, RT>::clear_render_target(const RT& in_clear_value) { for (size_t i = 0; i < render_target->get_number_of_elements(); i++) { render_target->item(i) = in_clear_value; } } template<typename VB, typename RT> inline void raytracer<VB, RT>::set_per_shape_vertex_buffer( std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer) { per_shape_vertex_buffer = in_per_shape_vertex_buffer; } template<typename VB, typename RT> inline void raytracer<VB, RT>::build_acceleration_structure() { for (auto& vertex_buffer : per_shape_vertex_buffer) { size_t vertex_id = 0; aabb<VB> aabb; while (vertex_id < vertex_buffer->get_number_of_elements()) { triangle<VB> triangle( vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++)); aabb.add_triangle(triangle); } acceleration_structures.push_back(aabb); } } template<typename VB, typename RT> inline void raytracer<VB, RT>::set_viewport(size_t in_width, size_t in_height) { width = in_width; height = in_height; } template<typename VB, typename RT> inline void raytracer<VB, RT>::ray_generation( float3 position, float3 direction, float3 right, float3 up) { for (int x = 0; x < width; x++) { #pragma omp parallel for for (int y = 0; y < height; y++) { // from [0, width-1] to [-1, 1] float u = 2.f * x / static_cast<float>(width - 1) - 1.f; u *= static_cast<float>(width) / static_cast<float>(height); float v = 2.f * y / static_cast<float>(height - 1) - 1.f; float3 ray_direction = direction + u * right - v * up; ray ray(position, ray_direction); payload payload = trace_ray(ray, 1); render_target->item(x, y) = RT::from_color(payload.color); } } } template<typename VB, typename RT> inline payload raytracer<VB, RT>::trace_ray(const ray& ray, size_t depth, float max_t, float min_t) const { if (depth == 0) { return miss_shader(ray); } depth--; payload closest_hit_payload = {}; closest_hit_payload.t = max_t; const triangle<VB>* closest_triangle = nullptr; for (auto& aabb : acceleration_structures) { if (!aabb.aabb_test(ray)) continue; for (auto& triangle : aabb.get_traingles()) { payload payload = intersection_shader(triangle, ray); if (payload.t > min_t && payload.t < closest_hit_payload.t) { closest_hit_payload = payload; closest_triangle = &triangle; if (any_hit_shader) return any_hit_shader(ray, payload, triangle); } } } if (closest_hit_payload.t < max_t) { if (closest_hit_shader) { return closest_hit_shader(ray, closest_hit_payload, *closest_triangle); } } return miss_shader(ray); } template<typename VB, typename RT> inline payload raytracer<VB, RT>::intersection_shader(const triangle<VB>& triangle, const ray& ray) const { payload payload{}; payload.t = -1.f; float3 pvec = cross(ray.direction, triangle.ca); float det = dot(triangle.ba, pvec); const float eps = 1e-8f; if (abs(det) < eps) { return payload; } float inv_det = 1.f / det; float3 tvec = ray.position - triangle.a; float u = dot(tvec, pvec) * inv_det; if (u < 0.f || u > 1.f) { return payload; } float3 qvec = cross(tvec, triangle.ba); float v = dot(ray.direction, qvec) * inv_det; if (v < 0.f || (u + v) > 1.f) { return payload; } payload.t = dot(triangle.ca, qvec) * inv_det; payload.bary = float3{ 1.f - u - v, u, v }; return payload; } template<typename VB, typename RT> inline float raytracer<VB, RT>::get_random(const int thread_num, const float range) const { static std::default_random_engine generator(thread_num); static std::normal_distribution<float> distribution(0.f, range); return distribution(generator); } template<typename VB> inline void aabb<VB>::add_triangle(const triangle<VB> triangle) { if (triangles.empty()) aabb_max = aabb_min = triangle.a; triangles.push_back(triangle); aabb_max = max(triangle.a, aabb_max); aabb_max = max(triangle.b, aabb_max); aabb_max = max(triangle.c, aabb_max); aabb_min = min(triangle.a, aabb_min); aabb_min = min(triangle.b, aabb_min); aabb_min = min(triangle.c, aabb_min); } template<typename VB> inline const std::vector<triangle<VB>>& aabb<VB>::get_traingles() const { return triangles; } template<typename VB> inline bool aabb<VB>::aabb_test(const ray& ray) const { float3 inv_ray_direction = float3(1.f) / ray.direction; float3 t0 = (aabb_max - ray.position) * inv_ray_direction; float3 t1 = (aabb_min - ray.position) * inv_ray_direction; float3 tmin = min(t0, t1); float3 tmax = max(t0, t1); return maxelem(tmin) <= minelem(tmax); } } // namespace cg::renderer
GB_unaryop__ainv_fp64_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_fp64_uint8 // op(A') function: GB_tran__ainv_fp64_uint8 // C type: double // A type: uint8_t // cast: double cij = (double) aij // unaryop: cij = -aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, x) \ double z = (double) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_FP64 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_fp64_uint8 ( double *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_fp64_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_fc64_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_fc64_fp32) // op(A') function: GB (_unop_tran__identity_fc64_fp32) // C type: GxB_FC64_t // A type: float // cast: GxB_FC64_t cij = GxB_CMPLX ((double) (aij), 0) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FC64 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fc64_fp32) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fc64_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__isle_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isle_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__isle_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__isle_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__isle_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isle_uint64) // A*D function (colscale): GB (_AxD__isle_uint64) // D*A function (rowscale): GB (_DxB__isle_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__isle_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__isle_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isle_uint64) // C=scalar+B GB (_bind1st__isle_uint64) // C=scalar+B' GB (_bind1st_tran__isle_uint64) // C=A+scalar GB (_bind2nd__isle_uint64) // C=A'+scalar GB (_bind2nd_tran__isle_uint64) // C type: uint64_t // A type: uint64_t // A pattern? 0 // B type: uint64_t // B pattern? 0 // BinaryOp: cij = (aij <= bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x <= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISLE || GxB_NO_UINT64 || GxB_NO_ISLE_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isle_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isle_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isle_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isle_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isle_uint64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isle_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint64_t alpha_scalar ; uint64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ; beta_scalar = (*((uint64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isle_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isle_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__isle_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isle_uint64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isle_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = (x <= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isle_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = (aij <= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x <= aij) ; \ } GrB_Info GB (_bind1st_tran__isle_uint64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij <= y) ; \ } GrB_Info GB (_bind2nd_tran__isle_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
omp_single_nowait.c
<ompts:test> <ompts:testdescription></ompts:testdescription> <ompts:ompversion>2.0</ompts:ompversion> <ompts:directive>omp single nowait</ompts:directive> <ompts:dependences>omp critical,omp atomic</ompts:dependences> <ompts:testcode> #include <stdio.h> #include "omp_testsuite.h" int my_iterations; #pragma omp threadprivate(my_iterations) int <ompts:testcode:functionname>omp_single_nowait</ompts:testcode:functionname>(FILE * logFile) { <ompts:orphan:vars> int nr_iterations; </ompts:orphan:vars> int total_iterations = 0; int i; nr_iterations = 0; my_iterations = 0; #pragma omp parallel private(i) { for (i = 0; i < LOOPCOUNT; i++) { <ompts:orphan> <ompts:check>#pragma omp single nowait</ompts:check> { #pragma omp atomic nr_iterations++; } /* end of single*/ </ompts:orphan> } /* end of for */ } /* end of parallel */ #pragma omp parallel private(i) { my_iterations = 0; for (i = 0; i < LOOPCOUNT; i++) { <ompts:orphan> <ompts:check>#pragma omp single nowait</ompts:check> { my_iterations++; } /* end of single*/ </ompts:orphan> } /* end of for */ #pragma omp critical { total_iterations += my_iterations; } } /* end of parallel */ return ((nr_iterations == LOOPCOUNT) && (total_iterations == LOOPCOUNT)); } /* end of check_single_nowait*/ </ompts:testcode> </ompts:test>
matrix.c
#include <stdio.h> #include <omp.h> #define SIZE 1000 int a[SIZE][SIZE],b[SIZE][SIZE],res_seq[SIZE][SIZE],res_parallel[SIZE][SIZE]; void seq_matmul(int a[][SIZE],int b[][SIZE]) { int i,j,k; for(i=0;i<SIZE;++i) { for(j=0;j<SIZE;++j) { res_seq[i][j]=0; for(k=0;k<SIZE;++k) { res_seq[i][j] = res_seq[i][j] + a[i][k]*b[k][j]; } } } } void parallel_matmul(int a[][SIZE],int b[][SIZE],int NUM_THREADS) { int nthreads; omp_set_num_threads(NUM_THREADS); int i,j,k; #pragma omp parallel for private(i) for(i=0;i<SIZE;i++) { #pragma omp parallel for private(j) for(j=0;j<SIZE;++j) { int t_sum = 0; #pragma omp parallel for reduction(+:t_sum) private(k) for(k=0;k<SIZE;++k) { t_sum = t_sum + a[i][k]*b[k][j]; } #pragma omp critical { res_parallel[i][j] = t_sum; } } } } int check_eq_matrix() { for(int i=0;i<SIZE;++i) for(int j=0;j<SIZE;++j) if(res_seq[i][j] != res_parallel[i][j]) return 0; return 1; } int main() { int i,j; for(i=0;i<SIZE;++i) for(j=0;j<SIZE;++j) a[i][j]=b[i][j] = 1; double time_taken_serial = omp_get_wtime(),time_taken_parallel; seq_matmul(a,b); time_taken_serial = omp_get_wtime() - time_taken_serial; int NUM_THREADS=2; while(NUM_THREADS<=20) { time_taken_parallel = omp_get_wtime(); parallel_matmul(a,b,NUM_THREADS); time_taken_parallel = omp_get_wtime() - time_taken_parallel; if(check_eq_matrix()) printf("Speed up for %d threads is %lf\n",NUM_THREADS,time_taken_parallel/time_taken_serial); else printf("Parallel program gave wrong answer\n"); NUM_THREADS++; } }
test.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <omp.h> #include <cilk/cilk.h> // maximum value of n #define NMAX 75000000 //#define NMAX 200 #define CHUNKSIZE 20 typedef struct{ int lt; int gt; } flag; flag *flags; double *local; int size; // void printArray(int n){ // int j; // printf("["); // int t =0; // for(j = 0; j<n; j++){ // //if(j<10){ // if(t){ // printf(", %f", N[j]); // }else{ // t=1; // printf("%f", N[j]); // } // //} // } // printf("]\n"); // } double drand ( double low, double high ) { return ( (double)rand() * ( high - low ) ) / (double)RAND_MAX + low; } void fillArrayRandom(double *arr, int n){ int j; cilk_for(j = 0; j<n; j++){ double r = drand(0,1000); arr[j]=r; } } int cmpfunc (const void * a, const void * b) { if (*(double*)a > *(double*)b) return 1; else if (*(double*)a < *(double*)b) return -1; else return 0; } void swap(double *xp, double *yp){ double temp = *xp; *xp = *yp; *yp = temp; } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] // void merge(int l, int m, int r){ // int i, j, k; // int n1 = m - l + 1; // int n2 = r - m; // /* create temp arrays */ // int L[n1], R[n2]; // /* Copy data to temp arrays L[] and R[] */ // for (i = 0; i < n1; i++) // L[i] = N[l + i]; // for (j = 0; j < n2; j++) // R[j] = N[m + 1+ j]; // /* Merge the temp arrays back into arr[l..r]*/ // i = 0; // Initial index of first subarray // j = 0; // Initial index of second subarray // k = l; // Initial index of merged subarray // while (i < n1 && j < n2){ // if (L[i] <= R[j]){ // N[k] = L[i]; // i++; // }else{ // N[k] = R[j]; // j++; // } // k++; // } // /* Copy the remaining elements of L[], if there // are any */ // while (i < n1){ // N[k] = L[i]; // i++; // k++; // } // /* Copy the remaining elements of R[], if there // are any */ // while (j < n2){ // N[k] = R[j]; // j++; // k++; // } // } /* l is for left index and r is right index of the sub-array of arr to be sorted */ // void mergeSortHelper(int l, int r){ // if (l < r){ // int m = l+(r-l)/2; // // Sort first and second halves // mergeSortHelper(l, m); // mergeSortHelper(m+1, r); // merge(l, m, r); // } // } // double mergeSort(int n){ // double t1, t2; // #pragma omp master // t1 = omp_get_wtime(); // mergeSortHelper(0,n-1); // #pragma omp master // t2 = omp_get_wtime(); // return t2-t1; // } // double insertionSort(int n){ // int key, j, i; // double t1, t2; // #pragma omp master // t1 = omp_get_wtime(); // for (i = 1; i < n; i++){ // key = N[i]; // j = i-1; // while (j >= 0 && N[j] > key){ // N[j+1] = N[j]; // j--; // } // N[j+1] = key; // } // #pragma omp master // t2 = omp_get_wtime(); // return t2-t1; // } int partition(double *arr, int p, int r){ double key=arr[r]; int i=p-1; int j; double temp; for(j=p; j<r; j++){ if(arr[j]<=key){ i+=1; temp = arr[i]; arr[i]=arr[j]; arr[j]=temp; } } temp = arr[i+1]; arr[i+1]=arr[r]; arr[r]=temp; return i+1; } // void quickSortHelper(int p, int r){ // if(p<r){ // int q=partition(p,r); // #pragma omp task // { // quickSortHelper(p,q-1); // } // quickSortHelper(q+1,r); // } // } // double sequentialQuickSort(int n){ // double t1, t2; // #pragma omp master // t1 = omp_get_wtime(); // #pragma omp parallel // { // We only want our master thread to be executed once, thus we use the singel construct here. // nowait is used becuse we have no need for synchronization at the end of the region // #pragma omp single nowait // { // quickSortHelper(0, n-1); // } // } // #pragma omp master // t2 = omp_get_wtime(); // return t2-t1; // } void insertionSortHelper(double *arr, int p, int r){ double key; int j, i; for (i = p+1; i<r+1 ; i++){ key = arr[i]; j = i-1; while (j >= p && arr[j] > key){ arr[j+1] = arr[j]; j--; } arr[j+1] = key; } } void prefixSum(int arr[], int p, int r){ int i; for(i=p+1;i<r+1;i++){ arr[i]+=arr[i-1]; } } int log_2(int n){ int i=0; while(n >>= 1) {++i;} return i; } void parallelPrefixSum(int p, int r){ int len = r-p+1; int shift, j, h; int k = log_2(len); for(h=1; h<k+1;h++){ shift = 1<<h; // #pragma omp parallel for schedule(static) private(j) cilk_for (j=1; j<(len/shift)+1;j++){ flags[p+j*shift-1].lt+=flags[p+j*shift-(shift/2)-1].lt; flags[p+j*shift-1].gt+=flags[p+j*shift-(shift/2)-1].gt; } } for(h=k; h>-1;h--){ shift = 1<<h; // #pragma omp parallel for schedule(static) private(j) cilk_for (j=2; j<(len/shift)+1;j++){ if(j%2==1){ flags[p+j*shift-1].lt+=flags[p+j*shift-shift-1].lt; flags[p+j*shift-1].gt+=flags[p+j*shift-shift-1].gt; } } } } int parallelPartition(double *arr, int p, int r){ // printf("p %d r %d\n", p, r); double key=arr[r]; int i,j; double temp; // printf("%d: before first parallel region\n",omp_get_thread_num()); //#pragma omp for schedule(static) private(i) cilk_for (i=p; i<r+1; i++){ flags[i].lt=0; flags[i].gt=0; local[i]=arr[i]; } //#pragma omp for schedule(static) private(i) cilk_for (i = p; i <r; i++){ if(arr[i]<key){ flags[i].lt=1; flags[i].gt=0; }else{ flags[i].lt=0; flags[i].gt=1; } } // printf("before less than: ["); // for(i=p; i<r+1; i++){ // printf("%d, ", lt[i]); // } // printf("]\n"); // printf("before greater than: ["); // for(i=p; i<r+1; i++){ // printf("%d, ", gt[i]); // } // printf("]\n"); // printf("%d: before prefix sum\n",omp_get_thread_num()); parallelPrefixSum(p,r); // prefixSum(lt, p,r); // prefixSum(gt,p,r); // printf("%d: after prefix sum\n",omp_get_thread_num()); //prefixSum(lt, gt, p, r); // printf("after less than: ["); // for(i=p; i<r+1; i++){ // printf("%d, ", lt[i]); // } // printf("]\n"); // printf("after greater than: ["); // for(i=p; i<r+1; i++){ // printf("%d, ", gt[i]); // } // printf("]\n"); int pivot = flags[r].lt; // printf("pivot point is %d\n",pivot); arr[pivot+p]=key; //#pragma omp for schedule(static) private(i) cilk_for (i=p; i<r; i++){ if(local[i]<key){ int index = p+flags[i].lt-1; arr[index]=local[i]; }else{ int index = p+pivot+flags[i].gt; arr[index]=local[i]; } } // printf("%d: after second parallel\n", omp_get_thread_num()); return pivot+p; } void psqHelper(double *arr, int p, int r){ int q; if(p<r){ if(r-p<=50){ insertionSortHelper(arr, p,r); }else{ if(r-p < 0.5*size){ q = partition(arr,p,r); }else{ q=parallelPartition(arr,p,r); } // printf("left p: %d left r: %d\n", p, q-1); // printf("right p: %d right r: %d\n", q+1, r); cilk_spawn psqHelper(arr,p,q-1); psqHelper(arr,q+1,r); } } } double parallelQuickSort(double *arr, int n){ double t1, t2; flags = malloc(sizeof(flag)*n); local = malloc(sizeof(double)*n); int i; cilk_for(i=0; i<n; i++){ local[i]=0; flags[i].lt=0; flags[i].gt=0; } #pragma omp master t1 = omp_get_wtime(); // #pragma omp parallel // { // We only want our master thread to be executed once, thus we use the singel construct here. // nowait is used becuse we have no need for synchronization at the end of the region // #pragma omp single nowait // { psqHelper(arr, 0, n-1); // } // } #pragma omp master t2 = omp_get_wtime(); return t2-t1; } // double selectionSort(int n){ // int j, min_idx,i; // double t1,t2; // #pragma omp master // t1 = omp_get_wtime(); // // One by one move boundary of unsorted subarray // for (i = 0; i < n-1; i++){ // // Find the minimum element in unsorted array // min_idx = i; // for (j = i+1; j < n; j++){ // if (N[j] < N[min_idx]){ // min_idx = j; // } // } // double temp = N[i]; // N[i] = N[min_idx]; // N[min_idx]=temp; // } // #pragma omp master // t2 = omp_get_wtime(); // return t2-t1; // } int checkArray(double *arr, int n){ int j; for(j = 0; j<n-1; j++){ if(arr[j]>arr[j+1]){ return -1; } } return 0; } // void tester(int n){ // srand(getpid()); // fillArrayRandom(n); // printArray(n); // double t = parallelQuickSort(n); // printArray(n); // } int main(int argc, char * argv[]){ FILE* fp = fopen("simTimes.csv","w+"); int len=15; //int len=5; int n[] = {10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000,20000,200000,2000000,20000000,75000000}; int i; srand(getpid()); //tester(10); for(i = 0; i<len; i++){ size = n[i]; double *arr = malloc(sizeof(double)*n[i]); fillArrayRandom(arr, n[i]); //printf("Before for array of size %d:\n", n[i]); //printArray(n[i]); double t = parallelQuickSort(arr, n[i]); printf("%d elements sorted in %f time\n", n[i], t); if(checkArray(arr, n[i])==-1){ printf("SORT FAILED\n"); }else{ printf("SUCCESSFUL SORT\n"); } //printf("after for array of size %d:", n[i]); //printArray(n[i]); } fclose(fp); }
data45.h
// The data are synthesized. #ifndef _DATA_H_ #define _DATA_H_ #pragma omp declare target const int NODE_N=45; const int STATE_N=2; const int DATA_N=600; int data[DATA_N*NODE_N]={ 1,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,1,1,0,1,1,0,1,0,1,0,0,0,0,0,1,0,1,0,0,1,1, 1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,1,0,0,0,1,1,0,0,1,1,1,1,0,0,1,0,1,0,0,1,0,0,1,0,0, 1,1,0,1,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,1,1,0,0,0,1,0,1,1,0,0,1,1,1,1,0,1,1,0, 1,1,1,0,1,0,1,0,0,0,0,1,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,1,1,1,0,1,1,0,1,0,1,0,1,0, 1,0,0,1,1,0,0,1,0,0,0,1,0,1,1,1,1,0,1,0,0,0,0,1,1,1,0,1,0,1,0,1,0,0,0,1,0,1,1,1,1,0,0,0,1, 1,0,0,0,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,1, 1,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,1,0,0,0,0,1,0,1,1, 1,0,0,1,0,0,0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,0,1, 1,0,1,1,1,0,0,0,1,1,1,0,1,1,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,1,1,0,0,1,0,0,1,0,1,1,0,1, 1,1,1,1,1,0,1,1,0,1,0,1,1,1,0,0,0,0,0,1,1,1,1,0,1,0,0,0,1,1,0,1,0,1,1,0,1,0,1,0,1,0,1,1,0, 1,0,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0, 1,0,0,1,0,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,1,1,0,1,0,1,0, 1,0,0,0,0,0,1,0,0,0,0,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1, 1,0,0,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,1,1,0,0,1,0,0,0,1,0,1,1,1,0,1,0,1,0,1,0,0,1,0,0,1,1,0, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,0,1,0,0,1,1,0,1,1,0,1,1,1,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,1,1,1, 1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,1,1,1,0,1,0,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0, 1,0,1,1,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,0,1,1,0,0,1,0,1,1,1,0,1,1,1,0,0, 1,1,1,1,0,1,1,0,0,0,0,1,1,0,0,1,1,1,0,1,0,0,1,0,1,1,1,0,1,0,1,0,0,0,1,0,1,1,0,1,1,1,1,1,1, 1,1,1,0,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,0,1,1,0,1,1,0,1,1,0,0,1,0,1,0,0,0,0,1,1,0,0,0,1,0,0, 1,1,1,1,0,0,1,0,1,0,1,1,1,0,0,1,0,1,0,0,1,1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,0,0,1,0,1,1,0,1,1, 0,1,0,1,1,1,1,1,0,1,0,1,1,1,1,0,1,1,0,0,1,1,1,0,1,0,0,0,0,1,1,0,1,1,1,1,1,1,0,1,1,1,0,1,0, 1,1,0,0,0,0,1,1,0,1,1,1,0,0,1,1,1,1,0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,0,1,0,1,1,1,1,1,1,0,1,1, 1,1,1,1,0,1,1,1,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,1,0,0,1,1,1,0,1,1,0,0,1,0,1,0,1,1,1,0,0,0,0, 0,1,1,1,1,0,0,1,1,1,1,0,0,1,0,0,0,1,0,1,1,1,0,1,1,0,0,0,1,0,0,1,0,1,0,0,0,1,1,0,1,0,1,1,1, 1,0,1,1,0,1,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,1,1,0,1,0,0,1,0,0, 1,0,1,1,0,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,1,1,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1, 1,0,0,0,0,0,1,1,0,1,0,1,0,0,1,0,0,1,0,1,0,0,0,0,1,1,0,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,1,1,1, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,1,1,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1,1,0,0, 1,1,0,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,1,0,1,1,0,1,0,1,0,0,1,0,0,1,0,0,0,0,1,1,0,0,1,1,0,1, 1,0,0,1,0,1,1,1,0,0,0,0,1,1,1,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1, 1,0,1,0,0,1,1,1,1,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1,0,0,1,0,1,0,1,0,0,0,0,0,0,1,1,1,1, 1,1,0,1,1,0,1,1,0,1,0,1,1,0,1,1,0,1,1,0,0,1,1,0,1,1,0,0,1,0,0,1,1,1,1,1,1,0,1,0,0,0,1,0,0, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,1,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0, 0,0,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,0,1,0,0,0,0,1,0,0,1,0,0, 1,1,0,1,0,0,1,0,0,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,0,0,0,1,0,1,0, 0,0,1,1,1,1,1,1,0,0,1,1,0,1,0,1,0,0,1,0,1,0,0,1,1,1,0,0,1,1,0,0,0,1,1,0,1,1,0,0,1,1,1,1,1, 1,1,1,0,1,1,0,0,1,0,0,1,0,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,1,0,0,1,1,0,0,0,1,1,1,0,0,0,1,0,0, 1,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,0,1,1,0,0,1,1,0,1,1,1, 1,0,0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,0,0, 1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,0,1,0,0,1,0,0,0,0,1, 1,0,0,0,0,1,0,1,1,1,0,0,1,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,1,0,0, 1,1,0,0,1,0,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,1,0,1,1,1,0,0,0,1,0,1,0,1,0,1,1,1,1,1,0,0,0,1, 1,1,1,1,1,1,0,1,1,1,0,1,1,1,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,1,0,0, 1,1,0,1,0,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,1,1,1,0,1,0,1,0,1,1,1,1,1,0,0,0,1,1,0,0,0,0,1,0,1, 1,1,1,0,0,0,1,1,1,1,1,0,0,0,1,0,1,1,0,1,1,0,1,1,0,1,1,0,0,0,0,0,0,0,1,0,1,0,0,0,1,1,0,1,1, 1,0,0,1,1,0,1,0,0,1,0,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0, 1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,1,0,1,1, 0,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,0,1,0,1,1,1,1,0,0,0,0,0,0,1,1,0,1,0,1,0,0,0,1,1,1,1,1,0,0, 1,1,1,1,0,1,1,1,1,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,1,1,0,0,1,1,1,0,0,1,1,1,1,1,0,1,1,1,0,1,0, 1,1,0,1,0,0,1,1,0,1,1,1,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,0,1,1,0,0,1,0,0,0,0,0,1,0,1,0, 1,1,0,0,0,0,1,1,0,0,0,0,1,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,1,1,1,0,1, 1,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,1, 1,1,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,1,0,1,1,0,1,1,1,0,0,0,1,0,1,0,0,0,0,0,1,1,0,1,1,0,1, 1,0,0,1,0,0,1,0,0,1,0,1,0,1,1,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,1,0,1,0,0,0,0,0,1,1,0,0,1,1,0, 0,1,1,0,0,1,0,1,1,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,1,0,0,1,1,0, 1,1,1,1,0,0,1,0,0,0,0,1,1,0,0,1,0,1,1,0,0,1,1,0,1,0,1,0,0,1,0,0,1,0,1,0,1,1,0,0,0,0,1,0,0, 1,1,1,1,0,1,1,0,1,0,0,1,1,1,0,1,1,1,0,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1, 1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,0,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,1,0,1,0,1,1,0,1,1,1,0,1,1, 1,1,0,1,0,1,0,0,1,0,0,1,0,1,0,1,0,0,1,1,1,0,0,1,0,0,1,1,1,0,0,0,1,0,1,0,1,1,0,1,0,0,1,1,1, 1,0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,1,1,0,0,1,0,0,0,0,0,0,1,0,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,1, 1,0,1,1,0,0,0,1,1,0,0,1,0,1,1,1,1,0,1,0,0,0,0,1,1,0,1,1,1,0,0,0,1,0,1,0,1,1,0,1,1,1,1,0,1, 1,1,0,1,0,1,0,0,1,0,1,0,0,0,0,0,1,0,0,1,0,0,1,1,0,0,0,1,0,0,0,1,0,1,0,1,1,1,1,1,1,1,0,1,1, 1,0,0,1,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,1,0,1, 0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,0,1,0, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,1,1,0,1,0,1,1, 0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,1,1,0,1,0,1,0,1,0,0,1,0,0,0,1,0, 1,0,1,0,1,1,0,1,1,1,0,1,1,1,1,1,1,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,0,1,1, 1,0,0,1,0,1,0,1,1,0,1,1,0,1,1,0,1,1,0,0,0,0,0,1,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,0,0, 1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,0,1,0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,0,1,0,0,0,1,1,0,1,0, 0,1,1,1,1,1,1,1,0,1,0,1,1,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,1,1,1,1,1,0,0,1,1,0,1,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0,0,1,1,0,1, 1,1,0,1,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,1,0,1,1,1,1,0,0,1,1,0,0,1,0,1,1,1,0,1,0,1,1,0,1,1,1, 1,1,0,1,0,0,1,1,0,1,1,0,0,1,1,1,0,1,1,1,0,0,0,1,1,1,1,0,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,0, 1,0,0,1,0,1,1,0,0,1,1,1,0,0,1,0,0,1,0,1,0,1,1,0,1,0,1,1,0,0,0,0,1,1,1,1,1,0,0,1,0,1,1,0,0, 1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,0,1,0,0,1,1,0,1,0,0,1,0,1,0,1,1,1,1,0,0,1,1,0,1,0,0,0,1,1, 0,0,1,1,1,0,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0,0,0,1,1,0,1,0,1,1,0,1,1,1,0,1,0,0,0,0, 1,1,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,1,0,1,1,1,0,0,0, 1,0,1,1,0,0,0,1,1,0,0,1,0,1,1,1,1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,1, 1,1,0,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,0,0,1,1,0,0,1,0,1,1, 1,1,0,0,0,0,1,1,0,0,1,1,1,0,1,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,0,1,0,0,1,0,0,1,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,1,0,0,1,0,0,1,1,1, 0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,1,1,0,1,1,1,1,0,0,1,1,0,1,0,0,1,0,1,1,1,0,0,1,0,1, 1,0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,1,0,0, 1,0,1,0,0,1,0,1,1,1,0,0,1,1,1,1,1,1,0,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1, 1,1,1,1,0,1,1,1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,1,1,0,0,1,1,1,1,1,0,1,0, 1,1,1,0,0,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,1,0,0,1,1,1,1,1,1,0,1,1,0,0,1,0,1, 1,0,0,1,0,0,0,1,1,0,0,0,0,1,0,1,1,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,0,1,0,1,1,0,1,0,0,1,0,1, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,1,1,1,1,0,1,0,1,0,1,1,0,0,1,1, 0,1,1,1,1,1,1,1,0,1,1,0,1,1,0,0,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,1,0,1,1,0,1,0,1,0,0,0,1,1,0, 1,1,1,0,0,1,1,0,1,0,0,0,1,1,0,0,0,1,1,1,1,1,1,0,0,0,1,0,1,1,1,1,1,1,0,1,1,1,0,1,1,1,0,1,0, 1,1,1,1,1,0,1,1,0,1,0,1,1,1,0,0,0,0,1,0,1,0,1,0,1,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,1,0,0,0,0, 0,1,1,1,0,1,1,1,0,1,0,1,0,1,0,1,1,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0, 1,0,1,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,1,0,0, 1,1,0,1,0,1,1,1,0,1,1,0,0,0,1,0,0,1,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,1,0,1,1,1,1, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,1,1,0,1,0,0,1, 1,1,0,1,1,1,0,1,0,1,0,0,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,0, 1,1,1,1,0,0,1,0,0,0,0,1,1,0,0,0,1,1,1,1,0,1,1,0,1,0,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0,1, 1,0,0,1,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,0,1,0,0,1,1,1,1,1,1,0,1,0,1,1,0,1,0,0,1,0,1,0,0,1,1, 1,0,0,0,1,1,0,1,0,1,0,1,0,0,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,0,1,1,0,1,1,1,1,0,1,0,1,1,0,1, 0,1,0,1,1,0,1,1,0,1,0,0,1,1,1,0,0,1,0,0,1,0,1,0,0,0,0,0,0,1,1,1,0,1,0,1,0,0,1,1,1,0,0,1,0, 1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,0,1,1,1,1,1,1,0,0,1,1,0,0,0,1,1,0,1,1,0,1,0,1,1,1,0,0,1,1,0, 1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,0,0,1,1,1, 1,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,1,1,1,0,1,1,1,0,0,0,1,1,0,1,0,0,0,0,1,1,0,1,0,1,1,1,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,1,1,0,1,1,1,0,0,0,0,1,1,0,1,1,1,0,0,1,0,0,0,0,0,1,0,1,1,0,1,0, 1,0,0,0,0,0,1,0,0,0,1,1,1,0,1,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,1,1,0,1,0,0,0,1,1,0,0,1,1,1, 0,1,1,1,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,1,1,0,1, 1,1,0,1,0,0,1,1,0,1,1,0,0,1,1,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,0,1,0,1,1,1,1,1,0,0,0,0,0,1,0, 1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,1,0,1,1,0,1,1,1,0,1,1,0,0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0, 1,1,0,1,1,1,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,1,0,0,1,0,0,1,1,0,1,0,0,1,0,0,0,1,0,1,0,1,0, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,1,1,0,0,1,1,0,1,1,1,1,1,1,1,0,1,1,0,0,1,1,0,0,0,1,0,1,0,0,0,1, 1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,1,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,0,1,1,1,1,0,1,0,1,0,1,0,0, 1,1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,0,1,1,0,0,0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,1,1,0,1,1,1,1, 1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,1,1,1,0,1, 1,1,1,1,0,1,1,1,1,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,1,1,1,0,0,1,0,0, 1,0,0,0,1,1,1,1,0,1,0,1,1,0,0,0,1,1,0,0,1,1,0,0,1,0,0,0,1,0,0,0,1,1,0,0,0,1,1,0,1,1,1,1,0, 1,1,1,0,1,1,1,0,0,0,0,1,0,1,0,1,0,0,1,1,0,1,1,0,1,1,1,0,0,0,1,0,0,0,1,0,1,1,0,1,1,1,0,1,0, 1,1,1,1,1,0,0,0,1,0,0,1,0,1,1,0,1,0,1,0,1,0,0,1,0,1,1,1,0,0,1,1,1,1,0,1,1,1,0,0,1,1,1,0,0, 1,1,1,1,1,1,0,0,1,0,1,1,0,0,0,1,1,0,0,1,0,0,1,1,1,1,0,1,0,1,0,1,1,0,0,1,1,0,0,1,1,1,0,1,0, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,1,1,0,1, 0,1,0,1,0,0,1,1,0,1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,1,1,0,1,1,1,0,0,0,1,1,0,0,0,1,1,1,0,1,0,0, 1,1,1,1,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0,0,0,0,1,0,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,0,1, 0,1,0,1,1,1,0,1,0,1,0,0,1,1,0,0,1,0,1,1,1,0,1,1,0,0,1,0,0,1,1,1,0,0,1,1,1,0,0,0,1,1,0,1,1, 1,0,0,1,0,0,1,0,0,1,1,1,0,0,1,1,0,1,0,0,0,1,0,1,1,1,1,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0, 0,1,0,1,1,1,0,0,0,0,0,0,0,1,1,0,1,0,1,1,0,1,1,1,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,1,0,1,1,0,1, 1,0,0,1,0,1,1,1,0,0,0,0,1,0,0,1,1,1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,1,1,0,1,0,1,1,0,0,0,0,1,1, 1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,1, 1,1,1,1,0,1,1,1,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,1,1,1,0,1,0,0, 1,1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,0,1,0,1,0,1,1,0,0,0,1,0,1,1,1,1,1,0,0,0,1,1,0,0,1,0,0,1,0, 1,0,1,1,0,0,0,0,1,1,1,1,1,1,1,0,1,1,0,0,0,0,1,1,0,1,0,1,0,1,1,1,1,0,0,0,1,0,0,1,1,0,0,0,0, 1,1,1,0,0,1,1,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,1,1,0,0,1,0,0,1,0,1,1,1,1,1,0,1,0,0,1,0,1, 1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,0,0,0,1,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,1,1,0,1,1, 1,0,0,1,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,1,1,0,0,0,0,0,1,0,0,1,0,0,1,0,1,0,1,1,0,1,0,1,1,1, 1,1,0,1,0,0,1,1,0,1,1,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,1,0,0,0,1,0,1,1,0,1,0,1,0,0,0,1,0,0, 1,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,0,1,1,1,0,1,0,1,1,0,0,0,0,1,1,0,1,1,0,0,1,1, 1,1,0,0,0,0,1,0,0,0,0,1,1,0,0,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,1,0,0,1,1, 1,1,0,1,1,1,0,1,0,1,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,1, 1,1,1,1,0,0,1,1,0,1,0,0,0,1,1,0,0,1,1,1,1,0,1,0,0,1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0, 1,0,1,0,0,1,1,1,0,1,0,1,0,1,1,0,1,0,0,0,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,1,0,1,0,1,1,0, 1,0,0,0,0,0,0,1,1,1,1,0,1,0,1,0,1,1,0,0,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,0, 0,1,1,1,1,0,0,1,1,1,0,0,1,1,1,0,1,0,1,0,1,1,0,1,1,0,1,1,1,0,0,1,0,0,1,0,1,0,1,0,0,1,0,1,1, 1,1,1,1,0,0,1,1,1,1,0,1,0,0,1,1,0,1,1,0,0,0,1,0,1,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,0,1,0,0, 0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,0,1,0,1,0,0,1,1,0,1,0,1,0,0,0,0,1,1,1,1,0,0,1,0,1,1,0,1, 1,0,0,1,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,1,1,0,0,1,1,0,1,1,1,0,1,0,1,0,1,0,1,0,0,1,1,0,1,1, 1,1,1,1,0,1,1,1,1,1,0,1,0,0,0,1,0,1,1,0,1,1,1,0,1,1,0,0,1,0,0,1,1,0,0,0,0,0,1,0,0,0,1,1,1, 1,0,0,1,0,0,0,0,1,1,0,1,1,1,1,1,1,0,1,0,1,0,0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0, 1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,1,1,1,0,0,1, 1,1,1,0,0,0,0,0,1,0,0,1,0,1,1,0,1,1,0,0,0,1,1,0,1,0,1,0,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,1,0, 1,0,1,0,0,0,0,1,1,1,1,0,1,0,1,1,1,0,1,0,1,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,1,0,1,1,0,1, 1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,1,1,0,0,1,0,1, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,1,1, 0,0,0,0,1,1,1,1,0,1,0,0,1,1,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,1,1,1,0,1,0, 1,1,0,1,1,0,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,1,0,1,1,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1, 0,1,1,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,0,1,1,1,1,0, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1,0,1,1,0,1,0,0,1,1,1,1,0,0, 0,1,1,0,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,1,0,0,0,1,0,1,1,1,1,0,0,1,0,1,1,1,0,0,1,1,1,0,0,1,1, 1,1,0,1,0,0,0,0,1,0,0,1,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0,1,1,1,1,0,0,0,1, 1,1,1,1,0,0,1,1,0,1,0,1,0,1,0,1,1,1,0,0,0,1,1,0,1,0,0,0,1,1,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0, 1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,1,0,1,0,1,1,1,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,1,1,0,1,0, 1,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,1,0,1,0,0,0,1,0,0,1,0,1,0,1,0,1,0,1,1,0,1,1,0,1,1,1,0,1,0, 1,1,0,1,1,0,1,1,0,1,0,0,1,1,1,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,1,0,1,0,1,0,1,0,1,0,1,0,0,0,0, 1,0,1,0,0,0,0,0,1,0,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,1,1,1,0,0, 0,1,1,0,1,0,1,0,0,0,0,1,0,1,0,0,0,1,0,1,1,0,1,0,1,0,1,0,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,1,1, 1,1,0,1,1,0,1,0,0,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,1,1,1,0,0,0,1,0,1,0,1,0,1,0,0,0,0,0,0,1,0, 1,1,0,1,0,1,1,1,0,1,0,0,0,0,1,0,1,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,1,0,1,1,0, 1,1,0,1,0,0,0,0,1,0,0,1,0,1,0,1,1,1,0,0,1,1,1,0,1,1,1,0,1,0,1,1,0,0,1,0,0,1,1,0,1,0,1,1,1, 1,0,1,0,0,0,0,1,1,1,0,1,1,1,1,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,0,1,0,0,0,0,1,1,1,0,0,1,0,1, 1,0,1,1,0,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,1,1,1,1, 1,1,1,1,1,0,0,1,1,1,1,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,1,0,1,0,0,1,1,1,0,0, 0,1,1,1,1,1,1,1,0,1,0,0,1,1,1,0,0,0,0,1,1,0,0,0,1,1,0,1,1,0,0,0,1,0,0,0,0,1,0,1,0,0,1,0,0, 1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,1,0, 1,1,1,1,1,0,1,0,0,0,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,0,0, 0,1,1,1,0,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,0,1,0,1,1,1,0,1,0,1,0,1,0,1,1, 1,0,0,0,0,0,0,0,1,0,0,1,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,1,0,1, 1,0,1,0,1,0,0,1,1,1,0,0,1,0,1,0,0,0,1,1,1,0,0,1,0,1,0,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,1,0,0, 1,0,1,1,1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,1,0,0,1,1,0,1,1,0,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1, 1,1,1,1,1,0,1,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,1,1,1,1,0,1,1,0,1,1,1,0,1,1,0,1, 0,0,0,1,1,0,0,1,0,0,0,1,0,1,1,1,0,0,1,0,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,1,1, 1,1,1,1,1,0,0,1,1,1,0,0,0,1,1,0,1,0,0,0,1,0,0,0,1,0,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,1, 1,1,0,1,0,1,1,1,0,1,1,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0,1,0,1,0,1,0,1,1,0,0,0,0,0,1,1, 1,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,1,0,0,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,0,0,0,1,1,1,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,0,1,1,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,0,0,1,0,1,1,0,1,1,1,1,1,0, 1,0,0,1,0,0,1,0,0,1,0,0,0,1,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,1,0,1,1,0,0,0,1,1, 1,1,1,1,0,1,1,0,0,0,0,1,1,1,0,1,0,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1,0,1,1,0,0,0,1,1,1,0,1,0,1, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0,1,0,0,1,0,0,1,0,0, 1,1,0,1,0,0,1,0,0,0,1,1,1,1,1,0,1,1,1,0,0,0,0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,1,1,1,0,1,1, 1,1,0,1,1,0,1,1,0,1,0,0,1,1,1,0,0,1,1,0,0,1,0,0,1,1,0,1,1,0,1,1,0,0,1,0,1,1,1,1,1,0,0,1,1, 1,1,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,1,1,0,1,0,1,1,0,0,0,1,1,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,0,0,1,0,1,1,0,0,1,1,0,1,1,1,0,0,0,0,0,1,1,1,0,1,1,0,1,0,1,1,0,1, 1,1,0,1,0,1,1,1,0,1,0,1,0,0,1,0,0,1,0,0,0,1,1,0,1,0,0,0,1,1,1,1,1,0,1,0,1,1,0,0,1,1,0,1,0, 1,0,0,1,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,0,1,1,0,1,0,1,1,1,0,1,0,1,0,0,1,1,0,0,1,0,0, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,0,0,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,1,1,0,1,0,1,1,0,0,0,1,0,0, 1,1,0,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,1,1, 1,1,0,1,0,0,1,1,0,1,1,0,0,1,1,1,0,0,1,0,1,1,0,1,1,1,1,0,0,1,1,0,0,0,1,1,0,0,0,0,1,1,0,1,1, 1,0,0,1,0,0,1,1,0,0,0,0,1,0,0,1,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,0,0,0,1,0, 1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0,1,0,0,0,1,1,1,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,1,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,0,0,1,1,0,0,1,0,1,0,1,1,1,0,1,0,1,0,1,1,0,1,0,0,0,1,0,1,1,0,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,0,1,0,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0,1,1,1,0,0,1,0,1, 1,1,1,0,0,1,1,1,0,0,0,0,1,0,1,0,0,1,1,0,1,1,0,0,1,1,0,0,1,1,0,1,1,0,1,0,1,0,1,1,0,0,1,1,0, 1,0,1,1,0,1,1,1,0,0,1,0,1,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,0,0,1,0,1,1,0,1,0,1,1,0,0,1,0,0, 1,0,0,1,0,1,0,1,1,0,1,1,0,1,1,0,0,1,0,0,1,1,0,1,1,0,0,0,1,0,0,1,1,1,1,0,1,1,0,0,0,0,1,1,1, 1,1,0,1,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,1,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,1,1,1, 1,0,0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,0,1,0,1,0,1,1,1,1,0,0,1,0,0,1,0,1,1,1,0,1,1,1,0,0,1,0,1, 1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,1,1,0,1,0,0,0,1,0,1,1,1,0,1,1,0,0,0, 1,1,0,1,1,1,0,0,0,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,0,0,1,1,0,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,1, 0,1,0,1,1,1,1,0,0,0,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,1,0,0,1,1, 1,1,0,1,0,0,1,0,0,0,1,0,1,1,1,0,0,1,0,0,0,0,0,1,1,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,0,1,1,1,0, 1,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,1,1,0,0,1,0,0,1,0,0,1,1,0,1,0,0,0,1,0,1,1,1,1,0,1,1,0,1, 1,0,0,1,0,0,1,1,0,0,1,1,1,0,1,0,1,0,1,1,0,0,1,1,1,1,1,1,1,1,0,0,0,1,1,0,0,0,1,0,1,1,0,0,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,1,1,0,1,1,1,0,0,0,0,0,1,0,1,0,1,1,0,1,0,1,0,1,1, 1,1,1,0,1,0,1,0,0,0,1,1,0,1,1,1,0,1,0,0,1,0,0,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,0,0,1,1,0, 1,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,0,0,0, 1,1,1,0,1,1,1,1,0,1,1,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,1,0,0,1,1,1,0,0,0,0,0, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,1,0,0,1,1,0,0,0,0,1,0,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,0,1,1,0,1, 1,0,0,1,0,1,0,1,1,0,1,1,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,1,0,1,0,0,0,0,0,0,1,1,0,1,0,0,1,1, 0,1,1,1,1,0,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0,0,0,0,1,0,1,0,0,0,1,1,0,0,0,0,1,0,0,0,1,1,0,1, 1,1,0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,0,0,1, 1,0,1,0,0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,1, 1,1,1,1,0,0,1,0,1,0,0,1,1,0,1,1,0,1,0,0,0,0,0,0,0,1,0,1,0,0,1,1,1,0,0,0,1,1,0,1,0,0,1,0,1, 1,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1, 1,0,0,1,0,1,0,1,1,0,0,1,0,1,1,1,1,1,0,0,1,1,1,0,1,0,0,0,1,1,0,1,0,1,1,1,1,1,0,0,1,1,1,0,1, 0,1,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,1,0,0,1,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,1, 1,1,0,1,1,1,1,1,0,1,1,0,1,0,1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0, 1,1,0,1,0,0,1,1,0,1,1,0,0,1,1,1,1,0,1,1,0,1,1,1,0,0,1,1,0,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,1, 0,0,1,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,1,0,0,0,0,1,0,1,0,1,0,1,1,1,1,0,0,0,1,1,1,0,0,1,0, 1,1,1,1,0,0,1,0,1,0,0,1,1,1,1,0,0,1,0,0,0,0,1,0,1,0,1,0,0,1,0,1,1,0,0,0,1,1,0,1,1,0,0,0,0, 1,1,1,1,0,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,0,1,1,0,0,0,0, 1,1,0,1,0,0,1,0,0,0,1,0,1,1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,1,0,1,0,1,0,1,1,1,0,1,1,1,1,1, 1,1,0,0,0,0,1,0,0,0,1,1,1,0,0,1,0,1,0,0,1,1,1,1,1,1,0,1,1,1,1,0,1,0,0,0,0,1,1,0,1,1,1,1,0, 1,1,1,1,0,0,1,1,0,1,0,0,0,0,1,0,1,1,1,1,0,1,0,0,1,0,0,1,0,0,1,0,1,1,0,0,0,0,0,1,1,0,0,0,0, 1,1,1,1,0,1,0,1,1,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,1,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,1, 1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,1,1,1,1,1,0,1,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,1,0,0, 1,1,1,1,0,0,1,0,0,0,0,1,1,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,1,0,0,1,1,1,1,0,0,1,0, 0,1,0,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,1,0,1,1,1,1,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,1,1,1,1,0,0, 1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,0,0,1,0,0,0,0,0,1,1,1,1,0,0,1,0,1,0,1,0,1,0,0,0,1,1,1,0,1,1, 1,1,0,1,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,0,0,1,1,0,0,1,1,1,0,1,0,1,0,0,0,1,0,0, 1,1,0,1,1,0,1,0,0,0,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,1,1,0,1,0,0,0,0,1,1,1,1,1,0,1,1,0,0,1,1, 1,0,0,1,0,0,1,1,0,0,0,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,1,0,1,0,1,1,1,0,1,0, 1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,0,1,1,0,0,1,1,1,1,0,0,0,1,0,0,1,0,0,1,1,0,1,0,0,1,0,0,1,0,1, 1,1,0,1,0,0,1,1,0,1,0,1,0,0,1,0,0,1,0,1,1,1,1,0,1,1,0,0,1,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,1, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,0, 1,0,0,1,0,0,0,0,1,1,0,1,1,1,1,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,0,1,0,1,1,0,1,0,1,1,0, 1,1,0,1,0,0,1,0,0,0,1,1,1,1,0,1,0,1,1,0,1,0,0,1,0,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,0,1,1,0,0, 1,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,0,0,0,1,1,0,0,1,1,1,1,1,0,0,1,1,0,1,0, 0,1,1,1,0,0,1,1,0,1,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,1,0,1,0,1,0,1,1,0,0,1,0,1,1,1,0,0,0,1,1, 1,1,1,1,1,0,0,0,1,0,1,0,0,1,1,1,0,1,0,0,1,1,1,1,0,1,0,1,0,1,1,0,1,0,1,0,1,1,1,0,0,0,1,1,0, 1,1,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1,1,1,0,0,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,1,1,1, 1,1,1,1,1,0,1,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,1,0,1,0,1,0,1,1,1,1,1,0,0,0,1,1,0,1,1,0,1,0,0, 1,1,0,0,0,0,1,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,1, 0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,1,1,0,0,0,1,1,0,1,0,0,1,1, 1,1,0,1,0,0,1,1,0,1,0,1,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,1,0,1,0,0,1,0,0,0,1,0,0, 1,1,0,1,1,1,0,1,0,1,0,1,0,0,0,1,1,0,0,0,1,1,1,0,1,0,0,0,1,1,0,1,0,0,1,1,1,0,1,1,0,0,1,0,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,1,0,1,1,1,1,0, 1,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,1,1,0,0,0,1,1,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0, 1,1,0,1,1,1,0,1,0,1,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,1,1,0,0,1,1,0, 1,0,0,1,0,0,1,1,0,0,0,1,1,1,0,0,1,1,0,1,1,1,1,0,1,1,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,1,0,0,0, 1,1,0,0,1,1,0,1,0,1,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,1,0,1,1, 1,1,0,1,0,0,1,0,0,0,1,1,1,1,0,1,0,1,0,0,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,0,0,1,1,0,1,1,0,0,0, 1,1,0,1,0,0,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,0,1,1,0,1,0,1,0,1,0,0, 1,0,0,1,1,0,1,1,0,0,1,1,0,1,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,0,0,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,1,0,0,0,0,1,0,1, 1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1,1,0,1,1, 1,1,0,1,0,1,1,0,0,0,0,0,1,0,1,0,0,1,1,1,0,1,1,0,0,0,1,0,1,1,1,1,1,0,1,0,0,0,0,1,1,0,0,1,0, 1,1,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,1,0,1,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1,0,0, 1,1,1,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0,1,1,0,1,0,1,1,0,1,0,1,1,1, 1,1,0,1,0,1,0,1,1,1,0,0,1,1,0,0,1,1,0,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,1,1,0, 1,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,1,1,1,0,1,1,0,0,1,0,1,0,0,1,0,1,1,0,0, 1,1,0,1,0,0,1,1,0,1,0,1,0,0,1,0,0,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,0,1,1,1,0,0, 1,0,1,0,1,1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,0,1,1,1,1,0,0,1,0,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,1,0,0,1,1,0,1,1,1,0,0,0,0,0,0,1,1,0,0,1,0,1,0,1,1,0,1,0,1,0,1, 1,0,1,1,0,1,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,1,1,1,1, 1,1,1,1,0,1,1,0,1,0,1,1,1,0,1,0,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,0,1,0,0,1,0,1, 1,1,1,1,0,1,1,0,0,0,1,0,1,1,1,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,0,1,0,0,1,0,0,1,0,1,1,1,0,1,0, 1,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,1,1,1,0,1,0,0,1,1,0,0,0,1,1,0,1,0,0,1,1,1, 1,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,1,0,0,1,1,1, 1,1,0,1,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,0,1,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0, 1,1,1,1,0,0,1,1,1,1,1,0,0,0,1,0,0,1,0,1,1,1,1,0,0,1,0,1,0,1,1,0,0,0,1,0,1,0,1,0,0,1,1,0,1, 1,1,1,1,0,0,1,0,0,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,0,1,1,0,1,1,0,0,1,0,1,1,1,1,0,0,0,1,1,1,0, 1,0,0,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,1,1,0,1,1,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0, 1,0,0,1,0,0,0,0,1,1,0,1,1,1,0,0,1,1,0,0,0,1,1,0,0,0,1,0,0,1,0,0,1,1,1,1,1,1,0,0,0,1,0,1,1, 1,0,1,1,0,1,1,0,0,1,1,0,0,0,0,0,1,1,0,1,0,1,1,0,0,1,1,1,0,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,0, 1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0,0,0,1,0,0,0,0,0,0,1,0, 0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,1,1,0,1,0,0,1,0,0, 1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,0,1,0,1,0, 1,1,0,1,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,1,1,0,0,1,1,1,0,1,1,0,0,1,0,1,0,0,0,0,0,1,0,1, 0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,0,1,1,1,0,0,1,1,1,0,0,1,0,0,1,0,0,0,1,1,1,0,1,1,0,0,0,0,1,1, 1,0,1,1,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,0,1,0,0,1,1,1,0,1,0,1,1,0,1,0,1,1,0,1, 1,0,0,1,0,0,1,1,0,0,0,1,1,1,1,1,0,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,0,1,0,0,0,1,0,1,1,0,0,0, 1,0,1,1,0,1,1,1,1,0,0,0,1,1,1,0,0,1,1,0,1,0,1,0,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0, 1,0,1,1,0,1,0,1,1,0,0,1,0,1,0,0,1,1,1,0,1,1,1,1,0,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,0,1,0, 1,1,1,0,0,0,0,1,1,1,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,1,1,1,1,0,0,1,1, 1,1,0,1,0,0,0,0,1,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,0,0,1,1,0,0,1,1,1,0,1,0,0,0,1,1,0,0,1,1,1, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0,1,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,1,0,1,0, 1,1,0,1,1,0,1,0,0,0,0,1,0,1,1,1,0,0,1,1,1,0,1,0,1,1,1,0,0,0,1,1,1,0,1,0,0,0,0,1,1,0,0,0,0, 1,1,1,1,0,1,1,1,0,1,0,0,0,0,0,1,0,1,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1,1,1,1,1,0,1,1,0,0,0,0, 0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,0,1,0,1,0,1,1,0,0,0,1,0,1,1,1,1,1,0,1,0,0,1,0,0,0,0,1,1,0, 1,0,1,1,1,0,1,1,0,0,0,1,0,1,1,1,0,1,0,0,1,1,1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,1, 1,0,0,0,0,0,0,1,1,1,0,0,1,1,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,1,0,0,1,0, 1,0,0,1,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,1,0,0,1,0,0,1,0,1,0,0,0,0,1,1,1,1,0,0,0,1,1,0,1,1, 1,1,0,1,0,0,1,1,0,1,1,0,0,1,0,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,1,1,0,0,1,0,1, 1,0,0,1,1,1,1,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1,0,1,1,0,1,0,0,0,1,0,1,0,1,0,1,0,0,0,0,1,0,1,1, 1,0,0,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,0,0,0,0,1,1,1,0,0,1,1,1,0,1,0,1,0,1,0,0,0,0,1,0,1,0, 1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,0,1,1,1,1,0,0,0,1,0,1,1,1,1,1,0,1,0,0,0,1,0,1,1,1,0,0, 1,1,0,1,0,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1,1,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,1,0,1, 1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,1,0,1,1,1,0,1,0,0,1,0,0,1,1,0,1,1,1,0,1,0,0,0,1,0,0,1,0,1,1, 1,0,1,1,0,0,0,1,1,0,1,0,0,1,1,0,1,1,0,0,0,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,1,1,0,1,1,0,0,0,1, 1,1,1,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,0,1,1,1,1,0,0,1,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,0,0, 1,1,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,1,0,1,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,0,1,0,0,1,0,1,1,0,0,0,1,1,0,1,1,0,1,0,1,0,0,0,0,0,0,1,0,0,1,0,1, 1,0,1,0,0,1,0,0,1,0,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1,0,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1, 1,0,0,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,1,0,1,1,1,1,1,1,1,0,1,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0, 0,1,1,0,1,0,1,1,0,1,0,0,1,0,1,0,1,1,1,0,1,0,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,1,0,0,1,1,1, 1,0,0,0,0,0,0,0,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,0,1,1,0,0,1,1,0,1,1,1,0,1,1,0,0,1,0,1,1,1,1, 1,1,0,1,0,0,0,1,1,1,0,0,1,0,0,0,1,0,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,0,1,1,1,0,0,0,1,0,0,1,0, 1,1,1,1,0,1,1,1,0,1,1,0,0,1,1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,1,1,0,0,1,1,1,0,0,1,0,1,0,1,1,0, 1,1,1,1,0,0,0,1,1,1,0,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,0,1,1,0,0,1,0,1,1,1,0,0,0,1,1,0,1,1, 1,0,1,0,1,1,0,0,1,0,1,1,0,1,0,0,1,1,0,1,0,0,1,1,0,1,0,0,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,1, 0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,0,0,1,1,0,1,0,1,0,1,1,0,0,1,1,0,0,1,0,0,1,0,1, 0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,0,1,0,1,1,0,1,0,1,1,0,0,1,1,1,1,0,0,0,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,1,1,1,0,0,0,0,1,1,1,1,0,1,1, 1,0,0,1,0,0,1,1,0,0,0,0,1,0,1,0,1,1,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,1,1,0,0,1,0,1, 1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,1,0,0,0,1,0,1,0,1,0,1,0,1,1,0,0,1,0,1,1,1,1,1,0,0,0,1,1,1, 1,1,1,1,1,0,1,0,0,0,0,1,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,1,0,1,0,1,1,0,1,1,0,1,1,1,0,0,1,1,1, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,0,0,0,1,1,1,0,1, 1,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,0,1,0,1,1,1,1,1,1,0, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,1,1,0,1,0,1,0,0,1,0,1,1,0,0,1,0,0,0,1,0,1,0,0,1,0,0,1,1,1,1,1, 1,1,0,1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,0,1,1, 1,1,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,1,1,0,1,0,0,0,0,0,1,1,0,1,1,0,1, 1,0,1,1,1,0,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,1,1,1,0,0,1,0,0,1,1,1,0,0,0,1,0,0,1,0,1,1,0,1, 0,1,1,1,1,1,0,1,1,1,0,0,0,0,1,1,1,1,0,1,0,0,0,0,1,1,0,1,1,1,1,0,0,0,1,0,0,1,0,1,1,0,1,1,0, 1,0,0,1,0,0,1,1,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,1,0,0,0,0,0,1,0,0,1,0,0, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,1,0,1,1,0,0,1,1,1,0,1,1, 1,0,0,0,1,1,0,1,0,1,0,0,0,1,1,0,1,0,1,0,1,1,1,1,0,0,1,0,0,1,1,0,0,1,0,0,0,0,1,1,1,1,0,1,0, 1,1,0,1,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,0,1,1,1,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,1,0,0,0,1,1,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,0,1,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,1, 1,0,0,1,0,0,0,1,1,0,0,1,0,1,0,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0,0,1,0,0,1,0,1,0,0,0,0,0,0,1,1, 1,1,1,1,0,1,0,1,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,1,1,0,1,1,1,1,0, 1,1,0,0,0,1,0,0,1,0,0,0,0,0,0,1,1,1,1,1,0,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,0,0,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,1,0,1,1,0,1,0,1,1, 1,1,1,1,0,1,1,0,0,0,0,1,1,1,0,0,1,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,0,0,0,1,1,0,0,1,1,1, 1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,0,0,1,0,0,1,1,1,0,1,1,0,0, 1,1,1,1,0,0,1,0,1,0,0,0,1,1,1,0,0,1,1,0,1,0,1,0,0,1,1,0,1,0,1,0,1,0,0,0,0,1,1,1,1,0,0,0,1, 1,1,1,0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,1,0,1,1,0,1,0,1,1,1,1,0,0,1,0, 0,0,1,1,1,0,1,1,0,0,1,0,0,1,0,0,0,1,0,0,0,0,1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,1,0,1, 0,1,0,1,0,0,1,0,0,0,1,0,1,1,1,0,0,0,1,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,1,1,0,1,1,1,0,0,1,1, 0,0,0,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,0,1,0,1,1,1,0,0,0,1,0,1,0,0,0,1,1,0, 1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,0,1,0,1,1,0,0,1,0,1,1,0,1,1,1,0,1,1, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,0,1,0,1,1,0,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,1,1,0,0,1,0,1,1,0,1, 1,0,0,1,0,0,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,1, 0,0,0,1,1,1,0,0,0,1,0,1,1,0,0,1,1,0,0,1,0,1,1,0,0,0,1,0,0,1,1,0,1,0,1,1,1,0,1,0,0,0,1,0,0, 1,0,0,1,0,0,0,0,1,1,0,1,1,1,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,1,1,1,0,1,1,0,0,0,0,0,0, 1,0,0,1,0,0,0,0,1,1,0,1,1,0,1,1,1,1,0,0,1,1,0,0,1,1,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0, 1,0,1,1,1,0,0,1,1,0,0,0,0,1,0,0,1,0,1,0,0,0,0,1,0,1,1,1,0,1,1,1,1,0,0,1,0,1,0,0,0,1,1,0,0, 1,0,0,1,0,0,0,0,1,1,1,1,1,1,0,0,1,1,1,0,0,0,1,0,0,0,1,1,0,0,0,1,1,1,1,1,0,0,0,1,0,1,1,0,0, 0,1,1,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,1,1,0,0,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,1, 1,0,0,1,1,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,0,1,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0,0, 1,0,1,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,0,1,0,1,1,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,0,1,1, 1,1,0,1,1,0,0,1,0,1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,1,1,0,0,1,1, 1,1,0,1,0,0,1,1,0,1,0,0,0,0,1,1,1,1,0,1,0,0,0,0,1,1,0,1,0,0,1,1,1,0,0,0,0,1,0,1,0,0,1,0,1, 1,1,1,1,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,1,1,1,1,0,1,1,1,0,0,0,1, 1,1,0,1,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,1,1,1,0,1,0, 1,0,1,1,0,1,1,0,1,1,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,1,1,1,0,1,0,1,1,0,1,0,0,0,0,1,0,1,0,1,0, 1,1,1,1,0,0,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,0,0,1,0,1,0,0,1,0,0,1,1,1,0,1,1,0,1,0,1,1,1, 1,1,0,1,1,1,0,1,0,1,0,1,0,0,1,0,0,0,0,1,0,1,1,0,1,0,0,0,1,1,0,1,0,1,0,0,0,0,1,1,1,0,0,1,1, 1,1,1,0,0,0,1,1,0,0,0,1,1,1,0,0,0,1,0,1,1,0,1,0,1,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,0,1,0,0, 1,0,1,0,1,0,1,0,0,0,0,1,0,1,1,1,0,0,1,0,1,0,1,0,1,0,1,0,0,1,1,0,0,0,0,1,0,0,1,1,1,1,1,1,0, 1,0,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,0,1,1,0,0,0,1,1,0,0,0,1,1,0,0,1,0,1,1, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,1,0,0,1,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0,1,0,1,0,0,0,1,1,1,1,1, 1,0,0,0,1,0,0,1,0,1,0,0,1,1,1,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,1,1,0,1,1, 0,1,0,1,1,0,1,1,0,1,1,1,1,1,0,0,1,0,1,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,1,0,0,1,1,1,0,0,1,1, 0,0,0,1,0,0,0,1,1,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,1,0, 1,1,1,1,0,0,1,1,1,1,0,1,0,0,1,1,0,1,1,1,1,0,0,0,0,1,0,1,0,1,1,1,0,0,1,0,1,0,0,0,1,0,0,1,0, 1,1,1,1,0,0,1,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,0,1,1,1,0,0,0,0,1,1,0,0, 1,1,0,1,1,1,1,1,0,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,0,0,1,0,1,0,0,0,1, 1,0,0,0,0,0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,0,0,1,0,1,1,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0,1,1,0,0, 1,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,0,1,1,0,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,1,0, 1,1,1,1,1,1,0,0,1,0,1,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,1,0,0,1,0,1, 1,0,0,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,1,1,1, 1,1,0,1,0,1,1,1,0,1,0,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,1,0, 1,1,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,1,0,0,0,1,1,0,1,1,1,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,1,0,0, 1,1,0,1,0,0,1,0,0,0,1,1,1,1,1,1,0,1,0,0,1,1,1,0,1,1,1,1,0,1,0,0,1,0,0,0,0,0,1,0,1,0,1,1,0, 1,1,1,1,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,0,0,1,1,1,1,0,0,0,1, 1,1,0,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,0,0,0,1,1,0,1,1,1,0,1,0,1,1,0,0,0,0,1,1,1,0,1,1,0,0,1, 1,1,0,1,0,0,1,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,0,1,0,1,0,1,1,1,1,1,0,0,1,1,0, 1,0,0,1,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,1,1,1,0,0,1,1,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,1,1, 0,1,0,1,1,0,1,0,0,0,1,0,0,0,1,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,1,1,1,1,1,0,0,0,0, 1,0,1,1,0,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,1,0,1,0,1,0,1,1,1,1,1,1,1, 1,0,0,0,0,1,1,0,0,0,0,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,0,1,0,0,0,1,0,1,0,1,1,1,0,1,1,1,0, 1,1,1,0,0,1,1,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,0,0,1,0,1,1,0,0, 1,1,0,1,1,1,1,1,0,1,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,1,0,0,0, 1,1,1,1,0,0,1,0,0,0,1,0,1,1,0,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,0,1,1,0,1,0,1,0,1,0,0,0,0, 1,1,0,1,0,1,0,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,0,1,1,1,0,0,1,0,0,1,0,0,1,1,1,1,0,0,0,1, 0,1,0,1,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,1,1,1,0,0,0,1,0,0,0,0,0,1,0,1,0,1,0,0,0,1,1,0,0, 1,1,0,1,1,0,0,1,0,1,0,0,1,1,1,0,1,1,0,1,1,1,0,0,1,1,0,1,1,0,1,1,0,0,1,0,1,0,1,0,1,1,1,0,0, 1,0,0,0,1,1,1,1,0,1,0,0,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,1,1, 1,0,0,1,0,0,1,0,0,1,0,1,0,1,1,1,1,0,0,1,0,0,0,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,1,0,1,1,1,0,0, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,0,1,0,1,1,1,0,1, 0,1,0,1,1,1,1,0,0,0,0,0,0,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,0,1,1,1,0,0,0,1,1,1,0,1,1,0,0,1,0, 1,0,0,1,0,0,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1, 1,1,1,1,0,0,1,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,1,1,0,0,0,1,1,0,1,1,0,1,0,1, 1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,1,0,0,0,0,0,1,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,1, 1,0,0,0,1,1,0,0,0,0,0,1,0,1,0,1,1,0,0,1,1,0,0,0,1,0,0,0,1,0,0,1,0,1,1,1,0,0,1,1,1,0,0,0,0, 1,0,0,1,0,1,1,1,0,0,0,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,0,1,0,0,0,1,0,1,0,1,0,0,1,1,1,0,0,0,0, 0,0,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,1,1,0,0,1,1,0,1,0,1,0,1,1,0,1,0, 1,0,0,1,0,0,0,0,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,0,1,1,1,0,1,0,1,1,1,0,0,0,1,1,0,1,0,0,0,0,1, 1,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,1,1,0,1,0,1,0,1,0,0,0,0,0,0,1,1,1,1,0,0,1,0, 1,1,1,1,0,1,1,0,0,0,0,0,1,1,1,1,0,1,1,1,1,1,1,0,0,1,1,0,1,0,1,1,0,0,1,0,0,1,1,1,1,1,1,1,1, 1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1,0,0,1,1,0,1,0,0,0,1,1,0,1,0,0,1,1,1,0,0,1,1,1,0,1,0, 1,0,0,1,0,0,1,1,0,0,0,1,1,1,1,1,0,1,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,0,0, 1,1,1,1,0,1,0,1,1,1,0,1,1,0,0,0,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0,1,1, 1,0,0,1,1,0,1,0,0,1,0,0,1,1,1,0,0,0,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,0,0,0,0,0,1,1,0,0, 1,1,1,1,0,0,0,0,1,0,0,0,0,0,0,1,1,1,0,0,0,1,1,0,0,1,1,0,0,0,0,0,1,0,0,0,0,1,0,1,0,1,1,1,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,0,1,1,1,0,0,0,0,0,0,1,1,0,1,1,1,1,0,0,0,1,0,0,1,1,0,1,1,1,0,0, 1,1,1,1,0,0,0,0,1,0,0,1,0,0,1,0,1,1,1,0,0,0,0,1,0,1,1,1,0,1,0,1,1,1,0,1,1,1,0,1,0,1,1,0,0, 1,0,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,1,0,1,1,1,1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0, 1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,1,1,0,1,0,0,1,1,0,0,0,1,1,0,0,1,0,1,0,1,0,1,1,0,1,0,0,1,0,1, 1,0,1,0,1,1,1,1,0,1,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,1,1, 0,0,1,1,0,0,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1, 1,1,1,1,0,1,1,0,1,0,0,1,1,0,1,1,1,1,1,1,0,0,1,0,1,1,1,0,1,0,1,0,1,0,0,0,0,1,0,1,0,1,1,0,1, 1,0,1,1,0,0,1,0,1,1,1,1,0,1,1,1,0,0,1,0,0,1,1,1,0,1,0,1,0,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1, 1,1,0,1,0,0,1,1,0,1,1,0,0,1,0,0,0,1,0,0,1,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,1,1,0,1, 1,0,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,0,0,0,0,1,1,1,0,1,1,0,0, 1,1,1,1,1,0,1,0,0,0,0,1,0,1,1,1,0,1,0,0,1,1,1,0,1,0,1,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,0,0, 0,1,1,1,0,1,0,1,1,1,0,0,1,1,0,0,1,0,1,0,1,1,1,1,0,1,1,0,0,0,1,0,1,0,0,0,0,0,0,1,1,1,0,1,1, 1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,1, 1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,1,0,0,1,0,0,0,1,1,0,0,0,1,1,1,1,0,0,0,1,0,0,0,1,1,1,1,0, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,0,0,0,1,0,0,0,0,1,1,1,0,0,1,0,1, 1,0,0,0,0,0,1,0,0,0,0,1,1,1,1,1,0,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0,1,1,1,0,0,1,0,0, 1,1,0,1,1,0,1,1,0,1,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,1,0,1,1,0,1,0,1,1,0,0,0,0,0,0,1,1,1,0,1, 1,1,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0, 0,1,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,0,1,1,1,1,0,1,1,1,1,0,0,1,1,0,1,0,0,1,0,0,0,0,0,1,1,0,1, 1,0,0,1,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,0,1,1,0,1,0,0,0,0,0,1,1,1,0,1,1,0,0,1,1,1,0,0,0,1,0,1,0,1,0,0,0,0,0,1,1,1, 1,0,0,1,0,1,1,1,0,0,0,0,1,1,1,1,1,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,0,1,1, 1,1,0,0,0,0,1,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,0,1,1,1, 1,1,0,1,0,0,0,1,1,1,0,1,1,0,0,0,0,1,0,0,1,0,1,0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,0,1,1,0,1, 1,0,0,1,1,1,1,1,0,0,0,1,0,0,1,1,1,1,0,1,1,0,1,0,1,0,0,0,0,1,1,1,1,0,1,0,1,0,1,1,1,0,0,1,1, 1,1,1,1,0,0,1,1,0,1,1,1,0,0,0,1,0,1,0,0,0,1,1,0,1,0,0,1,1,0,1,1,1,1,0,0,0,1,1,0,0,0,1,1,0, 1,0,1,0,0,0,1,0,1,0,1,1,1,1,1,0,0,1,0,0,1,1,1,0,0,1,1,1,1,1,1,0,1,0,0,0,0,1,1,0,1,0,0,0,1, 0,0,0,1,0,0,0,0,1,1,1,0,1,1,0,1,1,0,1,1,1,0,1,0,0,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,1,1,0,1,0, 1,0,0,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1,0,0,1,1,1,1,0,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,1,1,1,0,1, 1,1,1,1,0,0,1,1,0,1,1,0,0,1,1,1,0,1,1,1,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,1,1,1,0,0, 0,1,1,1,1,0,1,1,0,1,1,0,1,1,0,0,0,1,0,0,1,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,1,1,1, 0,1,0,1,0,1,0,0,1,0,1,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,1,1,0,0,1,0,0,1,0,0,0,0,1,0,1, 1,0,1,1,0,1,1,0,0,1,0,1,0,1,1,1,0,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,1,1,0,1,0,1,1,0,1,1,0,1,1, 1,0,1,0,1,1,1,1,0,1,0,0,1,0,1,0,1,1,1,0,1,1,1,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1, 1,1,0,1,0,1,0,0,1,0,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,0,0,0,0,1, 1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,0,0,1,0,1,0, 1,1,0,1,1,0,1,0,0,0,1,1,0,0,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1,0,1,1,0,0,1,1,0,0,1,1,1,1,0,1, 1,0,0,1,1,1,0,1,0,0,0,1,0,1,1,1,0,1,1,0,0,1,1,1,0,0,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,0,1, 1,0,0,1,0,0,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,1,1,0,0,0,1,0,1,1,0,1,1,0,1,1,0,0,1,1,0,0,1,0,1, 0,0,1,1,1,0,0,0,1,1,0,0,0,1,1,0,1,0,1,0,1,0,0,1,0,1,1,1,0,0,1,1,0,1,1,1,0,1,0,1,1,0,0,0,1, 1,0,0,1,0,0,0,1,1,0,1,0,0,1,1,1,1,1,1,0,1,0,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,1,1,1,0,1,0,0, 1,1,1,0,1,1,1,1,0,0,0,1,0,1,1,0,0,1,0,0,1,1,1,0,1,1,0,0,1,0,0,0,1,1,0,1,0,1,0,1,0,1,1,0,1, 1,0,0,1,0,0,1,1,0,0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0, 1,0,1,1,1,1,1,1,0,0,0,1,0,1,1,0,0,0,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,1, 1,0,0,1,0,1,0,0,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,1,0,0, 1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,1,0,1,1,1,0,1,0,0,1,0, 1,1,1,0,0,0,0,1,1,1,0,0,1,1,0,0,0,1,0,1,1,0,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,1,0,1,1,0,0,0,1, 0,1,1,1,1,1,1,0,0,0,1,1,0,1,1,0,1,1,1,0,0,1,1,1,1,1,0,1,0,1,1,0,1,0,1,0,1,1,0,1,0,1,0,1,0, 1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,0, 0,1,1,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,1,1,1,0,0,1,1,0,1,0,0,1,0,1,1,1,0,1,0,0,1,1,0,1,1, 1,0,0,0,1,0,1,0,0,0,0,1,0,1,1,1,0,1,1,0,1,1,1,0,0,0,1,0,1,1,1,0,1,0,0,0,0,1,1,0,1,0,0,1,1, 1,0,1,1,0,1,1,1,0,0,1,0,1,0,1,1,0,1,0,0,0,1,1,0,0,0,0,1,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,1,1, 1,1,1,1,0,1,1,0,1,0,1,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,1,1,1,1, 1,0,1,1,0,1,1,1,0,0,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,1,0,1,1,0,0,0,1,0,1,1, 1,1,0,1,0,0,1,1,0,1,0,1,0,0,1,1,1,1,0,0,1,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,1,0,1,0,1,1,0,1, 1,0,0,1,0,0,0,1,1,0,0,1,0,0,1,1,0,1,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,1,0,0,1,1,1,1,0,0,1,0, 1,0,1,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,1,0,1,1,0,0,1,1,0,1,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1, 1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,0,1,1,0,1,0,1,1,1,1,0,1,1,0,1,1,0,0, 1,1,1,1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,0,1,1,0,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,1,0,1, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,1,0,1,1,1,0,0,0,1,1,1,0,0,1,0,0,1,0,1,0, 1,1,1,1,0,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,0,0,1,0,1,0,1,0,1,0,0,0,0,1,1,0,0,0,0,1,1, 1,1,0,0,0,1,1,1,0,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,0,1,0,1,0,1,1,1,0,0,1, 1,1,1,1,0,0,1,0,0,0,0,1,1,1,1,1,0,1,0,0,1,0,0,0,0,1,0,1,0,1,1,1,1,0,0,0,1,1,0,1,1,1,0,1,1, 1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0, 1,1,1,1,1,1,1,0,0,0,0,1,0,1,1,1,0,0,1,1,1,1,1,0,1,1,1,0,0,0,1,0,1,1,1,1,1,1,0,0,1,0,0,0,0, 1,1,0,1,1,1,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,0,0,0,1,0,0,1,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0, 1,0,1,1,1,1,0,1,1,0,0,1,0,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,0,1,0, 1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0,1,1,0,0,1,0,0,0,1, 0,1,0,1,0,0,1,0,0,0,1,0,1,1,1,0,0,0,1,0,0,0,0,1,1,1,1,0,0,1,1,1,1,1,0,0,1,1,1,0,0,1,1,0,1, 0,0,1,0,0,0,1,0,0,0,1,1,1,0,1,1,0,1,1,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,1,1,0,0,0,1,0,1,1, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,1,1,1,0,1,1,1, 1,1,0,1,1,1,0,1,0,1,0,1,0,0,1,1,1,1,0,0,0,1,1,0,1,0,0,0,1,1,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0, 1,0,0,1,0,1,1,1,0,0,1,1,1,1,1,1,0,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,0,1,1,1,0,1,1, 1,0,0,0,0,0,1,0,0,0,0,1,1,1,1,0,0,1,1,0,1,0,0,0,1,1,0,0,1,1,1,1,1,0,1,0,0,1,1,1,0,0,1,1,1, 1,1,1,1,0,1,0,1,1,1,0,0,1,1,1,0,1,1,1,0,1,1,0,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,1,1,1,1,0,1,1, 1,1,1,0,0,0,0,0,1,0,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,1,0,1,0,0,0,0,1,0,0,0,0,1,1,0, 1,0,0,1,1,0,0,1,0,0,1,0,0,1,1,0,1,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,0,0,1,1,1, 1,0,0,1,1,0,0,1,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,1,0,1,0,1,0,1,0,1,0, 0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0,1,0,0,0,1,1,0,1,0,0,0,1,1,1,0,0,0,1, 0,0,0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,1,0,1,1,1,0, 0,0,0,1,1,1,0,0,0,1,1,0,0,0,0,1,0,0,1,1,1,1,1,0,0,0,1,1,1,0,0,1,0,1,1,1,0,1,0,0,1,1,0,1,1, 1,0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0, 1,1,0,1,0,0,1,1,0,1,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,0, 1,0,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,0,0,1,1,0,1,0, 1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,0,0,0,1,0,1,0,1,0,1,0,1,1,0,0,0,1,1, 1,1,1,0,0,1,0,0,1,0,0,1,0,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,0,0,1,1,1,0,1, 1,0,0,1,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,0,1,1,1,0,1,0,1,0,1,0,0,0,1,0,0,1,1,0,1, 1,0,0,1,0,0,0,1,1,0,1,1,0,1,1,1,1,1,0,1,1,0,0,1,1,1,1,0,1,1,1,0,0,0,1,0,1,1,0,0,0,0,0,0,1, 0,1,1,1,0,0,1,1,1,1,0,1,0,1,0,1,1,0,1,0,1,1,0,0,0,1,0,1,0,1,0,0,0,1,1,0,0,0,1,0,0,0,1,1,0, 1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,0,1,1,0,0,0,1,1,1,0,0,0,1,0,0,1,0,0,1,0,1,0,0,0,0,0,1,0,1,1, 1,0,1,1,1,0,0,1,1,0,0,0,0,1,1,0,1,0,1,1,0,0,1,1,0,1,1,0,0,0,1,1,1,0,0,0,0,1,0,1,0,1,0,1,1, 1,0,0,1,0,0,0,0,1,1,0,1,1,0,1,1,1,1,1,0,1,0,0,1,1,1,1,1,1,1,1,0,1,1,0,1,0,0,0,0,0,1,0,1,0, 1,0,1,1,0,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,0,1,1,0,1,0,1,1,0,0,1,1,1, 1,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,0,1,1,0,1,0, 1,1,0,1,0,0,1,1,0,1,0,1,0,1,0,0,0,1,0,1,0,1,1,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,1,0,1,0,0,1,0, 1,0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,1,1,0,0,1,0,0,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,1,0,0,1,0,0, 1,0,0,0,0,1,1,1,0,1,0,1,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1, 1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,1,0,0,0,1,0,1,1,1,1,1,1,0,1,1,0,0,1,1,1,0,0,1, 1,0,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,1,1,0,0, 1,0,0,1,1,1,1,1,0,0,1,0,0,1,1,1,0,0,1,0,1,0,1,1,0,0,1,1,1,0,0,0,1,1,0,1,0,1,0,0,1,1,0,1,1, 1,0,0,0,0,0,1,1,0,1,1,1,0,0,1,1,0,1,1,1,0,0,0,1,1,1,1,1,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,0,0, 1,1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,1,0,1,0,1,1,0,1,0,0,1,1,1, 1,0,0,1,0,0,1,0,0,1,1,1,0,1,1,1,1,1,0,0,0,1,1,0,0,0,1,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,1, 0,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,1,1,1,1,0,0,1,1,0,1,1, 1,0,0,0,0,0,0,1,1,1,0,1,1,1,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,1,0, 0,1,0,1,1,1,0,1,0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0,1,1,0,0,1,0,1,0,0,0,0,0,1,1,0,0,1,1,1, 1,1,0,1,1,0,1,0,0,0,1,1,0,1,0,1,1,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0,1,1,1, 1,0,0,1,0,1,1,1,0,0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,0,1,0,1,0,0,0,1,1,1,1, 1,0,0,1,0,0,0,0,1,1,0,1,1,1,1,1,1,0,1,1,1,0,1,1,0,0,0,0,0,1,0,1,1,0,0,1,1,0,1,1,1,0,0,0,1, 1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,1,1,1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,0,1,1,0,0,1,1,1,0,1,0, 1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,1,1,1,0,0,1,1, 1,1,0,1,0,1,1,1,0,1,0,1,0,0,1,1,0,1,0,0,1,0,1,0,1,0,0,0,1,1,0,0,0,0,1,0,1,1,0,0,1,0,0,0,1, 1,0,0,0,0,0,1,1,0,1,0,0,0,0,1,0,1,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0, 1,1,0,1,0,0,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,1,1,0,0,0,0, 1,0,1,1,0,0,1,0,0,1,0,0,0,1,1,0,0,1,1,0,1,0,0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,0,1,1,0,0,1,1,0, 1,1,0,1,1,0,1,0,0,0,0,0,0,1,1,1,0,1,0,1,1,1,1,0,0,0,1,0,1,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1, 1,1,0,1,0,0,1,0,0,0,1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,0,1, 1,1,0,1,0,0,1,0,0,0,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,1,0,1,0,0,1,1,1,0,0,0,1,1,0,0,0,1,0,1,1, 1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,1,0,0,0,1,0,1,1, 1,0,1,0,0,1,0,1,1,1,0,0,1,1,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1, 1,1,1,0,1,1,1,0,0,0,1,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,0,1,0,1,1,1,0, 1,0,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0,0,1,0,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,0,0,0,1,1,0,0, 1,1,1,1,1,1,1,1,0,1,0,1,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,1,1,0,1,0,0,1,0,0,1,1,1, 1,0,1,1,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,1,1,0,1,0,1,1,1,0,0,1,0,0, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,1,1,0,1,0,0,1,0,1,1,1,0,1,0,0, 0,0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,0,1,1,0,0, 1,0,1,1,1,0,1,0,0,1,0,1,1,1,1,1,0,1,0,0,0,1,1,0,1,0,1,0,0,1,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0, 1,0,0,1,0,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,1,0,1,0, 0,1,1,1,0,0,0,1,1,1,1,0,1,1,0,0,1,0,1,1,0,1,1,0,0,1,0,1,0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0,0, 0,0,0,1,1,1,1,0,0,1,1,0,1,0,0,0,0,0,1,1,0,1,1,1,0,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0, 1,1,0,1,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,1,1,1,1,1,0,1,1,1,0,0,0,1,1,0,0, 1,1,0,1,0,0,1,1,0,1,1,0,0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,1, 1,1,1,0,0,0,1,0,1,0,1,1,1,1,1,1,0,1,1,0,0,0,0,1,0,1,1,1,1,0,1,1,0,0,1,0,0,0,0,1,1,1,1,1,0, 1,1,1,0,0,1,0,1,1,0,0,0,0,1,0,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,0,1,0, 1,0,0,1,1,1,0,1,0,0,0,1,0,0,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,1,0,1,0,0,1,1,0,1,1,1,0, 1,1,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,1,0,0,1,1,0, 1,0,0,1,0,0,0,0,1,1,0,1,1,1,1,1,1,0,1,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,1,0,1,1,0, 1,0,1,0,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,0,0,0,1,1,0,0,0,1,1,0,1,0,1,0,1,0,0,1,0,1,1,1,0, 1,1,0,1,1,0,0,0,0,0,1,1,0,1,0,1,0,1,0,0,1,0,0,1,0,0,1,0,1,0,1,0,0,0,1,0,1,1,0,0,1,1,0,1,0, 1,0,0,1,0,0,0,0,1,1,0,0,1,1,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0, 1,0,0,1,0,0,1,0,0,1,1,0,0,1,1,0,1,1,0,0,0,0,1,0,0,0,1,1,0,0,0,1,1,1,1,1,0,0,0,1,0,0,1,1,1, 1,1,0,1,1,1,1,1,0,1,1,0,1,0,0,0,0,1,0,0,0,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1, 1,0,0,1,0,0,0,0,1,1,1,1,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,1,0,1,1,0,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,1,1,0,1,0,0,1,0,1, 1,0,0,0,0,0,0,1,1,1,0,0,1,0,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,1,1,1,0, 1,1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,1,1,0,1, 1,1,0,1,0,1,1,0,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,1,0,1,1,0,0,0,0,1,0,0,0,0,1,1,1,1,0,1,1,1, 1,0,0,0,0,0,0,1,1,1,0,1,1,1,0,1,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1,0,0,1,0,1,0,0,1,1,0,0,0,1,0, 1,0,0,1,0,0,0,0,1,1,1,0,1,1,1,0,1,1,0,0,1,0,1,1,0,0,0,1,0,0,1,1,1,0,1,0,0,1,0,1,1,0,0,0,1, 0,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,1,0,0,1,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,1,1,1,1,1, 1,1,1,0,0,1,1,1,0,0,0,0,1,0,1,1,0,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,1,1,1,0, 1,1,0,1,1,0,1,0,0,0,1,1,0,1,1,0,1,0,1,0,1,1,1,1,1,1,0,1,1,1,0,1,0,1,1,0,0,1,1,1,0,0,1,0,1, 1,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,0,1,1,0,1,0,0,0,0,1,1,1,1,0,0,0,0, 1,0,0,1,0,0,0,0,1,1,0,1,1,0,1,1,1,0,0,0,0,0,0,0,1,1,0,1,0,1,0,1,1,1,0,0,1,0,0,1,1,0,0,0,0, 1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,1,1,1,0,0, 1,0,0,0,1,1,0,0,0,0,0,1,0,1,0,1,1,1,0,1,0,1,1,0,1,0,1,0,1,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1, 1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,0,0,0,1,1,0,1,1,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1,1,0,0,0, 1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1, 1,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,0,0,0,1,1,1,0,0,1,0,1, 1,1,1,0,0,1,0,1,1,1,0,1,1,0,0,1,1,0,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,0,1, 1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,0,0,1,1,1,1,1,0,0,1,1,0,1,0,1,0,1,0, 1,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,0,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,0,1,0,0,0,0,1,0,1,1, 1,0,0,0,0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,1,0,0,1,1,1,0,0,1, 1,1,0,1,0,0,1,0,0,0,1,1,1,1,0,1,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,0,0,0,1,1,0,0,0,1,0,1,0, 0,0,0,1,1,0,1,1,0,0,0,1,0,1,0,0,0,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,0,0,0,0,0,1,1,1,0,1,1,1, 1,1,0,1,0,0,1,1,0,1,0,0,0,0,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,1,0,0,0,0,0,1,1,0,0, 1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,0,0,1,0,0,0,1,1,0,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,0,0,0,1,1,1, 1,0,0,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,1,0,0,1,1,0,0,0,0,1,1,0,1, 1,0,1,0,0,0,0,0,1,0,0,1,0,1,1,0,1,1,0,0,1,0,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,1,0,1,1, 1,1,1,0,1,0,1,0,0,0,1,1,0,1,1,1,0,0,1,0,1,0,0,1,0,1,1,1,1,1,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1, 0,1,1,1,1,0,1,0,0,0,0,0,0,1,1,0,0,0,1,0,1,1,1,0,0,1,1,0,1,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,0, 1,1,0,1,0,0,1,0,0,0,0,0,1,1,1,0,0,1,1,0,1,0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,0,1,1,0,0,0,0,1,0, 1,1,0,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0, 1,1,0,1,0,1,0,1,1,1,0,0,1,1,1,0,1,1,1,0,1,0,1,1,0,0,1,0,0,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,1, 1,1,1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,0,1,0, 1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,0,0,0,0,1,0,0,1,0,0,1,1,1,1,1,1,0,1, 1,1,0,1,1,1,0,0,0,0,1,0,0,1,1,1,1,0,1,1,1,1,0,0,1,0,0,0,1,0,0,1,1,1,0,1,1,1,1,0,0,0,1,0,1, 1,1,1,1,0,1,1,0,0,0,1,0,1,1,0,0,1,1,1,1,0,0,1,1,0,1,0,1,0,1,1,1,1,0,1,0,0,1,0,1,1,1,0,1,0, 1,0,0,1,0,0,1,1,0,0,0,1,1,1,1,0,1,1,1,0,1,0,1,0,0,0,0,0,0,1,1,1,0,0,1,0,1,1,0,1,1,1,0,1,0, 0,0,0,1,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,1,1,1,0,1,1,0,0,1,0,0,1,0,0,0,0,0,1,1,0,1,0,0,1,1, 1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,1,0,1,1,1,0,1,1,1,0,0,0, 1,0,0,1,1,0,0,1,0,0,0,0,0,1,0,0,1,1,0,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,1,0,1,0,0,0,0,1,0,1,0, 0,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,0,1,0,1,0, 1,1,1,1,0,1,0,1,1,1,1,0,1,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,0,1,0,0,1,0,1,1, 1,1,0,1,0,0,0,0,1,0,0,1,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0,0,1,1,1,0,0,1,0,0, }; #pragma omp end declare target #endif
pi-v3.c
/* * Compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x) * between 0 and 1. * * parallel version using OpenMP */ #include <stdio.h> #include <stdlib.h> #include <omp.h> /* OpenMP */ #if _DEBUG_ #define _DEBUG_ 1 #else #define _DEBUG_ 0 #endif int main(int argc, char *argv[]) { double x, sum=0.0, pi=0.0; #if !_DEBUG_ double start,end; #endif int i; const char Usage[] = "Usage: pi <num_steps> (try 1000000000)\n"; if (argc < 2) { fprintf(stderr, Usage); exit(1); } int num_steps = atoi(argv[1]); double step = 1.0/(double) num_steps; #if !_DEBUG_ start= omp_get_wtime(); #endif /* do computation -- using all available threads */ // WARNING : incorrect code #pragma omp parallel private(i, x) { int id = omp_get_thread_num(); int num_threads = omp_get_num_threads(); // interleaved execution of iterations among threads for (i=id; i < num_steps; i=i+num_threads) { x = (i+0.5)*step; sum += 4.0/(1.0+x*x); #if _DEBUG_ printf("thread id:%d it:%d\n",id,i); #endif } } pi = step * sum; #if !_DEBUG_ end = omp_get_wtime(); printf("Wall clock execution time = %.9f seconds\n", end-start); #endif /* print results */ printf("Value of pi = %12.10f\n", pi); return EXIT_SUCCESS; }
globals.h
#include <iostream> using std::cout; using std::endl; #ifndef _flops_globals_H #define _flops_globals_H //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #include <stdint.h> #include <string.h> #include <omp.h> #include <memory> #include "tools.h" namespace Flops{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// typedef uint64_t largeint_t; const double TEST_ADD_ADD = 1.4142135623730950488; const double TEST_ADD_SUB = 1.414213562373095; const double TEST_MUL_MUL = 1.4142135623730950488; const double TEST_MUL_DIV = 0.70710678118654752440; const double TEST_FMA_LINEAR_MUL0 = 1.4142135623730950488; const double TEST_FMA_LINEAR_MUL1 = 1.7320508075688772935; const double TEST_FMA_HORNER_MUL0 = 1.4142135623730950488; const double TEST_FMA_HORNER_ADD0 = 1.7320508075688772935; const double TEST_FMA_HORNER_MUL1 = 0.70710678118654752440; const double TEST_FMA_HORNER_ADD1 = -1.2247448713915890491; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// class benchmark{ virtual void print_meta() const = 0; virtual largeint_t run_loop(largeint_t iterations, double &result) const = 0; public: void run(largeint_t iterations) const{ print_meta(); double result; wclk start = wclk_now(); iterations = run_loop(iterations, result); double seconds = wclk_secs_since(start); cout << " Result = " << result << endl; cout << " FP Ops = " << iterations << endl; cout << " seconds = " << seconds << endl; cout << " GFlops = " << iterations / seconds / 1.e9 << endl; cout << endl; } void run(largeint_t iterations, size_t threads) const{ print_meta(); auto thread_result = std::unique_ptr<double[]>(new double[threads]); auto thread_iterations = std::unique_ptr<largeint_t[]>(new largeint_t[threads]); memset(thread_result.get() , 0, threads * sizeof(double)); memset(thread_iterations.get(), 0, threads * sizeof(largeint_t)); wclk start = wclk_now(); #pragma omp parallel num_threads((int)threads) { size_t thread_id = omp_get_thread_num(); double result; thread_iterations[thread_id] = run_loop(iterations, result); thread_result[thread_id] = result; } double seconds = wclk_secs_since(start); double result = 0; iterations = 0; for (size_t i = 0; i < threads; i++){ result += thread_result[i]; iterations += thread_iterations[i]; } cout << " Result = " << result << endl; cout << " FP Ops = " << iterations << endl; cout << " seconds = " << seconds << endl; cout << " GFlops = " << iterations / seconds / 1.e9 << endl; cout << endl; } }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// } #endif
hybrid_hello.c
#include <stdio.h> #include <omp.h> #include "mpi.h" int main(int argc, char* argv[]) { int rank, size; int tid, thread_level; MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &thread_level); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); printf("Hello, world! I am the main thread of MPI rank %d of size %d\n", rank, size); #pragma omp parallel private(tid) { tid = omp_get_thread_num(); printf("Hello, world! I am OpenMP thread %d of MPI rank %d\n", tid, rank); } MPI_Finalize(); return 0; }
convolution_1x1.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON #include "mat.h" namespace ncnn { static void conv1x1s1_sgemm_transform_kernel_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { const float* kernel = _kernel; // interleave #if __ARM_NEON && __aarch64__ kernel_tm.create(4 * 8, inch / 4 + inch % 4, outch / 8 + (outch % 8) / 4 + outch % 4); #else kernel_tm.create(4 * 4, inch / 4 + inch % 4, outch / 4 + outch % 4); #endif // __ARM_NEON && __aarch64__ int p = 0; #if __ARM_NEON && __aarch64__ for (; p + 7 < outch; p += 8) { const float* kernel0 = kernel + (p + 0)*inch; const float* kernel1 = kernel + (p + 1)*inch; const float* kernel2 = kernel + (p + 2)*inch; const float* kernel3 = kernel + (p + 3)*inch; const float* kernel4 = kernel + (p + 4)*inch; const float* kernel5 = kernel + (p + 5)*inch; const float* kernel6 = kernel + (p + 6)*inch; const float* kernel7 = kernel + (p + 7)*inch; float* ktmp = kernel_tm.channel(p / 8); for (int q = 0; q < inch; q++) { // kernel0...7 0 ktmp[0] = kernel0[0]; ktmp[1] = kernel1[0]; ktmp[2] = kernel2[0]; ktmp[3] = kernel3[0]; ktmp[4] = kernel4[0]; ktmp[5] = kernel5[0]; ktmp[6] = kernel6[0]; ktmp[7] = kernel7[0]; ktmp += 8; kernel0 += 1; kernel1 += 1; kernel2 += 1; kernel3 += 1; kernel4 += 1; kernel5 += 1; kernel6 += 1; kernel7 += 1; } } #endif // __ARM_NEON && __aarch64__ for (; p + 3 < outch; p += 4) { const float* kernel0 = kernel + (p + 0)*inch; const float* kernel1 = kernel + (p + 1)*inch; const float* kernel2 = kernel + (p + 2)*inch; const float* kernel3 = kernel + (p + 3)*inch; #if __ARM_NEON && __aarch64__ float* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4); #else float* ktmp = kernel_tm.channel(p / 4); #endif // __ARM_NEON && __aarch64__ for (int q = 0; q < inch; q++) { // kernel0...3 0 ktmp[0] = kernel0[0]; ktmp[1] = kernel1[0]; ktmp[2] = kernel2[0]; ktmp[3] = kernel3[0]; ktmp += 4; kernel0 += 1; kernel1 += 1; kernel2 += 1; kernel3 += 1; } } for (; p < outch; p++) { const float* kernel0 = kernel + p*inch; #if __ARM_NEON && __aarch64__ float* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4); #else float* ktmp = kernel_tm.channel(p / 4 + p % 4); #endif // __ARM_NEON && __aarch64__ for (int q = 0; q < inch; q++) { ktmp[0] = kernel0[0]; ktmp++; kernel0++; } } } static void conv1x1s1_sgemm_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; const float* bias = _bias; // interleave Mat tmp(8 * 4, inch / 4 + inch % 4, size / 8 + (size % 8) / 4 + size % 4, 4u); { int nn_size = size >> 3; int remain_size_start = nn_size << 3; //#pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = ii * 8; const float* img0 = bottom_blob.channel(0); img0 += i; float* tmpptr = tmp.channel(i / 8); for (int q = 0; q < inch; q++) { #if __ARM_NEON #if __aarch64__ vst1q_f32(tmpptr, vld1q_f32(img0)); vst1q_f32(tmpptr + 4, vld1q_f32(img0 + 4)); tmpptr += 8; img0 += bottom_blob.cstep; #else asm volatile( "pld [%0, #256] \n" "vld1.f32 {d0-d3}, [%0 :128] \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "q0", "q1" ); img0 += bottom_blob.cstep; #endif // __aarch64__ #else tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr[4] = img0[4]; tmpptr[5] = img0[5]; tmpptr[6] = img0[6]; tmpptr[7] = img0[7]; tmpptr += 8; img0 += bottom_blob.cstep; #endif // __ARM_NEON } } nn_size = (size - remain_size_start) >> 2; //#pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 4; const float* img0 = bottom_blob.channel(0); img0 += i; float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); for (int q = 0; q < inch; q++) { #if __ARM_NEON #if __aarch64__ vst1q_f32(tmpptr, vld1q_f32(img0)); tmpptr += 4; img0 += bottom_blob.cstep; #else asm volatile( "pld [%0, #128] \n" "vld1.f32 {d0-d1}, [%0 :128] \n" "vst1.f32 {d0-d1}, [%1 :128]! \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "q0" ); img0 += bottom_blob.cstep; #endif // __aarch64__ #else tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; #endif // __ARM_NEON } } remain_size_start += nn_size << 2; //#pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { const float* img0 = bottom_blob.channel(0); img0 += i; float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); for (int q = 0; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr++; img0 += bottom_blob.cstep; } } } int nn_outch = 0; int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; //#pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; float* outptr0 = top_blob.channel(p); float* outptr1 = top_blob.channel(p + 1); float* outptr2 = top_blob.channel(p + 2); float* outptr3 = top_blob.channel(p + 3); float* outptr4 = top_blob.channel(p + 4); float* outptr5 = top_blob.channel(p + 5); float* outptr6 = top_blob.channel(p + 6); float* outptr7 = top_blob.channel(p + 7); const float zeros[8] = { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; const float* biasptr = bias ? bias + p : zeros; int i = 0; for (; i + 7 < size; i += 8) { const float* tmpptr = tmp.channel(i / 8); const float* kptr = kernel.channel(p / 8); asm volatile( "ld1 {v0.4s, v1.4s}, [%20] \n" "dup v16.4s, v0.s[0] \n" "dup v17.4s, v0.s[0] \n" "dup v18.4s, v0.s[1] \n" "dup v19.4s, v0.s[1] \n" "dup v20.4s, v0.s[2] \n" "dup v21.4s, v0.s[2] \n" "dup v22.4s, v0.s[3] \n" "dup v23.4s, v0.s[3] \n" "dup v24.4s, v1.s[0] \n" "dup v25.4s, v1.s[0] \n" "dup v26.4s, v1.s[1] \n" "dup v27.4s, v1.s[1] \n" "dup v28.4s, v1.s[2] \n" "dup v29.4s, v1.s[2] \n" "dup v30.4s, v1.s[3] \n" "dup v31.4s, v1.s[3] \n" // inch loop "lsr w4, %w21, #2 \n"// w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v18.4s, v8.4s, v0.s[1] \n" "fmla v20.4s, v8.4s, v0.s[2] \n" "fmla v22.4s, v8.4s, v0.s[3] \n" "fmla v17.4s, v9.4s, v0.s[0] \n" "fmla v19.4s, v9.4s, v0.s[1] \n" "fmla v21.4s, v9.4s, v0.s[2] \n" "fmla v23.4s, v9.4s, v0.s[3] \n" "fmla v24.4s, v8.4s, v1.s[0] \n" "fmla v26.4s, v8.4s, v1.s[1] \n" "fmla v28.4s, v8.4s, v1.s[2] \n" "fmla v30.4s, v8.4s, v1.s[3] \n" "fmla v25.4s, v9.4s, v1.s[0] \n" "fmla v27.4s, v9.4s, v1.s[1] \n" "fmla v29.4s, v9.4s, v1.s[2] \n" "fmla v31.4s, v9.4s, v1.s[3] \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%8], #64 \n" "fmla v16.4s, v10.4s, v2.s[0] \n" "fmla v18.4s, v10.4s, v2.s[1] \n" "fmla v20.4s, v10.4s, v2.s[2] \n" "fmla v22.4s, v10.4s, v2.s[3] \n" "fmla v17.4s, v11.4s, v2.s[0] \n" "fmla v19.4s, v11.4s, v2.s[1] \n" "fmla v21.4s, v11.4s, v2.s[2] \n" "fmla v23.4s, v11.4s, v2.s[3] \n" "fmla v24.4s, v10.4s, v3.s[0] \n" "fmla v26.4s, v10.4s, v3.s[1] \n" "fmla v28.4s, v10.4s, v3.s[2] \n" "fmla v30.4s, v10.4s, v3.s[3] \n" "fmla v25.4s, v11.4s, v3.s[0] \n" "fmla v27.4s, v11.4s, v3.s[1] \n" "fmla v29.4s, v11.4s, v3.s[2] \n" "fmla v31.4s, v11.4s, v3.s[3] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n" "fmla v16.4s, v12.4s, v4.s[0] \n" "fmla v18.4s, v12.4s, v4.s[1] \n" "fmla v20.4s, v12.4s, v4.s[2] \n" "fmla v22.4s, v12.4s, v4.s[3] \n" "fmla v17.4s, v13.4s, v4.s[0] \n" "fmla v19.4s, v13.4s, v4.s[1] \n" "fmla v21.4s, v13.4s, v4.s[2] \n" "fmla v23.4s, v13.4s, v4.s[3] \n" "fmla v24.4s, v12.4s, v5.s[0] \n" "fmla v26.4s, v12.4s, v5.s[1] \n" "fmla v28.4s, v12.4s, v5.s[2] \n" "fmla v30.4s, v12.4s, v5.s[3] \n" "fmla v25.4s, v13.4s, v5.s[0] \n" "fmla v27.4s, v13.4s, v5.s[1] \n" "fmla v29.4s, v13.4s, v5.s[2] \n" "fmla v31.4s, v13.4s, v5.s[3] \n" "subs w4, w4, #1 \n" "fmla v16.4s, v14.4s, v6.s[0] \n" "fmla v18.4s, v14.4s, v6.s[1] \n" "fmla v20.4s, v14.4s, v6.s[2] \n" "fmla v22.4s, v14.4s, v6.s[3] \n" "fmla v17.4s, v15.4s, v6.s[0] \n" "fmla v19.4s, v15.4s, v6.s[1] \n" "fmla v21.4s, v15.4s, v6.s[2] \n" "fmla v23.4s, v15.4s, v6.s[3] \n" "fmla v24.4s, v14.4s, v7.s[0] \n" "fmla v26.4s, v14.4s, v7.s[1] \n" "fmla v28.4s, v14.4s, v7.s[2] \n" "fmla v30.4s, v14.4s, v7.s[3] \n" "fmla v25.4s, v15.4s, v7.s[0] \n" "fmla v27.4s, v15.4s, v7.s[1] \n" "fmla v29.4s, v15.4s, v7.s[2] \n" "fmla v31.4s, v15.4s, v7.s[3] \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w21, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {v8.4s, v9.4s}, [%8], #32 \n" "prfm pldl1keep, [%9, #256] \n" "ld1 {v0.4s, v1.4s}, [%9], #32 \n" "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v18.4s, v8.4s, v0.s[1] \n" "fmla v20.4s, v8.4s, v0.s[2] \n" "fmla v22.4s, v8.4s, v0.s[3] \n" "fmla v17.4s, v9.4s, v0.s[0] \n" "fmla v19.4s, v9.4s, v0.s[1] \n" "fmla v21.4s, v9.4s, v0.s[2] \n" "fmla v23.4s, v9.4s, v0.s[3] \n" "subs w4, w4, #1 \n" "fmla v24.4s, v8.4s, v1.s[0] \n" "fmla v26.4s, v8.4s, v1.s[1] \n" "fmla v28.4s, v8.4s, v1.s[2] \n" "fmla v30.4s, v8.4s, v1.s[3] \n" "fmla v25.4s, v9.4s, v1.s[0] \n" "fmla v27.4s, v9.4s, v1.s[1] \n" "fmla v29.4s, v9.4s, v1.s[2] \n" "fmla v31.4s, v9.4s, v1.s[3] \n" "bne 2b \n" "3: \n" "st1 {v16.4s, v17.4s}, [%0], #32 \n" "st1 {v18.4s, v19.4s}, [%1], #32 \n" "st1 {v20.4s, v21.4s}, [%2], #32 \n" "st1 {v22.4s, v23.4s}, [%3], #32 \n" "st1 {v24.4s, v25.4s}, [%4], #32 \n" "st1 {v26.4s, v27.4s}, [%5], #32 \n" "st1 {v28.4s, v29.4s}, [%6], #32 \n" "st1 {v30.4s, v31.4s}, [%7], #32 \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(outptr4), // %4 "=r"(outptr5), // %5 "=r"(outptr6), // %6 "=r"(outptr7), // %7 "=r"(tmpptr), // %8 "=r"(kptr) // %9 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(outptr4), "5"(outptr5), "6"(outptr6), "7"(outptr7), "8"(tmpptr), "9"(kptr), "r"(biasptr), // %20 "r"(inch) // %21 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31" ); } for (; i + 3 < size; i += 4) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); const float* kptr = kernel.channel(p / 8); asm volatile( "ld1 {v0.4s, v1.4s}, [%20] \n" "dup v16.4s, v0.s[0] \n" "dup v17.4s, v0.s[1] \n" "dup v18.4s, v0.s[2] \n" "dup v19.4s, v0.s[3] \n" "dup v20.4s, v1.s[0] \n" "dup v21.4s, v1.s[1] \n" "dup v22.4s, v1.s[2] \n" "dup v23.4s, v1.s[3] \n" // inch loop "lsr w4, %w21, #2 \n"// w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%8, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%8], #64 \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v0.s[1] \n" "fmla v18.4s, v8.4s, v0.s[2] \n" "fmla v19.4s, v8.4s, v0.s[3] \n" "fmla v20.4s, v8.4s, v1.s[0] \n" "fmla v21.4s, v8.4s, v1.s[1] \n" "fmla v22.4s, v8.4s, v1.s[2] \n" "fmla v23.4s, v8.4s, v1.s[3] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n" "fmla v16.4s, v9.4s, v2.s[0] \n" "fmla v17.4s, v9.4s, v2.s[1] \n" "fmla v18.4s, v9.4s, v2.s[2] \n" "fmla v19.4s, v9.4s, v2.s[3] \n" "fmla v20.4s, v9.4s, v3.s[0] \n" "fmla v21.4s, v9.4s, v3.s[1] \n" "fmla v22.4s, v9.4s, v3.s[2] \n" "fmla v23.4s, v9.4s, v3.s[3] \n" "subs w4, w4, #1 \n" "fmla v16.4s, v10.4s, v4.s[0] \n" "fmla v17.4s, v10.4s, v4.s[1] \n" "fmla v18.4s, v10.4s, v4.s[2] \n" "fmla v19.4s, v10.4s, v4.s[3] \n" "fmla v20.4s, v10.4s, v5.s[0] \n" "fmla v21.4s, v10.4s, v5.s[1] \n" "fmla v22.4s, v10.4s, v5.s[2] \n" "fmla v23.4s, v10.4s, v5.s[3] \n" "fmla v16.4s, v11.4s, v6.s[0] \n" "fmla v17.4s, v11.4s, v6.s[1] \n" "fmla v18.4s, v11.4s, v6.s[2] \n" "fmla v19.4s, v11.4s, v6.s[3] \n" "fmla v20.4s, v11.4s, v7.s[0] \n" "fmla v21.4s, v11.4s, v7.s[1] \n" "fmla v22.4s, v11.4s, v7.s[2] \n" "fmla v23.4s, v11.4s, v7.s[3] \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w21, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v8.4s}, [%8], #16 \n" "prfm pldl1keep, [%9, #256] \n" "ld1 {v0.4s, v1.4s}, [%9], #32 \n" "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v0.s[1] \n" "fmla v18.4s, v8.4s, v0.s[2] \n" "fmla v19.4s, v8.4s, v0.s[3] \n" "subs w4, w4, #1 \n" "fmla v20.4s, v8.4s, v1.s[0] \n" "fmla v21.4s, v8.4s, v1.s[1] \n" "fmla v22.4s, v8.4s, v1.s[2] \n" "fmla v23.4s, v8.4s, v1.s[3] \n" "bne 2b \n" "3: \n" "st1 {v16.4s}, [%0], #16 \n" "st1 {v17.4s}, [%1], #16 \n" "st1 {v18.4s}, [%2], #16 \n" "st1 {v19.4s}, [%3], #16 \n" "st1 {v20.4s}, [%4], #16 \n" "st1 {v21.4s}, [%5], #16 \n" "st1 {v22.4s}, [%6], #16 \n" "st1 {v23.4s}, [%7], #16 \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(outptr4), // %4 "=r"(outptr5), // %5 "=r"(outptr6), // %6 "=r"(outptr7), // %7 "=r"(tmpptr), // %8 "=r"(kptr) // %9 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(outptr4), "5"(outptr5), "6"(outptr6), "7"(outptr7), "8"(tmpptr), "9"(kptr), "r"(biasptr), // %20 "r"(inch) // %21 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23" ); } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); const float* kptr = kernel.channel(p / 8); asm volatile( "ld1 {v24.4s, v25.4s}, [%20] \n" // inch loop "lsr w4, %w21, #2 \n"// w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "0: \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v8.4s}, [%8], #16 \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n" "fmla v16.4s, v0.4s, v8.s[0] \n" "fmla v17.4s, v1.4s, v8.s[0] \n" "fmla v18.4s, v2.4s, v8.s[1] \n" "fmla v19.4s, v3.4s, v8.s[1] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%9], #64 \n" "subs w4, w4, #1 \n" "fmla v20.4s, v4.4s, v8.s[2] \n" "fmla v21.4s, v5.4s, v8.s[2] \n" "fmla v22.4s, v6.4s, v8.s[3] \n" "fmla v23.4s, v7.4s, v8.s[3] \n" "bne 0b \n" "fadd v16.4s, v16.4s, v18.4s \n" "fadd v17.4s, v17.4s, v19.4s \n" "fadd v20.4s, v20.4s, v22.4s \n" "fadd v21.4s, v21.4s, v23.4s \n" "fadd v16.4s, v16.4s, v20.4s \n" "fadd v17.4s, v17.4s, v21.4s \n" "fadd v24.4s, v24.4s, v16.4s \n" "fadd v25.4s, v25.4s, v17.4s \n" "1: \n" // remain loop "and w4, %w21, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%8, #32] \n" "ld1r {v8.4s}, [%8], #4 \n" "prfm pldl1keep, [%9, #256] \n" "ld1 {v0.4s, v1.4s}, [%9], #32 \n" "subs w4, w4, #1 \n" "fmla v24.4s, v8.4s, v0.4s \n" "fmla v25.4s, v8.4s, v1.4s \n" "bne 2b \n" "3: \n" "st1 {v24.s}[0],[%0], #4 \n" "st1 {v24.s}[1],[%1], #4 \n" "st1 {v24.s}[2],[%2], #4 \n" "st1 {v24.s}[3],[%3], #4 \n" "st1 {v25.s}[0],[%4], #4 \n" "st1 {v25.s}[1],[%5], #4 \n" "st1 {v25.s}[2],[%6], #4 \n" "st1 {v25.s}[3],[%7], #4 \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(outptr4), // %4 "=r"(outptr5), // %5 "=r"(outptr6), // %6 "=r"(outptr7), // %7 "=r"(tmpptr), // %8 "=r"(kptr) // %9 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(outptr4), "5"(outptr5), "6"(outptr6), "7"(outptr7), "8"(tmpptr), "9"(kptr), "r"(biasptr), // %20 "r"(inch) // %21 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25" ); } } #endif // __ARM_NEON && __aarch64__ nn_outch = (outch - remain_outch_start) >> 2; //#pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; float* outptr0 = top_blob.channel(p); float* outptr1 = top_blob.channel(p + 1); float* outptr2 = top_blob.channel(p + 2); float* outptr3 = top_blob.channel(p + 3); const float zeros[4] = { 0.f, 0.f, 0.f, 0.f }; const float* biasptr = bias ? bias + p : zeros; int i = 0; for (; i + 7 < size; i += 8) { const float* tmpptr = tmp.channel(i / 8); #if __ARM_NEON && __aarch64__ const float* kptr = kernel.channel(p / 8 + (p % 8) / 4); #else const float* kptr = kernel.channel(p / 4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v0.4s}, [%12] \n" "dup v8.4s, v0.s[0] \n" "dup v9.4s, v0.s[0] \n" "dup v10.4s, v0.s[1] \n" "dup v11.4s, v0.s[1] \n" "dup v12.4s, v0.s[2] \n" "dup v13.4s, v0.s[2] \n" "dup v14.4s, v0.s[3] \n" "dup v15.4s, v0.s[3] \n" // inch loop "lsr w4, %w13, #2 \n"// w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v10.4s, v4.4s, v0.s[1] \n" "fmla v12.4s, v4.4s, v0.s[2] \n" "fmla v14.4s, v4.4s, v0.s[3] \n" "fmla v9.4s, v5.4s, v0.s[0] \n" "fmla v11.4s, v5.4s, v0.s[1] \n" "fmla v13.4s, v5.4s, v0.s[2] \n" "fmla v15.4s, v5.4s, v0.s[3] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v8.4s, v6.4s, v1.s[0] \n" "fmla v10.4s, v6.4s, v1.s[1] \n" "fmla v12.4s, v6.4s, v1.s[2] \n" "fmla v14.4s, v6.4s, v1.s[3] \n" "fmla v9.4s, v7.4s, v1.s[0] \n" "fmla v11.4s, v7.4s, v1.s[1] \n" "fmla v13.4s, v7.4s, v1.s[2] \n" "fmla v15.4s, v7.4s, v1.s[3] \n" "subs w4, w4, #1 \n" "fmla v8.4s, v16.4s, v2.s[0] \n" "fmla v10.4s, v16.4s, v2.s[1] \n" "fmla v12.4s, v16.4s, v2.s[2] \n" "fmla v14.4s, v16.4s, v2.s[3] \n" "fmla v9.4s, v17.4s, v2.s[0] \n" "fmla v11.4s, v17.4s, v2.s[1] \n" "fmla v13.4s, v17.4s, v2.s[2] \n" "fmla v15.4s, v17.4s, v2.s[3] \n" "fmla v8.4s, v18.4s, v3.s[0] \n" "fmla v10.4s, v18.4s, v3.s[1] \n" "fmla v12.4s, v18.4s, v3.s[2] \n" "fmla v14.4s, v18.4s, v3.s[3] \n" "fmla v9.4s, v19.4s, v3.s[0] \n" "fmla v11.4s, v19.4s, v3.s[1] \n" "fmla v13.4s, v19.4s, v3.s[2] \n" "fmla v15.4s, v19.4s, v3.s[3] \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w13, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v4.4s, v5.4s}, [%4], #32 \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.4s}, [%5], #16 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v10.4s, v4.4s, v0.s[1] \n" "fmla v12.4s, v4.4s, v0.s[2] \n" "fmla v14.4s, v4.4s, v0.s[3] \n" "subs w4, w4, #1 \n" "fmla v9.4s, v5.4s, v0.s[0] \n" "fmla v11.4s, v5.4s, v0.s[1] \n" "fmla v13.4s, v5.4s, v0.s[2] \n" "fmla v15.4s, v5.4s, v0.s[3] \n" "bne 2b \n" "3: \n" "st1 {v8.4s, v9.4s}, [%0], #32 \n" "st1 {v10.4s, v11.4s}, [%1], #32 \n" "st1 {v12.4s, v13.4s}, [%2], #32 \n" "st1 {v14.4s, v15.4s}, [%3], #32 \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(biasptr), // %12 "r"(inch) // %13 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19" ); #else // __aarch64__ asm volatile( "vld1.f32 {d0-d1}, [%12] \n" "vdup.f32 q8, d0[0] \n" "vdup.f32 q9, d0[0] \n" "vdup.f32 q10, d0[1] \n" "vdup.f32 q11, d0[1] \n" "vdup.f32 q12, d1[0] \n" "vdup.f32 q13, d1[0] \n" "vdup.f32 q14, d1[1] \n" "vdup.f32 q15, d1[1] \n" // inch loop "lsr r4, %13, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" "pld [%4, #512] \n" "vldm %4!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%4 :128]! \n" // "vld1.f32 {d12-d15}, [%4 :128]! \n" "pld [%5, #512] \n" "vldm %5!, {d0-d7} \n" // "vld1.f32 {d0-d3}, [%5 :128]! \n" // "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q10, q4, d0[1] \n" "vmla.f32 q12, q4, d1[0] \n" "vmla.f32 q14, q4, d1[1] \n" "vmla.f32 q9, q5, d0[0] \n" "vmla.f32 q11, q5, d0[1] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q15, q5, d1[1] \n" "vmla.f32 q8, q6, d2[0] \n" "vmla.f32 q10, q6, d2[1] \n" "vmla.f32 q12, q6, d3[0] \n" "vmla.f32 q14, q6, d3[1] \n" "vmla.f32 q9, q7, d2[0] \n" "vmla.f32 q11, q7, d2[1] \n" "vmla.f32 q13, q7, d3[0] \n" "vmla.f32 q15, q7, d3[1] \n" "pld [%4, #512] \n" "vldm %4!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%4 :128]! \n" // "vld1.f32 {d12-d15}, [%4 :128]! \n" "vmla.f32 q8, q4, d4[0] \n" "vmla.f32 q10, q4, d4[1] \n" "vmla.f32 q12, q4, d5[0] \n" "vmla.f32 q14, q4, d5[1] \n" "vmla.f32 q9, q5, d4[0] \n" "vmla.f32 q11, q5, d4[1] \n" "vmla.f32 q13, q5, d5[0] \n" "vmla.f32 q15, q5, d5[1] \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q6, d6[0] \n" "vmla.f32 q10, q6, d6[1] \n" "vmla.f32 q12, q6, d7[0] \n" "vmla.f32 q14, q6, d7[1] \n" "vmla.f32 q9, q7, d6[0] \n" "vmla.f32 q11, q7, d6[1] \n" "vmla.f32 q13, q7, d7[0] \n" "vmla.f32 q15, q7, d7[1] \n" "bne 0b \n" "1: \n" // remain loop "and r4, %13, #3 \n"// r4 = remain = inch & 3; "cmp r4, #0 \n" "beq 3f \n" "2: \n" "pld [%4, #256] \n" "vld1.f32 {d8-d11}, [%4 :128]! \n" "pld [%5, #128] \n" "vld1.f32 {d0-d1}, [%5 :128]! \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q10, q4, d0[1] \n" "vmla.f32 q12, q4, d1[0] \n" "vmla.f32 q14, q4, d1[1] \n" "subs r4, r4, #1 \n" "vmla.f32 q9, q5, d0[0] \n" "vmla.f32 q11, q5, d0[1] \n" "vmla.f32 q13, q5, d1[0] \n" "vmla.f32 q15, q5, d1[1] \n" "bne 2b \n" "3: \n" "vst1.f32 {d16-d19}, [%0 :128]! \n" "vst1.f32 {d20-d23}, [%1 :128]! \n" "vst1.f32 {d24-d27}, [%2 :128]! \n" "vst1.f32 {d28-d31}, [%3 :128]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(biasptr), // %12 "r"(inch) // %13 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else float sum0_0 = biasptr[0]; float sum0_1 = biasptr[0]; float sum0_2 = biasptr[0]; float sum0_3 = biasptr[0]; float sum0_4 = biasptr[0]; float sum0_5 = biasptr[0]; float sum0_6 = biasptr[0]; float sum0_7 = biasptr[0]; float sum1_0 = biasptr[1]; float sum1_1 = biasptr[1]; float sum1_2 = biasptr[1]; float sum1_3 = biasptr[1]; float sum1_4 = biasptr[1]; float sum1_5 = biasptr[1]; float sum1_6 = biasptr[1]; float sum1_7 = biasptr[1]; float sum2_0 = biasptr[2]; float sum2_1 = biasptr[2]; float sum2_2 = biasptr[2]; float sum2_3 = biasptr[2]; float sum2_4 = biasptr[2]; float sum2_5 = biasptr[2]; float sum2_6 = biasptr[2]; float sum2_7 = biasptr[2]; float sum3_0 = biasptr[3]; float sum3_1 = biasptr[3]; float sum3_2 = biasptr[3]; float sum3_3 = biasptr[3]; float sum3_4 = biasptr[3]; float sum3_5 = biasptr[3]; float sum3_6 = biasptr[3]; float sum3_7 = biasptr[3]; for (int q = 0; q < inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum0_4 += tmpptr[4] * kptr[0]; sum0_5 += tmpptr[5] * kptr[0]; sum0_6 += tmpptr[6] * kptr[0]; sum0_7 += tmpptr[7] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum1_4 += tmpptr[4] * kptr[1]; sum1_5 += tmpptr[5] * kptr[1]; sum1_6 += tmpptr[6] * kptr[1]; sum1_7 += tmpptr[7] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum2_4 += tmpptr[4] * kptr[2]; sum2_5 += tmpptr[5] * kptr[2]; sum2_6 += tmpptr[6] * kptr[2]; sum2_7 += tmpptr[7] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; sum3_4 += tmpptr[4] * kptr[3]; sum3_5 += tmpptr[5] * kptr[3]; sum3_6 += tmpptr[6] * kptr[3]; sum3_7 += tmpptr[7] * kptr[3]; tmpptr += 8; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr0[4] = sum0_4; outptr0[5] = sum0_5; outptr0[6] = sum0_6; outptr0[7] = sum0_7; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr1[4] = sum1_4; outptr1[5] = sum1_5; outptr1[6] = sum1_6; outptr1[7] = sum1_7; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr2[4] = sum2_4; outptr2[5] = sum2_5; outptr2[6] = sum2_6; outptr2[7] = sum2_7; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr3[4] = sum3_4; outptr3[5] = sum3_5; outptr3[6] = sum3_6; outptr3[7] = sum3_7; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; #endif // __ARM_NEON } for (; i + 3 < size; i += 4) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); #if __ARM_NEON && __aarch64__ const float* kptr = kernel.channel(p / 8 + (p % 8) / 4); #else const float* kptr = kernel.channel(p / 4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v0.4s}, [%12] \n" "dup v8.4s, v0.s[0] \n" "dup v9.4s, v0.s[1] \n" "dup v10.4s, v0.s[2] \n" "dup v11.4s, v0.s[3] \n" // inch loop "lsr w4, %w13, #2 \n"// w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "fmla v8.4s, v5.4s, v1.s[0] \n" "fmla v9.4s, v5.4s, v1.s[1] \n" "fmla v10.4s, v5.4s, v1.s[2] \n" "fmla v11.4s, v5.4s, v1.s[3] \n" "subs w4, w4, #1 \n" "fmla v8.4s, v6.4s, v2.s[0] \n" "fmla v9.4s, v6.4s, v2.s[1] \n" "fmla v10.4s, v6.4s, v2.s[2] \n" "fmla v11.4s, v6.4s, v2.s[3] \n" "fmla v8.4s, v7.4s, v3.s[0] \n" "fmla v9.4s, v7.4s, v3.s[1] \n" "fmla v10.4s, v7.4s, v3.s[2] \n" "fmla v11.4s, v7.4s, v3.s[3] \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w13, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v4.4s}, [%4], #16 \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.4s}, [%5], #16 \n" "subs w4, w4, #1 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "bne 2b \n" "3: \n" "st1 {v8.4s}, [%0], #16 \n" "st1 {v9.4s}, [%1], #16 \n" "st1 {v10.4s}, [%2], #16 \n" "st1 {v11.4s}, [%3], #16 \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(biasptr), // %12 "r"(inch) // %13 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11" ); #else // __aarch64__ asm volatile( "vld1.f32 {d0-d1}, [%12] \n" "vdup.f32 q8, d0[0] \n" "vdup.f32 q9, d0[1] \n" "vdup.f32 q10, d1[0] \n" "vdup.f32 q11, d1[1] \n" // inch loop "lsr r4, %13, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" "pld [%4, #512] \n" "vldm %4!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%4 :128]! \n" // "vld1.f32 {d12-d15}, [%4 :128]! \n" "pld [%5, #512] \n" "vldm %5!, {d0-d7} \n" // "vld1.f32 {d0-d3}, [%5 :128]! \n" // "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d0[1] \n" "vmla.f32 q10, q4, d1[0] \n" "vmla.f32 q11, q4, d1[1] \n" "vmla.f32 q8, q5, d2[0] \n" "vmla.f32 q9, q5, d2[1] \n" "vmla.f32 q10, q5, d3[0] \n" "vmla.f32 q11, q5, d3[1] \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q6, d4[0] \n" "vmla.f32 q9, q6, d4[1] \n" "vmla.f32 q10, q6, d5[0] \n" "vmla.f32 q11, q6, d5[1] \n" "vmla.f32 q8, q7, d6[0] \n" "vmla.f32 q9, q7, d6[1] \n" "vmla.f32 q10, q7, d7[0] \n" "vmla.f32 q11, q7, d7[1] \n" "bne 0b \n" "1: \n" // remain loop "and r4, %13, #3 \n"// r4 = remain = inch & 3; "cmp r4, #0 \n" "beq 3f \n" "2: \n" "pld [%4, #128] \n" "vld1.f32 {d8-d9}, [%4 :128]! \n" "pld [%5, #128] \n" "vld1.f32 {d0-d1}, [%5 :128]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d0[1] \n" "vmla.f32 q10, q4, d1[0] \n" "vmla.f32 q11, q4, d1[1] \n" "bne 2b \n" "3: \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" "vst1.f32 {d20-d21}, [%2 :128]! \n" "vst1.f32 {d22-d23}, [%3 :128]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(biasptr), // %12 "r"(inch) // %13 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11" ); #endif // __aarch64__ #else float sum0_0 = biasptr[0]; float sum0_1 = biasptr[0]; float sum0_2 = biasptr[0]; float sum0_3 = biasptr[0]; float sum1_0 = biasptr[1]; float sum1_1 = biasptr[1]; float sum1_2 = biasptr[1]; float sum1_3 = biasptr[1]; float sum2_0 = biasptr[2]; float sum2_1 = biasptr[2]; float sum2_2 = biasptr[2]; float sum2_3 = biasptr[2]; float sum3_0 = biasptr[3]; float sum3_1 = biasptr[3]; float sum3_2 = biasptr[3]; float sum3_3 = biasptr[3]; for (int q = 0; q < inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; #endif // __ARM_NEON } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); #if __ARM_NEON && __aarch64__ const float* kptr = kernel.channel(p / 8 + (p % 8) / 4); #else const float* kptr = kernel.channel(p / 4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v12.4s}, [%12] \n" // inch loop "lsr w4, %w13, #2 \n"// w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "0: \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v4.4s}, [%4], #16 \n" "prfm pldl1keep, [%5, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n" "subs w4, w4, #1 \n" "fmla v8.4s, v0.4s, v4.s[0] \n" "fmla v9.4s, v1.4s, v4.s[1] \n" "fmla v10.4s, v2.4s, v4.s[2] \n" "fmla v11.4s, v3.4s, v4.s[3] \n" "bne 0b \n" "fadd v8.4s, v8.4s, v9.4s \n" "fadd v10.4s, v10.4s, v11.4s \n" "fadd v8.4s, v8.4s, v10.4s \n" "fadd v12.4s, v12.4s, v8.4s \n" "1: \n" // remain loop "and w4, %w13, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%4, #32] \n" "ld1r {v4.4s}, [%4], #4 \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.4s}, [%5], #16 \n" "subs w4, w4, #1 \n" "fmla v12.4s, v4.4s, v0.4s \n" "bne 2b \n" "3: \n" "st1 {v12.s}[0], [%0], #4 \n" "st1 {v12.s}[1], [%1], #4 \n" "st1 {v12.s}[2], [%2], #4 \n" "st1 {v12.s}[3], [%3], #4 \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(biasptr), // %12 "r"(inch) // %13 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11", "v12" ); #else // __aarch64__ asm volatile( "vld1.f32 {d24-d25}, [%12] \n" // inch loop "lsr r4, %13, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "veor q10, q10, q10 \n" "veor q11, q11, q11 \n" "0: \n" "pld [%4, #128] \n" "vld1.f32 {d8-d9}, [%4 :128]! \n" "pld [%5, #512] \n" "vldm %5!, {d0-d7} \n" // "vld1.f32 {d0-d3}, [%5 :128]! \n" // "vld1.f32 {d4-d7}, [%5 :128]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q0, d8[0] \n" "vmla.f32 q9, q1, d8[1] \n" "vmla.f32 q10, q2, d9[0] \n" "vmla.f32 q11, q3, d9[1] \n" "bne 0b \n" "vadd.f32 q8, q8, q9 \n" "vadd.f32 q10, q10, q11 \n" "vadd.f32 q8, q8, q10 \n" "vadd.f32 q12, q12, q8 \n" "1: \n" // remain loop "and r4, %13, #3 \n"// r4 = remain = inch & 3; "cmp r4, #0 \n" "beq 3f \n" "2: \n" "pld [%4, #32] \n" "vld1.f32 {d8[],d9[]}, [%4]! \n" "pld [%5, #128] \n" "vld1.f32 {d0-d1}, [%5 :128]! \n" "subs r4, r4, #1 \n" "vmla.f32 q12, q4, q0 \n" "bne 2b \n" "3: \n" "vst1.f32 {d24[0]}, [%0]! \n" "vst1.f32 {d24[1]}, [%1]! \n" "vst1.f32 {d25[0]}, [%2]! \n" "vst1.f32 {d25[1]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(biasptr), // %12 "r"(inch) // %13 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11", "q12" ); #endif // __aarch64__ #else float sum0 = biasptr[0]; float sum1 = biasptr[1]; float sum2 = biasptr[2]; float sum3 = biasptr[3]; for (int q = 0; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr++; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; outptr0++; outptr1++; outptr2++; outptr3++; #endif // __ARM_NEON } } remain_outch_start += nn_outch << 2; //#pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out0 = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; float* outptr0 = out0; int i = 0; for (; i + 7 < size; i += 8) { const float* tmpptr = tmp.channel(i / 8); #if __ARM_NEON && __aarch64__ const float* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4); #else const float* kptr = kernel.channel(p / 4 + p % 4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "dup v8.4s, %w6 \n" "dup v9.4s, %w6 \n" // inch loop "lsr w4, %w7, #2 \n"// w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%1, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v0.4s}, [%2], #16 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v5.4s, v0.s[0] \n" "prfm pldl1keep, [%1, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n" "fmla v8.4s, v6.4s, v0.s[1] \n" "fmla v9.4s, v7.4s, v0.s[1] \n" "subs w4, w4, #1 \n" "fmla v8.4s, v12.4s, v0.s[2] \n" "fmla v9.4s, v13.4s, v0.s[2] \n" "fmla v8.4s, v14.4s, v0.s[3] \n" "fmla v9.4s, v15.4s, v0.s[3] \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w7, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v4.4s, v5.4s}, [%1], #32 \n" "prfm pldl1keep, [%2, #32] \n" "ld1r {v0.4s}, [%2], #4 \n" "subs w4, w4, #1 \n" "fmla v8.4s, v4.4s, v0.4s \n" "fmla v9.4s, v5.4s, v0.4s \n" "bne 2b \n" "3: \n" "st1 {v8.4s, v9.4s}, [%0], #32 \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(bias0), // %6 "r"(inch) // %7 : "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v12", "v13", "v14", "v15" ); #else // __aarch64__ asm volatile( "vdup.f32 q8, %6 \n" "vdup.f32 q9, %6 \n" // inch loop "lsr r4, %7, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" "pld [%1, #512] \n" "vldm %1!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%1 :128]! \n" // "vld1.f32 {d12-d15}, [%1 :128]! \n" "pld [%2, #128] \n" "vld1.f32 {d0-d1}, [%2 :128]! \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q5, d0[0] \n" "pld [%1, #512] \n" "vldm %1!, {d24-d31} \n" // "vld1.f32 {d24-d27}, [%1 :128]! \n" // "vld1.f32 {d28-d31}, [%1 :128]! \n" "vmla.f32 q8, q6, d0[1] \n" "vmla.f32 q9, q7, d0[1] \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q12, d1[0] \n" "vmla.f32 q9, q13, d1[0] \n" "vmla.f32 q8, q14, d1[1] \n" "vmla.f32 q9, q15, d1[1] \n" "bne 0b \n" "1: \n" // remain loop "and r4, %7, #3 \n"// r4 = remain = inch & 3; "cmp r4, #0 \n" "beq 3f \n" "2: \n" "pld [%1, #256] \n" "vld1.f32 {d8-d11}, [%1 :128]! \n" "pld [%2, #32] \n" "vld1.f32 {d0[],d1[]}, [%2]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q4, q0 \n" "vmla.f32 q9, q5, q0 \n" "bne 2b \n" "3: \n" "vst1.f32 {d16-d19}, [%0 :128]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(bias0), // %6 "r"(inch) // %7 : "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else float sum0 = bias0; float sum1 = bias0; float sum2 = bias0; float sum3 = bias0; float sum4 = bias0; float sum5 = bias0; float sum6 = bias0; float sum7 = bias0; for (int q = 0; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; sum4 += tmpptr[4] * kptr[0]; sum5 += tmpptr[5] * kptr[0]; sum6 += tmpptr[6] * kptr[0]; sum7 += tmpptr[7] * kptr[0]; tmpptr += 8; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0[4] = sum4; outptr0[5] = sum5; outptr0[6] = sum6; outptr0[7] = sum7; outptr0 += 8; #endif // __ARM_NEON } for (; i + 3 < size; i += 4) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); #if __ARM_NEON && __aarch64__ const float* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4); #else const float* kptr = kernel.channel(p / 4 + p % 4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "dup v8.4s, %w6 \n" // inch loop "lsr w4, %w7, #2 \n"// w4 = nn = inch >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n" "prfm pldl1keep, [%1, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v0.4s}, [%2], #16 \n" "subs w4, w4, #1 \n" "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v8.4s, v5.4s, v0.s[1] \n" "fmla v8.4s, v6.4s, v0.s[2] \n" "fmla v8.4s, v7.4s, v0.s[3] \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w7, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v4.4s}, [%1], #16 \n" "prfm pldl1keep, [%2, #32] \n" "ld1r {v0.4s}, [%2], #4 \n" "subs w4, w4, #1 \n" "fmla v8.4s, v4.4s, v0.4s \n" "bne 2b \n" "3: \n" "st1 {v8.4s}, [%0], #16 \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(bias0), // %6 "r"(inch) // %7 : "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8" ); #else // __aarch64__ asm volatile( "vdup.f32 q8, %6 \n" // inch loop "lsr r4, %7, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n" "pld [%1, #512] \n" "vldm %1!, {d8-d15} \n" // "vld1.f32 {d8-d11}, [%1 :128]! \n" // "vld1.f32 {d12-d15}, [%1 :128]! \n" "pld [%2, #128] \n" "vld1.f32 {d0-d1}, [%2]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q8, q5, d0[1] \n" "vmla.f32 q8, q6, d1[0] \n" "vmla.f32 q8, q7, d1[1] \n" "bne 0b \n" "1: \n" // remain loop "and r4, %7, #3 \n"// r4 = remain = inch & 3; "cmp r4, #0 \n" "beq 3f \n" "2: \n" "pld [%1, #128] \n" "vld1.f32 {d8-d9}, [%1 :128]! \n" "pld [%2, #32] \n" "vld1.f32 {d0[],d1[]}, [%2]! \n" "subs r4, r4, #1 \n" "vmla.f32 q8, q4, q0 \n" "bne 2b \n" "3: \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(bias0), // %6 "r"(inch) // %7 : "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8" ); #endif // __aarch64__ #else float sum0 = bias0; float sum1 = bias0; float sum2 = bias0; float sum3 = bias0; for (int q = 0; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0 += 4; #endif // __ARM_NEON } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); #if __ARM_NEON && __aarch64__ const float* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4); #else const float* kptr = kernel.channel(p / 4 + p % 4); #endif // __ARM_NEON && __aarch64__ int q = 0; #if __ARM_NEON float32x4_t _sum0 = vdupq_n_f32(0.f); for (; q + 3 < inch; q += 4) { float32x4_t _p0 = vld1q_f32(tmpptr); tmpptr += 4; float32x4_t _k0 = vld1q_f32(kptr); kptr += 4; #if __aarch64__ _sum0 = vfmaq_f32(_sum0, _p0, _k0); #else _sum0 = vmlaq_f32(_sum0, _p0, _k0); #endif } #if __aarch64__ float sum0 = bias0 + vaddvq_f32(_sum0); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0)); float sum0 = bias0 + vget_lane_f32(vpadd_f32(_ss, _ss), 0); #endif #else float sum0 = bias0; #endif // __ARM_NEON for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } // // NOTE sgemm // for (; p<outch; p++) // { // Mat out0 = top_blob.channel(p); // // const float bias0 = bias ? bias[p] : 0.f; // // float* outptr0 = out0; // // for (int i=0; i<size; i++) // { // float sum = bias0; // // const float* kptr = _kernel.channel(p/8 + p%8); // // for (int q=0; q<inch; q++) // { // const float* img0 = bottom_blob.channel(q); // // sum += img0[i] * kptr[0]; // kptr ++; // } // // outptr0[i] = sum; // } // } } }
SuperRayGenerator.h
/* * Copyright(c) 2016, Youngsun Kwon, Donghyuk Kim, and Sung-eui Yoon, KAIST * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met : * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and / or other materials provided with the distribution. * * Neither the name of SuperRay nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef GRIDMAP3D_SUPERRAY_SUPERRAY_GENERATOR_H #define GRIDMAP3D_SUPERRAY_SUPERRAY_GENERATOR_H #include <gridmap3D/gridmap3D_types.h> #include <gridmap3D/Grid3DKey.h> #include <gridmap3D/Pointcloud.h> #include <gridmap3D_superray/SuperRayCloud.h> #ifdef _OPENMP #include <omp.h> #pragma omp declare reduction (merge : std::vector<gridmap3D::SuperRay> : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end())) #endif namespace gridmap3D{ class SuperRayGenerator{ public: SuperRayGenerator(const double _resolution, const unsigned int _grid_max_val, const int _threshold = 0); ~SuperRayGenerator() {}; void GenerateSuperRay(const Pointcloud& _pc, const point3d& _origin, SuperRayCloud& _srcloud); protected: struct VoxelInfo; struct Axis3D; point3d originW; // origin point in World Space Grid3DKey originKey; // origin key // constants for generating super rays double RESOLUTION; // resolution double RESOLUTION_FACTOR; // 1.0 / resolution unsigned int GRID_MAX_VAL; // offset unsigned int THRESHOLD; // threshold for limiting to generate super rays for each voxel // Functions for generating super rays void GenerateSuperRay(const point3d_collection& _pointlist, std::vector<SuperRay>& _srcloud); void GenerateSuperRay2D(const point3d_collection& _pointlist, Axis3D& _axis, VoxelInfo& _voxelinfo, std::vector<SuperRay>& _srcloud); void GenerateSuperRay3D(const point3d_collection& _pointlist, Axis3D& _axis, VoxelInfo& _voxelinfo, std::vector<SuperRay>& _srcloud); // Function for generating mapping line in 2-D double GenerateMappingLine(VoxelInfo& _voxelinfo, const unsigned int& _axisX, const unsigned int& _axisY, std::vector<double>& _mappingPlane); // Utility functions typedef unordered_ns::unordered_map<Grid3DKey, std::vector<point3d>, Grid3DKey::KeyHash> Voxelized_Pointclouds; void ComputeAxis(const point3d& _min, const point3d& _max, Axis3D& _axis); // Re-implmentation for Key / coordinate conversion functions inline Grid3DKey coordToKey(const point3d& coord) const { return Grid3DKey(coordToKey(coord(0)), coordToKey(coord(1)), coordToKey(coord(2))); } inline key_type coordToKey(double coordinate) const { return ((int)floor(RESOLUTION_FACTOR * coordinate)) + GRID_MAX_VAL; } // Structures that represents the traversal information struct VoxelInfo{ VoxelInfo(void) {}; // Voxel Info. point3d minW; // min position of voxel point3d maxW; // max position of voxel Grid3DKey voxelKey; // key of voxel }; struct Axis3D{ Axis3D(void) : axisU(0), axisV(1), axisK(2) {}; unsigned int axisU; // Nearest Axis unsigned int axisV; // unsigned int axisK; // Farthest Axis }; }; } #endif
decl2.c
/* Process declarations and variables for C++ compiler. Copyright (C) 1988-2015 Free Software Foundation, Inc. Hacked by Michael Tiemann (tiemann@cygnus.com) This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ /* Process declarations and symbol lookup for C++ front end. Also constructs types; the standard scalar types at initialization, and structure, union, array and enum types when they are declared. */ /* ??? not all decl nodes are given the most useful possible line numbers. For example, the CONST_DECLs for enum values. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "hash-set.h" #include "machmode.h" #include "vec.h" #include "double-int.h" #include "input.h" #include "alias.h" #include "symtab.h" #include "wide-int.h" #include "inchash.h" #include "tree.h" #include "stringpool.h" #include "varasm.h" #include "attribs.h" #include "stor-layout.h" #include "calls.h" #include "flags.h" #include "cp-tree.h" #include "decl.h" #include "toplev.h" #include "timevar.h" #include "cpplib.h" #include "target.h" #include "c-family/c-common.h" #include "c-family/c-objc.h" #include "hash-map.h" #include "is-a.h" #include "plugin-api.h" #include "hard-reg-set.h" #include "input.h" #include "function.h" #include "ipa-ref.h" #include "cgraph.h" #include "tree-inline.h" #include "c-family/c-pragma.h" #include "dumpfile.h" #include "intl.h" #include "splay-tree.h" #include "langhooks.h" #include "c-family/c-ada-spec.h" #include "asan.h" extern cpp_reader *parse_in; /* This structure contains information about the initializations and/or destructions required for a particular priority level. */ typedef struct priority_info_s { /* Nonzero if there have been any initializations at this priority throughout the translation unit. */ int initializations_p; /* Nonzero if there have been any destructions at this priority throughout the translation unit. */ int destructions_p; } *priority_info; static void mark_vtable_entries (tree); static bool maybe_emit_vtables (tree); static bool acceptable_java_type (tree); static tree start_objects (int, int); static void finish_objects (int, int, tree); static tree start_static_storage_duration_function (unsigned); static void finish_static_storage_duration_function (tree); static priority_info get_priority_info (int); static void do_static_initialization_or_destruction (tree, bool); static void one_static_initialization_or_destruction (tree, tree, bool); static void generate_ctor_or_dtor_function (bool, int, location_t *); static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node, void *); static tree prune_vars_needing_no_initialization (tree *); static void write_out_vars (tree); static void import_export_class (tree); static tree get_guard_bits (tree); static void determine_visibility_from_class (tree, tree); static bool determine_hidden_inline (tree); static bool decl_defined_p (tree); /* A list of static class variables. This is needed, because a static class variable can be declared inside the class without an initializer, and then initialized, statically, outside the class. */ static GTY(()) vec<tree, va_gc> *pending_statics; /* A list of functions which were declared inline, but which we may need to emit outline anyway. */ static GTY(()) vec<tree, va_gc> *deferred_fns; /* A list of decls that use types with no linkage, which we need to make sure are defined. */ static GTY(()) vec<tree, va_gc> *no_linkage_decls; /* Nonzero if we're done parsing and into end-of-file activities. */ int at_eof; /* Return a member function type (a METHOD_TYPE), given FNTYPE (a FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers that apply to the function). */ tree build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals, cp_ref_qualifier rqual) { tree raises; tree attrs; int type_quals; bool late_return_type_p; if (fntype == error_mark_node || ctype == error_mark_node) return error_mark_node; gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE || TREE_CODE (fntype) == METHOD_TYPE); type_quals = quals & ~TYPE_QUAL_RESTRICT; ctype = cp_build_qualified_type (ctype, type_quals); raises = TYPE_RAISES_EXCEPTIONS (fntype); attrs = TYPE_ATTRIBUTES (fntype); late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (fntype); fntype = build_method_type_directly (ctype, TREE_TYPE (fntype), (TREE_CODE (fntype) == METHOD_TYPE ? TREE_CHAIN (TYPE_ARG_TYPES (fntype)) : TYPE_ARG_TYPES (fntype))); if (attrs) fntype = cp_build_type_attribute_variant (fntype, attrs); if (rqual) fntype = build_ref_qualified_type (fntype, rqual); if (raises) fntype = build_exception_variant (fntype, raises); if (late_return_type_p) TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1; return fntype; } /* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its return type changed to NEW_RET. */ tree change_return_type (tree new_ret, tree fntype) { tree newtype; tree args = TYPE_ARG_TYPES (fntype); tree raises = TYPE_RAISES_EXCEPTIONS (fntype); tree attrs = TYPE_ATTRIBUTES (fntype); bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (fntype); if (new_ret == error_mark_node) return fntype; if (same_type_p (new_ret, TREE_TYPE (fntype))) return fntype; if (TREE_CODE (fntype) == FUNCTION_TYPE) { newtype = build_function_type (new_ret, args); newtype = apply_memfn_quals (newtype, type_memfn_quals (fntype), type_memfn_rqual (fntype)); } else newtype = build_method_type_directly (class_of_this_parm (fntype), new_ret, TREE_CHAIN (args)); if (raises) newtype = build_exception_variant (newtype, raises); if (attrs) newtype = cp_build_type_attribute_variant (newtype, attrs); if (late_return_type_p) TYPE_HAS_LATE_RETURN_TYPE (newtype) = 1; return newtype; } /* Build a PARM_DECL with NAME and TYPE, and set DECL_ARG_TYPE appropriately. */ tree cp_build_parm_decl (tree name, tree type) { tree parm = build_decl (input_location, PARM_DECL, name, type); /* DECL_ARG_TYPE is only used by the back end and the back end never sees templates. */ if (!processing_template_decl) DECL_ARG_TYPE (parm) = type_passed_as (type); return parm; } /* Returns a PARM_DECL for a parameter of the indicated TYPE, with the indicated NAME. */ tree build_artificial_parm (tree name, tree type) { tree parm = cp_build_parm_decl (name, type); DECL_ARTIFICIAL (parm) = 1; /* All our artificial parms are implicitly `const'; they cannot be assigned to. */ TREE_READONLY (parm) = 1; return parm; } /* Constructors for types with virtual baseclasses need an "in-charge" flag saying whether this constructor is responsible for initialization of virtual baseclasses or not. All destructors also need this "in-charge" flag, which additionally determines whether or not the destructor should free the memory for the object. This function adds the "in-charge" flag to member function FN if appropriate. It is called from grokclassfn and tsubst. FN must be either a constructor or destructor. The in-charge flag follows the 'this' parameter, and is followed by the VTT parm (if any), then the user-written parms. */ void maybe_retrofit_in_chrg (tree fn) { tree basetype, arg_types, parms, parm, fntype; /* If we've already add the in-charge parameter don't do it again. */ if (DECL_HAS_IN_CHARGE_PARM_P (fn)) return; /* When processing templates we can't know, in general, whether or not we're going to have virtual baseclasses. */ if (processing_template_decl) return; /* We don't need an in-charge parameter for constructors that don't have virtual bases. */ if (DECL_CONSTRUCTOR_P (fn) && !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn))) return; arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn)); basetype = TREE_TYPE (TREE_VALUE (arg_types)); arg_types = TREE_CHAIN (arg_types); parms = DECL_CHAIN (DECL_ARGUMENTS (fn)); /* If this is a subobject constructor or destructor, our caller will pass us a pointer to our VTT. */ if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn))) { parm = build_artificial_parm (vtt_parm_identifier, vtt_parm_type); /* First add it to DECL_ARGUMENTS between 'this' and the real args... */ DECL_CHAIN (parm) = parms; parms = parm; /* ...and then to TYPE_ARG_TYPES. */ arg_types = hash_tree_chain (vtt_parm_type, arg_types); DECL_HAS_VTT_PARM_P (fn) = 1; } /* Then add the in-charge parm (before the VTT parm). */ parm = build_artificial_parm (in_charge_identifier, integer_type_node); DECL_CHAIN (parm) = parms; parms = parm; arg_types = hash_tree_chain (integer_type_node, arg_types); /* Insert our new parameter(s) into the list. */ DECL_CHAIN (DECL_ARGUMENTS (fn)) = parms; /* And rebuild the function type. */ fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)), arg_types); if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn))) fntype = build_exception_variant (fntype, TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn))); if (TYPE_ATTRIBUTES (TREE_TYPE (fn))) fntype = (cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn)))); TREE_TYPE (fn) = fntype; /* Now we've got the in-charge parameter. */ DECL_HAS_IN_CHARGE_PARM_P (fn) = 1; } /* Classes overload their constituent function names automatically. When a function name is declared in a record structure, its name is changed to it overloaded name. Since names for constructors and destructors can conflict, we place a leading '$' for destructors. CNAME is the name of the class we are grokking for. FUNCTION is a FUNCTION_DECL. It was created by `grokdeclarator'. FLAGS contains bits saying what's special about today's arguments. DTOR_FLAG == DESTRUCTOR. If FUNCTION is a destructor, then we must add the `auto-delete' field as a second parameter. There is some hair associated with the fact that we must "declare" this variable in the manner consistent with the way the rest of the arguments were declared. QUALS are the qualifiers for the this pointer. */ void grokclassfn (tree ctype, tree function, enum overload_flags flags) { tree fn_name = DECL_NAME (function); /* Even within an `extern "C"' block, members get C++ linkage. See [dcl.link] for details. */ SET_DECL_LANGUAGE (function, lang_cplusplus); if (fn_name == NULL_TREE) { error ("name missing for member function"); fn_name = get_identifier ("<anonymous>"); DECL_NAME (function) = fn_name; } DECL_CONTEXT (function) = ctype; if (flags == DTOR_FLAG) DECL_DESTRUCTOR_P (function) = 1; if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function)) maybe_retrofit_in_chrg (function); } /* Create an ARRAY_REF, checking for the user doing things backwards along the way. DECLTYPE_P is for N3276, as in the parser. */ tree grok_array_decl (location_t loc, tree array_expr, tree index_exp, bool decltype_p) { tree type; tree expr; tree orig_array_expr = array_expr; tree orig_index_exp = index_exp; if (error_operand_p (array_expr) || error_operand_p (index_exp)) return error_mark_node; if (processing_template_decl) { if (type_dependent_expression_p (array_expr) || type_dependent_expression_p (index_exp)) return build_min_nt_loc (loc, ARRAY_REF, array_expr, index_exp, NULL_TREE, NULL_TREE); array_expr = build_non_dependent_expr (array_expr); index_exp = build_non_dependent_expr (index_exp); } type = TREE_TYPE (array_expr); gcc_assert (type); type = non_reference (type); /* If they have an `operator[]', use that. */ if (MAYBE_CLASS_TYPE_P (type) || MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp))) { tsubst_flags_t complain = tf_warning_or_error; if (decltype_p) complain |= tf_decltype; expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr, index_exp, NULL_TREE, /*overload=*/NULL, complain); } else { tree p1, p2, i1, i2; /* Otherwise, create an ARRAY_REF for a pointer or array type. It is a little-known fact that, if `a' is an array and `i' is an int, you can write `i[a]', which means the same thing as `a[i]'. */ if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE) p1 = array_expr; else p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false); if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE) p2 = index_exp; else p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false); i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr, false); i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp, false); if ((p1 && i2) && (i1 && p2)) error ("ambiguous conversion for array subscript"); if (p1 && i2) array_expr = p1, index_exp = i2; else if (i1 && p2) array_expr = p2, index_exp = i1; else { error ("invalid types %<%T[%T]%> for array subscript", type, TREE_TYPE (index_exp)); return error_mark_node; } if (array_expr == error_mark_node || index_exp == error_mark_node) error ("ambiguous conversion for array subscript"); expr = build_array_ref (input_location, array_expr, index_exp); } if (processing_template_decl && expr != error_mark_node) return build_min_non_dep (ARRAY_REF, expr, orig_array_expr, orig_index_exp, NULL_TREE, NULL_TREE); return expr; } /* Given the cast expression EXP, checking out its validity. Either return an error_mark_node if there was an unavoidable error, return a cast to void for trying to delete a pointer w/ the value 0, or return the call to delete. If DOING_VEC is true, we handle things differently for doing an array delete. Implements ARM $5.3.4. This is called from the parser. */ tree delete_sanity (tree exp, tree size, bool doing_vec, int use_global_delete, tsubst_flags_t complain) { tree t, type; if (exp == error_mark_node) return exp; if (processing_template_decl) { t = build_min (DELETE_EXPR, void_type_node, exp, size); DELETE_EXPR_USE_GLOBAL (t) = use_global_delete; DELETE_EXPR_USE_VEC (t) = doing_vec; TREE_SIDE_EFFECTS (t) = 1; return t; } /* An array can't have been allocated by new, so complain. */ if (TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE) warning (0, "deleting array %q#E", exp); t = build_expr_type_conversion (WANT_POINTER, exp, true); if (t == NULL_TREE || t == error_mark_node) { error ("type %q#T argument given to %<delete%>, expected pointer", TREE_TYPE (exp)); return error_mark_node; } type = TREE_TYPE (t); /* As of Valley Forge, you can delete a pointer to const. */ /* You can't delete functions. */ if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE) { error ("cannot delete a function. Only pointer-to-objects are " "valid arguments to %<delete%>"); return error_mark_node; } /* Deleting ptr to void is undefined behavior [expr.delete/3]. */ if (VOID_TYPE_P (TREE_TYPE (type))) { warning (OPT_Wdelete_incomplete, "deleting %qT is undefined", type); doing_vec = 0; } /* Deleting a pointer with the value zero is valid and has no effect. */ if (integer_zerop (t)) return build1 (NOP_EXPR, void_type_node, t); if (doing_vec) return build_vec_delete (t, /*maxindex=*/NULL_TREE, sfk_deleting_destructor, use_global_delete, complain); else return build_delete (type, t, sfk_deleting_destructor, LOOKUP_NORMAL, use_global_delete, complain); } /* Report an error if the indicated template declaration is not the sort of thing that should be a member template. */ void check_member_template (tree tmpl) { tree decl; gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL); decl = DECL_TEMPLATE_RESULT (tmpl); if (TREE_CODE (decl) == FUNCTION_DECL || DECL_ALIAS_TEMPLATE_P (tmpl) || (TREE_CODE (decl) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (decl)))) { /* The parser rejects template declarations in local classes (with the exception of generic lambdas). */ gcc_assert (!current_function_decl || LAMBDA_FUNCTION_P (decl)); /* The parser rejects any use of virtual in a function template. */ gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl))); /* The debug-information generating code doesn't know what to do with member templates. */ DECL_IGNORED_P (tmpl) = 1; } else if (variable_template_p (tmpl)) /* OK */; else error ("template declaration of %q#D", decl); } /* Return true iff TYPE is a valid Java parameter or return type. */ static bool acceptable_java_type (tree type) { if (type == error_mark_node) return false; if (VOID_TYPE_P (type) || TYPE_FOR_JAVA (type)) return true; if (TYPE_PTR_P (type) || TREE_CODE (type) == REFERENCE_TYPE) { type = TREE_TYPE (type); if (TREE_CODE (type) == RECORD_TYPE) { tree args; int i; if (! TYPE_FOR_JAVA (type)) return false; if (! CLASSTYPE_TEMPLATE_INFO (type)) return true; args = CLASSTYPE_TI_ARGS (type); i = TREE_VEC_LENGTH (args); while (--i >= 0) { type = TREE_VEC_ELT (args, i); if (TYPE_PTR_P (type)) type = TREE_TYPE (type); if (! TYPE_FOR_JAVA (type)) return false; } return true; } } return false; } /* For a METHOD in a Java class CTYPE, return true if the parameter and return types are valid Java types. Otherwise, print appropriate error messages, and return false. */ bool check_java_method (tree method) { bool jerr = false; tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (method)); tree ret_type = TREE_TYPE (TREE_TYPE (method)); if (!acceptable_java_type (ret_type)) { error ("Java method %qD has non-Java return type %qT", method, ret_type); jerr = true; } arg_types = TREE_CHAIN (arg_types); if (DECL_HAS_IN_CHARGE_PARM_P (method)) arg_types = TREE_CHAIN (arg_types); if (DECL_HAS_VTT_PARM_P (method)) arg_types = TREE_CHAIN (arg_types); for (; arg_types != NULL_TREE; arg_types = TREE_CHAIN (arg_types)) { tree type = TREE_VALUE (arg_types); if (!acceptable_java_type (type)) { if (type != error_mark_node) error ("Java method %qD has non-Java parameter type %qT", method, type); jerr = true; } } return !jerr; } /* Sanity check: report error if this function FUNCTION is not really a member of the class (CTYPE) it is supposed to belong to. TEMPLATE_PARMS is used to specify the template parameters of a member template passed as FUNCTION_DECL. If the member template is passed as a TEMPLATE_DECL, it can be NULL since the parameters can be extracted from the declaration. If the function is not a function template, it must be NULL. It returns the original declaration for the function, NULL_TREE if no declaration was found, error_mark_node if an error was emitted. */ tree check_classfn (tree ctype, tree function, tree template_parms) { int ix; bool is_template; tree pushed_scope; if (DECL_USE_TEMPLATE (function) && !(TREE_CODE (function) == TEMPLATE_DECL && DECL_TEMPLATE_SPECIALIZATION (function)) && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function))) /* Since this is a specialization of a member template, we're not going to find the declaration in the class. For example, in: struct S { template <typename T> void f(T); }; template <> void S::f(int); we're not going to find `S::f(int)', but there's no reason we should, either. We let our callers know we didn't find the method, but we don't complain. */ return NULL_TREE; /* Basic sanity check: for a template function, the template parameters either were not passed, or they are the same of DECL_TEMPLATE_PARMS. */ if (TREE_CODE (function) == TEMPLATE_DECL) { if (template_parms && !comp_template_parms (template_parms, DECL_TEMPLATE_PARMS (function))) { error ("template parameter lists provided don%'t match the " "template parameters of %qD", function); return error_mark_node; } template_parms = DECL_TEMPLATE_PARMS (function); } /* OK, is this a definition of a member template? */ is_template = (template_parms != NULL_TREE); /* [temp.mem] A destructor shall not be a member template. */ if (DECL_DESTRUCTOR_P (function) && is_template) { error ("destructor %qD declared as member template", function); return error_mark_node; } /* We must enter the scope here, because conversion operators are named by target type, and type equivalence relies on typenames resolving within the scope of CTYPE. */ pushed_scope = push_scope (ctype); ix = class_method_index_for_fn (complete_type (ctype), function); if (ix >= 0) { vec<tree, va_gc> *methods = CLASSTYPE_METHOD_VEC (ctype); tree fndecls, fndecl = 0; bool is_conv_op; const char *format = NULL; for (fndecls = (*methods)[ix]; fndecls; fndecls = OVL_NEXT (fndecls)) { tree p1, p2; fndecl = OVL_CURRENT (fndecls); p1 = TYPE_ARG_TYPES (TREE_TYPE (function)); p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl)); /* We cannot simply call decls_match because this doesn't work for static member functions that are pretending to be methods, and because the name may have been changed by asm("new_name"). */ /* Get rid of the this parameter on functions that become static. */ if (DECL_STATIC_FUNCTION_P (fndecl) && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE) p1 = TREE_CHAIN (p1); /* A member template definition only matches a member template declaration. */ if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL)) continue; /* ref-qualifier or absence of same must match. */ if (type_memfn_rqual (TREE_TYPE (function)) != type_memfn_rqual (TREE_TYPE (fndecl))) continue; /* While finding a match, same types and params are not enough if the function is versioned. Also check version ("target") attributes. */ if (same_type_p (TREE_TYPE (TREE_TYPE (function)), TREE_TYPE (TREE_TYPE (fndecl))) && compparms (p1, p2) && !targetm.target_option.function_versions (function, fndecl) && (!is_template || comp_template_parms (template_parms, DECL_TEMPLATE_PARMS (fndecl))) && (DECL_TEMPLATE_SPECIALIZATION (function) == DECL_TEMPLATE_SPECIALIZATION (fndecl)) && (!DECL_TEMPLATE_SPECIALIZATION (function) || (DECL_TI_TEMPLATE (function) == DECL_TI_TEMPLATE (fndecl)))) break; } if (fndecls) { if (pushed_scope) pop_scope (pushed_scope); return OVL_CURRENT (fndecls); } error_at (DECL_SOURCE_LOCATION (function), "prototype for %q#D does not match any in class %qT", function, ctype); is_conv_op = DECL_CONV_FN_P (fndecl); if (is_conv_op) ix = CLASSTYPE_FIRST_CONVERSION_SLOT; fndecls = (*methods)[ix]; while (fndecls) { fndecl = OVL_CURRENT (fndecls); fndecls = OVL_NEXT (fndecls); if (!fndecls && is_conv_op) { if (methods->length () > (size_t) ++ix) { fndecls = (*methods)[ix]; if (!DECL_CONV_FN_P (OVL_CURRENT (fndecls))) { fndecls = NULL_TREE; is_conv_op = false; } } else is_conv_op = false; } if (format) format = " %+#D"; else if (fndecls) format = N_("candidates are: %+#D"); else format = N_("candidate is: %+#D"); error (format, fndecl); } } else if (!COMPLETE_TYPE_P (ctype)) cxx_incomplete_type_error (function, ctype); else error ("no %q#D member function declared in class %qT", function, ctype); if (pushed_scope) pop_scope (pushed_scope); return error_mark_node; } /* DECL is a function with vague linkage. Remember it so that at the end of the translation unit we can decide whether or not to emit it. */ void note_vague_linkage_fn (tree decl) { DECL_DEFER_OUTPUT (decl) = 1; vec_safe_push (deferred_fns, decl); } /* As above, but for variable template instantiations. */ void note_variable_template_instantiation (tree decl) { vec_safe_push (pending_statics, decl); } /* We have just processed the DECL, which is a static data member. The other parameters are as for cp_finish_decl. */ void finish_static_data_member_decl (tree decl, tree init, bool init_const_expr_p, tree asmspec_tree, int flags) { DECL_CONTEXT (decl) = current_class_type; /* We cannot call pushdecl here, because that would fill in the TREE_CHAIN of our decl. Instead, we modify cp_finish_decl to do the right thing, namely, to put this decl out straight away. */ if (! processing_template_decl) vec_safe_push (pending_statics, decl); if (LOCAL_CLASS_P (current_class_type) /* We already complained about the template definition. */ && !DECL_TEMPLATE_INSTANTIATION (decl)) permerror (input_location, "local class %q#T shall not have static data member %q#D", current_class_type, decl); else for (tree t = current_class_type; TYPE_P (t); t = CP_TYPE_CONTEXT (t)) if (TYPE_ANONYMOUS_P (t)) { if (permerror (DECL_SOURCE_LOCATION (decl), "static data member %qD in unnamed class", decl)) inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "unnamed class defined here"); break; } DECL_IN_AGGR_P (decl) = 1; if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE && TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE) SET_VAR_HAD_UNKNOWN_BOUND (decl); cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags); } /* DECLARATOR and DECLSPECS correspond to a class member. The other parameters are as for cp_finish_decl. Return the DECL for the class member declared. */ tree grokfield (const cp_declarator *declarator, cp_decl_specifier_seq *declspecs, tree init, bool init_const_expr_p, tree asmspec_tree, tree attrlist) { tree value; const char *asmspec = 0; int flags; tree name; if (init && TREE_CODE (init) == TREE_LIST && TREE_VALUE (init) == error_mark_node && TREE_CHAIN (init) == NULL_TREE) init = NULL_TREE; value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist); if (! value || value == error_mark_node) /* friend or constructor went bad. */ return error_mark_node; if (TREE_TYPE (value) == error_mark_node) return value; if (TREE_CODE (value) == TYPE_DECL && init) { error ("typedef %qD is initialized (use decltype instead)", value); init = NULL_TREE; } /* Pass friendly classes back. */ if (value == void_type_node) return value; name = DECL_NAME (value); if (name != NULL_TREE) { if (TREE_CODE (name) == TEMPLATE_ID_EXPR) { error ("explicit template argument list not allowed"); return error_mark_node; } if (IDENTIFIER_POINTER (name)[0] == '_' && ! strcmp (IDENTIFIER_POINTER (name), "_vptr")) error ("member %qD conflicts with virtual function table field name", value); } /* Stash away type declarations. */ if (TREE_CODE (value) == TYPE_DECL) { DECL_NONLOCAL (value) = 1; DECL_CONTEXT (value) = current_class_type; if (attrlist) { int attrflags = 0; /* If this is a typedef that names the class for linkage purposes (7.1.3p8), apply any attributes directly to the type. */ if (OVERLOAD_TYPE_P (TREE_TYPE (value)) && value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value)))) attrflags = ATTR_FLAG_TYPE_IN_PLACE; cplus_decl_attributes (&value, attrlist, attrflags); } if (decl_spec_seq_has_spec_p (declspecs, ds_typedef) && TREE_TYPE (value) != error_mark_node && TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value) set_underlying_type (value); /* It's important that push_template_decl below follows set_underlying_type above so that the created template carries the properly set type of VALUE. */ if (processing_template_decl) value = push_template_decl (value); record_locally_defined_typedef (value); return value; } int friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend); if (!friendp && DECL_IN_AGGR_P (value)) { error ("%qD is already defined in %qT", value, DECL_CONTEXT (value)); return void_type_node; } if (asmspec_tree && asmspec_tree != error_mark_node) asmspec = TREE_STRING_POINTER (asmspec_tree); if (init) { if (TREE_CODE (value) == FUNCTION_DECL) { if (init == ridpointers[(int)RID_DELETE]) { DECL_DELETED_FN (value) = 1; DECL_DECLARED_INLINE_P (value) = 1; DECL_INITIAL (value) = error_mark_node; } else if (init == ridpointers[(int)RID_DEFAULT]) { if (defaultable_fn_check (value)) { DECL_DEFAULTED_FN (value) = 1; DECL_INITIALIZED_IN_CLASS_P (value) = 1; DECL_DECLARED_INLINE_P (value) = 1; } } else if (TREE_CODE (init) == DEFAULT_ARG) error ("invalid initializer for member function %qD", value); else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE) { if (integer_zerop (init)) DECL_PURE_VIRTUAL_P (value) = 1; else if (error_operand_p (init)) ; /* An error has already been reported. */ else error ("invalid initializer for member function %qD", value); } else { gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE); if (friendp) error ("initializer specified for friend function %qD", value); else error ("initializer specified for static member function %qD", value); } } else if (TREE_CODE (value) == FIELD_DECL) /* C++11 NSDMI, keep going. */; else if (!VAR_P (value)) gcc_unreachable (); } /* Pass friend decls back. */ if ((TREE_CODE (value) == FUNCTION_DECL || TREE_CODE (value) == TEMPLATE_DECL) && DECL_CONTEXT (value) != current_class_type) return value; /* Need to set this before push_template_decl. */ if (TREE_CODE (value) == VAR_DECL) DECL_CONTEXT (value) = current_class_type; if (processing_template_decl && VAR_OR_FUNCTION_DECL_P (value)) { value = push_template_decl (value); if (error_operand_p (value)) return error_mark_node; } if (attrlist) cplus_decl_attributes (&value, attrlist, 0); if (init && DIRECT_LIST_INIT_P (init)) flags = LOOKUP_NORMAL; else flags = LOOKUP_IMPLICIT; switch (TREE_CODE (value)) { case VAR_DECL: finish_static_data_member_decl (value, init, init_const_expr_p, asmspec_tree, flags); return value; case FIELD_DECL: if (asmspec) error ("%<asm%> specifiers are not permitted on non-static data members"); if (DECL_INITIAL (value) == error_mark_node) init = error_mark_node; cp_finish_decl (value, init, /*init_const_expr_p=*/false, NULL_TREE, flags); DECL_IN_AGGR_P (value) = 1; return value; case FUNCTION_DECL: if (asmspec) set_user_assembler_name (value, asmspec); cp_finish_decl (value, /*init=*/NULL_TREE, /*init_const_expr_p=*/false, asmspec_tree, flags); /* Pass friends back this way. */ if (DECL_FRIEND_P (value)) return void_type_node; DECL_IN_AGGR_P (value) = 1; return value; default: gcc_unreachable (); } return NULL_TREE; } /* Like `grokfield', but for bitfields. WIDTH is non-NULL for bit fields only, and is an INTEGER_CST node. */ tree grokbitfield (const cp_declarator *declarator, cp_decl_specifier_seq *declspecs, tree width, tree attrlist) { tree value = grokdeclarator (declarator, declspecs, BITFIELD, 0, &attrlist); if (value == error_mark_node) return NULL_TREE; /* friends went bad. */ if (TREE_TYPE (value) == error_mark_node) return value; /* Pass friendly classes back. */ if (VOID_TYPE_P (value)) return void_type_node; if (!INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (value)) && (POINTER_TYPE_P (value) || !dependent_type_p (TREE_TYPE (value)))) { error ("bit-field %qD with non-integral type", value); return error_mark_node; } if (TREE_CODE (value) == TYPE_DECL) { error ("cannot declare %qD to be a bit-field type", value); return NULL_TREE; } /* Usually, finish_struct_1 catches bitfields with invalid types. But, in the case of bitfields with function type, we confuse ourselves into thinking they are member functions, so we must check here. */ if (TREE_CODE (value) == FUNCTION_DECL) { error ("cannot declare bit-field %qD with function type", DECL_NAME (value)); return NULL_TREE; } if (DECL_IN_AGGR_P (value)) { error ("%qD is already defined in the class %qT", value, DECL_CONTEXT (value)); return void_type_node; } if (TREE_STATIC (value)) { error ("static member %qD cannot be a bit-field", value); return NULL_TREE; } cp_finish_decl (value, NULL_TREE, false, NULL_TREE, 0); if (width != error_mark_node) { /* The width must be an integer type. */ if (!type_dependent_expression_p (width) && !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (width))) error ("width of bit-field %qD has non-integral type %qT", value, TREE_TYPE (width)); DECL_INITIAL (value) = width; SET_DECL_C_BIT_FIELD (value); } DECL_IN_AGGR_P (value) = 1; if (attrlist) cplus_decl_attributes (&value, attrlist, /*flags=*/0); return value; } /* Returns true iff ATTR is an attribute which needs to be applied at instantiation time rather than template definition time. */ static bool is_late_template_attribute (tree attr, tree decl) { tree name = get_attribute_name (attr); tree args = TREE_VALUE (attr); const struct attribute_spec *spec = lookup_attribute_spec (name); tree arg; if (!spec) /* Unknown attribute. */ return false; /* Attribute weak handling wants to write out assembly right away. */ if (is_attribute_p ("weak", name)) return true; /* Attribute unused is applied directly, as it appertains to decls. */ if (is_attribute_p ("unused", name)) return false; /* #pragma omp declare simd attribute needs to be always deferred. */ if (flag_openmp && is_attribute_p ("omp declare simd", name)) return true; /* If any of the arguments are dependent expressions, we can't evaluate the attribute until instantiation time. */ for (arg = args; arg; arg = TREE_CHAIN (arg)) { tree t = TREE_VALUE (arg); /* If the first attribute argument is an identifier, only consider second and following arguments. Attributes like mode, format, cleanup and several target specific attributes aren't late just because they have an IDENTIFIER_NODE as first argument. */ if (arg == args && identifier_p (t)) continue; if (value_dependent_expression_p (t) || type_dependent_expression_p (t)) return true; } if (TREE_CODE (decl) == TYPE_DECL || TYPE_P (decl) || spec->type_required) { tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl); /* We can't apply any attributes to a completely unknown type until instantiation time. */ enum tree_code code = TREE_CODE (type); if (code == TEMPLATE_TYPE_PARM || code == BOUND_TEMPLATE_TEMPLATE_PARM || code == TYPENAME_TYPE) return true; /* Also defer most attributes on dependent types. This is not necessary in all cases, but is the better default. */ else if (dependent_type_p (type) /* But some attributes specifically apply to templates. */ && !is_attribute_p ("abi_tag", name) && !is_attribute_p ("deprecated", name) && !is_attribute_p ("visibility", name)) return true; else return false; } else return false; } /* ATTR_P is a list of attributes. Remove any attributes which need to be applied at instantiation time and return them. If IS_DEPENDENT is true, the declaration itself is dependent, so all attributes should be applied at instantiation time. */ static tree splice_template_attributes (tree *attr_p, tree decl) { tree *p = attr_p; tree late_attrs = NULL_TREE; tree *q = &late_attrs; if (!p) return NULL_TREE; for (; *p; ) { if (is_late_template_attribute (*p, decl)) { ATTR_IS_DEPENDENT (*p) = 1; *q = *p; *p = TREE_CHAIN (*p); q = &TREE_CHAIN (*q); *q = NULL_TREE; } else p = &TREE_CHAIN (*p); } return late_attrs; } /* Remove any late attributes from the list in ATTR_P and attach them to DECL_P. */ static void save_template_attributes (tree *attr_p, tree *decl_p) { tree *q; if (attr_p && *attr_p == error_mark_node) return; tree late_attrs = splice_template_attributes (attr_p, *decl_p); if (!late_attrs) return; if (DECL_P (*decl_p)) q = &DECL_ATTRIBUTES (*decl_p); else q = &TYPE_ATTRIBUTES (*decl_p); tree old_attrs = *q; /* Merge the late attributes at the beginning with the attribute list. */ late_attrs = merge_attributes (late_attrs, *q); *q = late_attrs; if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p)) { /* We've added new attributes directly to the main variant, so now we need to update all of the other variants to include these new attributes. */ tree variant; for (variant = TYPE_NEXT_VARIANT (*decl_p); variant; variant = TYPE_NEXT_VARIANT (variant)) { gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs); TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p); } } } /* Return true iff ATTRS are acceptable attributes to be applied in-place to a typedef which gives a previously anonymous class or enum a name for linkage purposes. */ bool attributes_naming_typedef_ok (tree attrs) { for (; attrs; attrs = TREE_CHAIN (attrs)) { tree name = get_attribute_name (attrs); if (is_attribute_p ("vector_size", name)) return false; } return true; } /* Like reconstruct_complex_type, but handle also template trees. */ tree cp_reconstruct_complex_type (tree type, tree bottom) { tree inner, outer; bool late_return_type_p = false; if (TYPE_PTR_P (type)) { inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom); outer = build_pointer_type_for_mode (inner, TYPE_MODE (type), TYPE_REF_CAN_ALIAS_ALL (type)); } else if (TREE_CODE (type) == REFERENCE_TYPE) { inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom); outer = build_reference_type_for_mode (inner, TYPE_MODE (type), TYPE_REF_CAN_ALIAS_ALL (type)); } else if (TREE_CODE (type) == ARRAY_TYPE) { inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom); outer = build_cplus_array_type (inner, TYPE_DOMAIN (type)); /* Don't call cp_build_qualified_type on ARRAY_TYPEs, the element type qualification will be handled by the recursive cp_reconstruct_complex_type call and cp_build_qualified_type for ARRAY_TYPEs changes the element type. */ return outer; } else if (TREE_CODE (type) == FUNCTION_TYPE) { late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (type); inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom); outer = build_function_type (inner, TYPE_ARG_TYPES (type)); outer = apply_memfn_quals (outer, type_memfn_quals (type), type_memfn_rqual (type)); } else if (TREE_CODE (type) == METHOD_TYPE) { late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (type); inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom); /* The build_method_type_directly() routine prepends 'this' to argument list, so we must compensate by getting rid of it. */ outer = build_method_type_directly (class_of_this_parm (type), inner, TREE_CHAIN (TYPE_ARG_TYPES (type))); } else if (TREE_CODE (type) == OFFSET_TYPE) { inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom); outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner); } else return bottom; if (TYPE_ATTRIBUTES (type)) outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type)); outer = cp_build_qualified_type (outer, cp_type_quals (type)); if (late_return_type_p) TYPE_HAS_LATE_RETURN_TYPE (outer) = 1; return outer; } /* Replaces any constexpr expression that may be into the attributes arguments with their reduced value. */ static void cp_check_const_attributes (tree attributes) { if (attributes == error_mark_node) return; tree attr; for (attr = attributes; attr; attr = TREE_CHAIN (attr)) { tree arg; for (arg = TREE_VALUE (attr); arg; arg = TREE_CHAIN (arg)) { tree expr = TREE_VALUE (arg); if (EXPR_P (expr)) TREE_VALUE (arg) = maybe_constant_value (expr); } } } /* Return true if TYPE is an OpenMP mappable type. */ bool cp_omp_mappable_type (tree type) { /* Mappable type has to be complete. */ if (type == error_mark_node || !COMPLETE_TYPE_P (type)) return false; /* Arrays have mappable type if the elements have mappable type. */ while (TREE_CODE (type) == ARRAY_TYPE) type = TREE_TYPE (type); /* A mappable type cannot contain virtual members. */ if (CLASS_TYPE_P (type) && CLASSTYPE_VTABLES (type)) return false; /* All data members must be non-static. */ if (CLASS_TYPE_P (type)) { tree field; for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field)) if (TREE_CODE (field) == VAR_DECL) return false; /* All fields must have mappable types. */ else if (TREE_CODE (field) == FIELD_DECL && !cp_omp_mappable_type (TREE_TYPE (field))) return false; } return true; } /* Like decl_attributes, but handle C++ complexity. */ void cplus_decl_attributes (tree *decl, tree attributes, int flags) { if (*decl == NULL_TREE || *decl == void_type_node || *decl == error_mark_node) return; /* Add implicit "omp declare target" attribute if requested. */ if (scope_chain->omp_declare_target_attribute && ((TREE_CODE (*decl) == VAR_DECL && (TREE_STATIC (*decl) || DECL_EXTERNAL (*decl))) || TREE_CODE (*decl) == FUNCTION_DECL)) { if (TREE_CODE (*decl) == VAR_DECL && DECL_CLASS_SCOPE_P (*decl)) error ("%q+D static data member inside of declare target directive", *decl); else if (TREE_CODE (*decl) == VAR_DECL && (DECL_FUNCTION_SCOPE_P (*decl) || (current_function_decl && !DECL_EXTERNAL (*decl)))) error ("%q+D in block scope inside of declare target directive", *decl); else if (!processing_template_decl && TREE_CODE (*decl) == VAR_DECL && !cp_omp_mappable_type (TREE_TYPE (*decl))) error ("%q+D in declare target directive does not have mappable type", *decl); else attributes = tree_cons (get_identifier ("omp declare target"), NULL_TREE, attributes); } if (processing_template_decl) { if (check_for_bare_parameter_packs (attributes)) return; save_template_attributes (&attributes, decl); } cp_check_const_attributes (attributes); if (TREE_CODE (*decl) == TEMPLATE_DECL) decl = &DECL_TEMPLATE_RESULT (*decl); if (TREE_TYPE (*decl) && TYPE_PTRMEMFUNC_P (TREE_TYPE (*decl))) { attributes = decl_attributes (decl, attributes, flags | ATTR_FLAG_FUNCTION_NEXT); decl_attributes (&TYPE_PTRMEMFUNC_FN_TYPE_RAW (TREE_TYPE (*decl)), attributes, flags); } else decl_attributes (decl, attributes, flags); if (TREE_CODE (*decl) == TYPE_DECL) SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl)); /* Propagate deprecation out to the template. */ if (TREE_DEPRECATED (*decl)) if (tree ti = get_template_info (*decl)) { tree tmpl = TI_TEMPLATE (ti); tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl) : DECL_TEMPLATE_RESULT (tmpl)); if (*decl == pattern) TREE_DEPRECATED (tmpl) = true; } } /* Walks through the namespace- or function-scope anonymous union OBJECT, with the indicated TYPE, building appropriate VAR_DECLs. Returns one of the fields for use in the mangled name. */ static tree build_anon_union_vars (tree type, tree object) { tree main_decl = NULL_TREE; tree field; /* Rather than write the code to handle the non-union case, just give an error. */ if (TREE_CODE (type) != UNION_TYPE) { error ("anonymous struct not inside named type"); return error_mark_node; } for (field = TYPE_FIELDS (type); field != NULL_TREE; field = DECL_CHAIN (field)) { tree decl; tree ref; if (DECL_ARTIFICIAL (field)) continue; if (TREE_CODE (field) != FIELD_DECL) { permerror (input_location, "%q+#D invalid; an anonymous union can only " "have non-static data members", field); continue; } if (TREE_PRIVATE (field)) permerror (input_location, "private member %q+#D in anonymous union", field); else if (TREE_PROTECTED (field)) permerror (input_location, "protected member %q+#D in anonymous union", field); if (processing_template_decl) ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object, DECL_NAME (field), NULL_TREE); else ref = build_class_member_access_expr (object, field, NULL_TREE, false, tf_warning_or_error); if (DECL_NAME (field)) { tree base; decl = build_decl (input_location, VAR_DECL, DECL_NAME (field), TREE_TYPE (field)); DECL_ANON_UNION_VAR_P (decl) = 1; DECL_ARTIFICIAL (decl) = 1; base = get_base_address (object); TREE_PUBLIC (decl) = TREE_PUBLIC (base); TREE_STATIC (decl) = TREE_STATIC (base); DECL_EXTERNAL (decl) = DECL_EXTERNAL (base); SET_DECL_VALUE_EXPR (decl, ref); DECL_HAS_VALUE_EXPR_P (decl) = 1; decl = pushdecl (decl); } else if (ANON_AGGR_TYPE_P (TREE_TYPE (field))) decl = build_anon_union_vars (TREE_TYPE (field), ref); else decl = 0; if (main_decl == NULL_TREE) main_decl = decl; } return main_decl; } /* Finish off the processing of a UNION_TYPE structure. If the union is an anonymous union, then all members must be laid out together. PUBLIC_P is nonzero if this union is not declared static. */ void finish_anon_union (tree anon_union_decl) { tree type; tree main_decl; bool public_p; if (anon_union_decl == error_mark_node) return; type = TREE_TYPE (anon_union_decl); public_p = TREE_PUBLIC (anon_union_decl); /* The VAR_DECL's context is the same as the TYPE's context. */ DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type)); if (TYPE_FIELDS (type) == NULL_TREE) return; if (public_p) { error ("namespace-scope anonymous aggregates must be static"); return; } main_decl = build_anon_union_vars (type, anon_union_decl); if (main_decl == error_mark_node) return; if (main_decl == NULL_TREE) { warning (0, "anonymous union with no members"); return; } if (!processing_template_decl) { /* Use main_decl to set the mangled name. */ DECL_NAME (anon_union_decl) = DECL_NAME (main_decl); maybe_commonize_var (anon_union_decl); if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl)) mangle_decl (anon_union_decl); DECL_NAME (anon_union_decl) = NULL_TREE; } pushdecl (anon_union_decl); cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0); } /* Auxiliary functions to make type signatures for `operator new' and `operator delete' correspond to what compiler will be expecting. */ tree coerce_new_type (tree type) { int e = 0; tree args = TYPE_ARG_TYPES (type); gcc_assert (TREE_CODE (type) == FUNCTION_TYPE); if (!same_type_p (TREE_TYPE (type), ptr_type_node)) { e = 1; error ("%<operator new%> must return type %qT", ptr_type_node); } if (args && args != void_list_node) { if (TREE_PURPOSE (args)) { /* [basic.stc.dynamic.allocation] The first parameter shall not have an associated default argument. */ error ("the first parameter of %<operator new%> cannot " "have a default argument"); /* Throw away the default argument. */ TREE_PURPOSE (args) = NULL_TREE; } if (!same_type_p (TREE_VALUE (args), size_type_node)) { e = 2; args = TREE_CHAIN (args); } } else e = 2; if (e == 2) permerror (input_location, "%<operator new%> takes type %<size_t%> (%qT) " "as first parameter", size_type_node); switch (e) { case 2: args = tree_cons (NULL_TREE, size_type_node, args); /* Fall through. */ case 1: type = build_exception_variant (build_function_type (ptr_type_node, args), TYPE_RAISES_EXCEPTIONS (type)); /* Fall through. */ default:; } return type; } tree coerce_delete_type (tree type) { int e = 0; tree args = TYPE_ARG_TYPES (type); gcc_assert (TREE_CODE (type) == FUNCTION_TYPE); if (!same_type_p (TREE_TYPE (type), void_type_node)) { e = 1; error ("%<operator delete%> must return type %qT", void_type_node); } if (!args || args == void_list_node || !same_type_p (TREE_VALUE (args), ptr_type_node)) { e = 2; if (args && args != void_list_node) args = TREE_CHAIN (args); error ("%<operator delete%> takes type %qT as first parameter", ptr_type_node); } switch (e) { case 2: args = tree_cons (NULL_TREE, ptr_type_node, args); /* Fall through. */ case 1: type = build_exception_variant (build_function_type (void_type_node, args), TYPE_RAISES_EXCEPTIONS (type)); /* Fall through. */ default:; } return type; } /* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable and mark them as needed. */ static void mark_vtable_entries (tree decl) { tree fnaddr; unsigned HOST_WIDE_INT idx; FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)), idx, fnaddr) { tree fn; STRIP_NOPS (fnaddr); if (TREE_CODE (fnaddr) != ADDR_EXPR && TREE_CODE (fnaddr) != FDESC_EXPR) /* This entry is an offset: a virtual base class offset, a virtual call offset, an RTTI offset, etc. */ continue; fn = TREE_OPERAND (fnaddr, 0); TREE_ADDRESSABLE (fn) = 1; /* When we don't have vcall offsets, we output thunks whenever we output the vtables that contain them. With vcall offsets, we know all the thunks we'll need when we emit a virtual function, so we emit the thunks there instead. */ if (DECL_THUNK_P (fn)) use_thunk (fn, /*emit_p=*/0); mark_used (fn); } } /* Set DECL up to have the closest approximation of "initialized common" linkage available. */ void comdat_linkage (tree decl) { if (flag_weak) make_decl_one_only (decl, cxx_comdat_group (decl)); else if (TREE_CODE (decl) == FUNCTION_DECL || (VAR_P (decl) && DECL_ARTIFICIAL (decl))) /* We can just emit function and compiler-generated variables statically; having multiple copies is (for the most part) only a waste of space. There are two correctness issues, however: the address of a template instantiation with external linkage should be the same, independent of what translation unit asks for the address, and this will not hold when we emit multiple copies of the function. However, there's little else we can do. Also, by default, the typeinfo implementation assumes that there will be only one copy of the string used as the name for each type. Therefore, if weak symbols are unavailable, the run-time library should perform a more conservative check; it should perform a string comparison, rather than an address comparison. */ TREE_PUBLIC (decl) = 0; else { /* Static data member template instantiations, however, cannot have multiple copies. */ if (DECL_INITIAL (decl) == 0 || DECL_INITIAL (decl) == error_mark_node) DECL_COMMON (decl) = 1; else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl))) { DECL_COMMON (decl) = 1; DECL_INITIAL (decl) = error_mark_node; } else if (!DECL_EXPLICIT_INSTANTIATION (decl)) { /* We can't do anything useful; leave vars for explicit instantiation. */ DECL_EXTERNAL (decl) = 1; DECL_NOT_REALLY_EXTERN (decl) = 0; } } DECL_COMDAT (decl) = 1; } /* For win32 we also want to put explicit instantiations in linkonce sections, so that they will be merged with implicit instantiations; otherwise we get duplicate symbol errors. For Darwin we do not want explicit instantiations to be linkonce. */ void maybe_make_one_only (tree decl) { /* We used to say that this was not necessary on targets that support weak symbols, because the implicit instantiations will defer to the explicit one. However, that's not actually the case in SVR4; a strong definition after a weak one is an error. Also, not making explicit instantiations one_only means that we can end up with two copies of some template instantiations. */ if (! flag_weak) return; /* We can't set DECL_COMDAT on functions, or cp_finish_file will think we can get away with not emitting them if they aren't used. We need to for variables so that cp_finish_decl will update their linkage, because their DECL_INITIAL may not have been set properly yet. */ if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC || (! DECL_EXPLICIT_INSTANTIATION (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl))) { make_decl_one_only (decl, cxx_comdat_group (decl)); if (VAR_P (decl)) { varpool_node *node = varpool_node::get_create (decl); DECL_COMDAT (decl) = 1; /* Mark it needed so we don't forget to emit it. */ node->forced_by_abi = true; TREE_USED (decl) = 1; } } } /* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage. This predicate will give the right answer during parsing of the function, which other tests may not. */ bool vague_linkage_p (tree decl) { /* Unfortunately, import_export_decl has not always been called before the function is processed, so we cannot simply check DECL_COMDAT. */ if (DECL_COMDAT (decl) || (((TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl)) || (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INSTANTIATION (decl))) && TREE_PUBLIC (decl))) return true; else if (DECL_FUNCTION_SCOPE_P (decl)) /* A local static in an inline effectively has vague linkage. */ return (TREE_STATIC (decl) && vague_linkage_p (DECL_CONTEXT (decl))); else return false; } /* Determine whether or not we want to specifically import or export CTYPE, using various heuristics. */ static void import_export_class (tree ctype) { /* -1 for imported, 1 for exported. */ int import_export = 0; /* It only makes sense to call this function at EOF. The reason is that this function looks at whether or not the first non-inline non-abstract virtual member function has been defined in this translation unit. But, we can't possibly know that until we've seen the entire translation unit. */ gcc_assert (at_eof); if (CLASSTYPE_INTERFACE_KNOWN (ctype)) return; /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface, we will have CLASSTYPE_INTERFACE_ONLY set but not CLASSTYPE_INTERFACE_KNOWN. In that case, we don't want to use this heuristic because someone will supply a #pragma implementation elsewhere, and deducing it here would produce a conflict. */ if (CLASSTYPE_INTERFACE_ONLY (ctype)) return; if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype))) import_export = -1; else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype))) import_export = 1; else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype) && !flag_implicit_templates) /* For a template class, without -fimplicit-templates, check the repository. If the virtual table is assigned to this translation unit, then export the class; otherwise, import it. */ import_export = repo_export_class_p (ctype) ? 1 : -1; else if (TYPE_POLYMORPHIC_P (ctype)) { /* The ABI specifies that the virtual table and associated information are emitted with the key method, if any. */ tree method = CLASSTYPE_KEY_METHOD (ctype); /* If weak symbol support is not available, then we must be careful not to emit the vtable when the key function is inline. An inline function can be defined in multiple translation units. If we were to emit the vtable in each translation unit containing a definition, we would get multiple definition errors at link-time. */ if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method))) import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1); } /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing a definition anywhere else. */ if (MULTIPLE_SYMBOL_SPACES && import_export == -1) import_export = 0; /* Allow back ends the chance to overrule the decision. */ if (targetm.cxx.import_export_class) import_export = targetm.cxx.import_export_class (ctype, import_export); if (import_export) { SET_CLASSTYPE_INTERFACE_KNOWN (ctype); CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0); } } /* Return true if VAR has already been provided to the back end; in that case VAR should not be modified further by the front end. */ static bool var_finalized_p (tree var) { return varpool_node::get_create (var)->definition; } /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason, must be emitted in this translation unit. Mark it as such. */ void mark_needed (tree decl) { TREE_USED (decl) = 1; if (TREE_CODE (decl) == FUNCTION_DECL) { /* Extern inline functions don't become needed when referenced. If we know a method will be emitted in other TU and no new functions can be marked reachable, just use the external definition. */ struct cgraph_node *node = cgraph_node::get_create (decl); node->forced_by_abi = true; /* #pragma interface and -frepo code can call mark_needed for maybe-in-charge 'tors; mark the clones as well. */ tree clone; FOR_EACH_CLONE (clone, decl) mark_needed (clone); } else if (TREE_CODE (decl) == VAR_DECL) { varpool_node *node = varpool_node::get_create (decl); /* C++ frontend use mark_decl_references to force COMDAT variables to be output that might appear dead otherwise. */ node->forced_by_abi = true; } } /* DECL is either a FUNCTION_DECL or a VAR_DECL. This function returns true if a definition of this entity should be provided in this object file. Callers use this function to determine whether or not to let the back end know that a definition of DECL is available in this translation unit. */ bool decl_needed_p (tree decl) { gcc_assert (VAR_OR_FUNCTION_DECL_P (decl)); /* This function should only be called at the end of the translation unit. We cannot be sure of whether or not something will be COMDAT until that point. */ gcc_assert (at_eof); /* All entities with external linkage that are not COMDAT/EXTERN should be emitted; they may be referred to from other object files. */ if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_REALLY_EXTERN (decl)) return true; /* Functions marked "dllexport" must be emitted so that they are visible to other DLLs. */ if (flag_keep_inline_dllexport && lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl))) return true; /* When not optimizing, do not bother to produce definitions for extern symbols. */ if (DECL_REALLY_EXTERN (decl) && ((TREE_CODE (decl) != FUNCTION_DECL && !optimize) || (TREE_CODE (decl) == FUNCTION_DECL && !opt_for_fn (decl, optimize))) && !lookup_attribute ("always_inline", decl)) return false; /* If this entity was used, let the back end see it; it will decide whether or not to emit it into the object file. */ if (TREE_USED (decl)) return true; /* Virtual functions might be needed for devirtualization. */ if (flag_devirtualize && TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl)) return true; /* Otherwise, DECL does not need to be emitted -- yet. A subsequent reference to DECL might cause it to be emitted later. */ return false; } /* If necessary, write out the vtables for the dynamic class CTYPE. Returns true if any vtables were emitted. */ static bool maybe_emit_vtables (tree ctype) { tree vtbl; tree primary_vtbl; int needed = 0; varpool_node *current = NULL, *last = NULL; /* If the vtables for this class have already been emitted there is nothing more to do. */ primary_vtbl = CLASSTYPE_VTABLES (ctype); if (var_finalized_p (primary_vtbl)) return false; /* Ignore dummy vtables made by get_vtable_decl. */ if (TREE_TYPE (primary_vtbl) == void_type_node) return false; /* On some targets, we cannot determine the key method until the end of the translation unit -- which is when this function is called. */ if (!targetm.cxx.key_method_may_be_inline ()) determine_key_method (ctype); /* See if any of the vtables are needed. */ for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl)) { import_export_decl (vtbl); if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl)) needed = 1; } if (!needed) { /* If the references to this class' vtables are optimized away, still emit the appropriate debugging information. See dfs_debug_mark. */ if (DECL_COMDAT (primary_vtbl) && CLASSTYPE_DEBUG_REQUESTED (ctype)) note_debug_info_needed (ctype); return false; } /* The ABI requires that we emit all of the vtables if we emit any of them. */ for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl)) { /* Mark entities references from the virtual table as used. */ mark_vtable_entries (vtbl); if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0) { vec<tree, va_gc> *cleanups = NULL; tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups, LOOKUP_NORMAL); /* It had better be all done at compile-time. */ gcc_assert (!expr && !cleanups); } /* Write it out. */ DECL_EXTERNAL (vtbl) = 0; rest_of_decl_compilation (vtbl, 1, 1); /* Because we're only doing syntax-checking, we'll never end up actually marking the variable as written. */ if (flag_syntax_only) TREE_ASM_WRITTEN (vtbl) = 1; else if (DECL_ONE_ONLY (vtbl)) { current = varpool_node::get_create (vtbl); if (last) current->add_to_same_comdat_group (last); last = current; } } /* Since we're writing out the vtable here, also write the debug info. */ note_debug_info_needed (ctype); return true; } /* A special return value from type_visibility meaning internal linkage. */ enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 }; /* walk_tree helper function for type_visibility. */ static tree min_vis_r (tree *tp, int *walk_subtrees, void *data) { int *vis_p = (int *)data; if (! TYPE_P (*tp)) { *walk_subtrees = 0; } else if (OVERLOAD_TYPE_P (*tp) && !TREE_PUBLIC (TYPE_MAIN_DECL (*tp))) { *vis_p = VISIBILITY_ANON; return *tp; } else if (CLASS_TYPE_P (*tp) && CLASSTYPE_VISIBILITY (*tp) > *vis_p) *vis_p = CLASSTYPE_VISIBILITY (*tp); return NULL; } /* Returns the visibility of TYPE, which is the minimum visibility of its component types. */ static int type_visibility (tree type) { int vis = VISIBILITY_DEFAULT; cp_walk_tree_without_duplicates (&type, min_vis_r, &vis); return vis; } /* Limit the visibility of DECL to VISIBILITY, if not explicitly specified (or if VISIBILITY is static). If TMPL is true, this constraint is for a template argument, and takes precedence over explicitly-specified visibility on the template. */ static void constrain_visibility (tree decl, int visibility, bool tmpl) { if (visibility == VISIBILITY_ANON) { /* extern "C" declarations aren't affected by the anonymous namespace. */ if (!DECL_EXTERN_C_P (decl)) { TREE_PUBLIC (decl) = 0; DECL_WEAK (decl) = 0; DECL_COMMON (decl) = 0; DECL_COMDAT (decl) = false; if (TREE_CODE (decl) == FUNCTION_DECL || TREE_CODE (decl) == VAR_DECL) { struct symtab_node *snode = symtab_node::get (decl); if (snode) snode->set_comdat_group (NULL); } DECL_INTERFACE_KNOWN (decl) = 1; if (DECL_LANG_SPECIFIC (decl)) DECL_NOT_REALLY_EXTERN (decl) = 1; } } else if (visibility > DECL_VISIBILITY (decl) && (tmpl || !DECL_VISIBILITY_SPECIFIED (decl))) { DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility; /* This visibility was not specified. */ DECL_VISIBILITY_SPECIFIED (decl) = false; } } /* Constrain the visibility of DECL based on the visibility of its template arguments. */ static void constrain_visibility_for_template (tree decl, tree targs) { /* If this is a template instantiation, check the innermost template args for visibility constraints. The outer template args are covered by the class check. */ tree args = INNERMOST_TEMPLATE_ARGS (targs); int i; for (i = TREE_VEC_LENGTH (args); i > 0; --i) { int vis = 0; tree arg = TREE_VEC_ELT (args, i-1); if (TYPE_P (arg)) vis = type_visibility (arg); else { if (REFERENCE_REF_P (arg)) arg = TREE_OPERAND (arg, 0); if (TREE_TYPE (arg)) STRIP_NOPS (arg); if (TREE_CODE (arg) == ADDR_EXPR) arg = TREE_OPERAND (arg, 0); if (VAR_OR_FUNCTION_DECL_P (arg)) { if (! TREE_PUBLIC (arg)) vis = VISIBILITY_ANON; else vis = DECL_VISIBILITY (arg); } } if (vis) constrain_visibility (decl, vis, true); } } /* Like c_determine_visibility, but with additional C++-specific behavior. Function-scope entities can rely on the function's visibility because it is set in start_preparsed_function. Class-scope entities cannot rely on the class's visibility until the end of the enclosing class definition. Note that because namespaces have multiple independent definitions, namespace visibility is handled elsewhere using the #pragma visibility machinery rather than by decorating the namespace declaration. The goal is for constraints from the type to give a diagnostic, and other constraints to be applied silently. */ void determine_visibility (tree decl) { tree class_type = NULL_TREE; bool use_template; bool orig_visibility_specified; enum symbol_visibility orig_visibility; /* Remember that all decls get VISIBILITY_DEFAULT when built. */ /* Only relevant for names with external linkage. */ if (!TREE_PUBLIC (decl)) return; /* Cloned constructors and destructors get the same visibility as the underlying function. That should be set up in maybe_clone_body. */ gcc_assert (!DECL_CLONED_FUNCTION_P (decl)); orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl); orig_visibility = DECL_VISIBILITY (decl); if (TREE_CODE (decl) == TYPE_DECL) { if (CLASS_TYPE_P (TREE_TYPE (decl))) use_template = CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)); else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl))) use_template = 1; else use_template = 0; } else if (DECL_LANG_SPECIFIC (decl)) use_template = DECL_USE_TEMPLATE (decl); else use_template = 0; /* If DECL is a member of a class, visibility specifiers on the class can influence the visibility of the DECL. */ if (DECL_CLASS_SCOPE_P (decl)) class_type = DECL_CONTEXT (decl); else { /* Not a class member. */ /* Virtual tables have DECL_CONTEXT set to their associated class, so they are automatically handled above. */ gcc_assert (!VAR_P (decl) || !DECL_VTABLE_OR_VTT_P (decl)); if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl)) { /* Local statics and classes get the visibility of their containing function by default, except that -fvisibility-inlines-hidden doesn't affect them. */ tree fn = DECL_CONTEXT (decl); if (DECL_VISIBILITY_SPECIFIED (fn)) { DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn); DECL_VISIBILITY_SPECIFIED (decl) = DECL_VISIBILITY_SPECIFIED (fn); } else { if (DECL_CLASS_SCOPE_P (fn)) determine_visibility_from_class (decl, DECL_CONTEXT (fn)); else if (determine_hidden_inline (fn)) { DECL_VISIBILITY (decl) = default_visibility; DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma; } else { DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn); DECL_VISIBILITY_SPECIFIED (decl) = DECL_VISIBILITY_SPECIFIED (fn); } } /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set, but have no TEMPLATE_INFO, so don't try to check it. */ use_template = 0; } else if (VAR_P (decl) && DECL_TINFO_P (decl) && flag_visibility_ms_compat) { /* Under -fvisibility-ms-compat, types are visible by default, even though their contents aren't. */ tree underlying_type = TREE_TYPE (DECL_NAME (decl)); int underlying_vis = type_visibility (underlying_type); if (underlying_vis == VISIBILITY_ANON || (CLASS_TYPE_P (underlying_type) && CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type))) constrain_visibility (decl, underlying_vis, false); else DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT; } else if (VAR_P (decl) && DECL_TINFO_P (decl)) { /* tinfo visibility is based on the type it's for. */ constrain_visibility (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false); /* Give the target a chance to override the visibility associated with DECL. */ if (TREE_PUBLIC (decl) && !DECL_REALLY_EXTERN (decl) && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl))) && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl)))) targetm.cxx.determine_class_data_visibility (decl); } else if (use_template) /* Template instantiations and specializations get visibility based on their template unless they override it with an attribute. */; else if (! DECL_VISIBILITY_SPECIFIED (decl)) { if (determine_hidden_inline (decl)) DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN; else { /* Set default visibility to whatever the user supplied with #pragma GCC visibility or a namespace visibility attribute. */ DECL_VISIBILITY (decl) = default_visibility; DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma; } } } if (use_template) { /* If the specialization doesn't specify visibility, use the visibility from the template. */ tree tinfo = (TREE_CODE (decl) == TYPE_DECL ? TYPE_TEMPLATE_INFO (TREE_TYPE (decl)) : DECL_TEMPLATE_INFO (decl)); tree args = TI_ARGS (tinfo); tree attribs = (TREE_CODE (decl) == TYPE_DECL ? TYPE_ATTRIBUTES (TREE_TYPE (decl)) : DECL_ATTRIBUTES (decl)); if (args != error_mark_node) { tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo)); if (!DECL_VISIBILITY_SPECIFIED (decl)) { if (!DECL_VISIBILITY_SPECIFIED (pattern) && determine_hidden_inline (decl)) DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN; else { DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern); DECL_VISIBILITY_SPECIFIED (decl) = DECL_VISIBILITY_SPECIFIED (pattern); } } if (args /* Template argument visibility outweighs #pragma or namespace visibility, but not an explicit attribute. */ && !lookup_attribute ("visibility", attribs)) { int depth = TMPL_ARGS_DEPTH (args); if (DECL_VISIBILITY_SPECIFIED (decl)) { /* A class template member with explicit visibility overrides the class visibility, so we need to apply all the levels of template args directly. */ int i; for (i = 1; i <= depth; ++i) { tree lev = TMPL_ARGS_LEVEL (args, i); constrain_visibility_for_template (decl, lev); } } else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))) /* Limit visibility based on its template arguments. */ constrain_visibility_for_template (decl, args); } } } if (class_type) determine_visibility_from_class (decl, class_type); if (decl_anon_ns_mem_p (decl)) /* Names in an anonymous namespace get internal linkage. This might change once we implement export. */ constrain_visibility (decl, VISIBILITY_ANON, false); else if (TREE_CODE (decl) != TYPE_DECL) { /* Propagate anonymity from type to decl. */ int tvis = type_visibility (TREE_TYPE (decl)); if (tvis == VISIBILITY_ANON || ! DECL_VISIBILITY_SPECIFIED (decl)) constrain_visibility (decl, tvis, false); } else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true)) /* DR 757: A type without linkage shall not be used as the type of a variable or function with linkage, unless o the variable or function has extern "C" linkage (7.5 [dcl.link]), or o the variable or function is not used (3.2 [basic.def.odr]) or is defined in the same translation unit. Since non-extern "C" decls need to be defined in the same translation unit, we can make the type internal. */ constrain_visibility (decl, VISIBILITY_ANON, false); /* If visibility changed and DECL already has DECL_RTL, ensure symbol flags are updated. */ if ((DECL_VISIBILITY (decl) != orig_visibility || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified) && ((VAR_P (decl) && TREE_STATIC (decl)) || TREE_CODE (decl) == FUNCTION_DECL) && DECL_RTL_SET_P (decl)) make_decl_rtl (decl); } /* By default, static data members and function members receive the visibility of their containing class. */ static void determine_visibility_from_class (tree decl, tree class_type) { if (DECL_VISIBILITY_SPECIFIED (decl)) return; if (determine_hidden_inline (decl)) DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN; else { /* Default to the class visibility. */ DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type); DECL_VISIBILITY_SPECIFIED (decl) = CLASSTYPE_VISIBILITY_SPECIFIED (class_type); } /* Give the target a chance to override the visibility associated with DECL. */ if (VAR_P (decl) && (DECL_TINFO_P (decl) || (DECL_VTABLE_OR_VTT_P (decl) /* Construction virtual tables are not exported because they cannot be referred to from other object files; their name is not standardized by the ABI. */ && !DECL_CONSTRUCTION_VTABLE_P (decl))) && TREE_PUBLIC (decl) && !DECL_REALLY_EXTERN (decl) && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type)) targetm.cxx.determine_class_data_visibility (decl); } /* Returns true iff DECL is an inline that should get hidden visibility because of -fvisibility-inlines-hidden. */ static bool determine_hidden_inline (tree decl) { return (visibility_options.inlines_hidden /* Don't do this for inline templates; specializations might not be inline, and we don't want them to inherit the hidden visibility. We'll set it here for all inline instantiations. */ && !processing_template_decl && TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl) && (! DECL_LANG_SPECIFIC (decl) || ! DECL_EXPLICIT_INSTANTIATION (decl))); } /* Constrain the visibility of a class TYPE based on the visibility of its field types. Warn if any fields require lesser visibility. */ void constrain_class_visibility (tree type) { tree binfo; tree t; int i; int vis = type_visibility (type); if (vis == VISIBILITY_ANON || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type))) return; /* Don't warn about visibility if the class has explicit visibility. */ if (CLASSTYPE_VISIBILITY_SPECIFIED (type)) vis = VISIBILITY_INTERNAL; for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t)) if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node) { tree ftype = strip_pointer_or_array_types (TREE_TYPE (t)); int subvis = type_visibility (ftype); if (subvis == VISIBILITY_ANON) { if (!in_main_input_context ()) warning (0, "\ %qT has a field %qD whose type uses the anonymous namespace", type, t); } else if (MAYBE_CLASS_TYPE_P (ftype) && vis < VISIBILITY_HIDDEN && subvis >= VISIBILITY_HIDDEN) warning (OPT_Wattributes, "\ %qT declared with greater visibility than the type of its field %qD", type, t); } binfo = TYPE_BINFO (type); for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i) { int subvis = type_visibility (TREE_TYPE (t)); if (subvis == VISIBILITY_ANON) { if (!in_main_input_context()) warning (0, "\ %qT has a base %qT whose type uses the anonymous namespace", type, TREE_TYPE (t)); } else if (vis < VISIBILITY_HIDDEN && subvis >= VISIBILITY_HIDDEN) warning (OPT_Wattributes, "\ %qT declared with greater visibility than its base %qT", type, TREE_TYPE (t)); } } /* Functions for adjusting the visibility of a tagged type and its nested types and declarations when it gets a name for linkage purposes from a typedef. */ static void bt_reset_linkage_1 (binding_entry, void *); static void bt_reset_linkage_2 (binding_entry, void *); /* First reset the visibility of all the types. */ static void reset_type_linkage_1 (tree type) { set_linkage_according_to_type (type, TYPE_MAIN_DECL (type)); if (CLASS_TYPE_P (type)) binding_table_foreach (CLASSTYPE_NESTED_UTDS (type), bt_reset_linkage_1, NULL); } static void bt_reset_linkage_1 (binding_entry b, void */*data*/) { reset_type_linkage_1 (b->type); } /* Then reset the visibility of any static data members or member functions that use those types. */ static void reset_decl_linkage (tree decl) { if (TREE_PUBLIC (decl)) return; if (DECL_CLONED_FUNCTION_P (decl)) return; TREE_PUBLIC (decl) = true; DECL_INTERFACE_KNOWN (decl) = false; determine_visibility (decl); tentative_decl_linkage (decl); } static void reset_type_linkage_2 (tree type) { if (CLASS_TYPE_P (type)) { if (tree vt = CLASSTYPE_VTABLES (type)) { tree name = mangle_vtbl_for_type (type); DECL_NAME (vt) = name; SET_DECL_ASSEMBLER_NAME (vt, name); reset_decl_linkage (vt); } if (tree ti = CLASSTYPE_TYPEINFO_VAR (type)) { tree name = mangle_typeinfo_for_type (type); DECL_NAME (ti) = name; SET_DECL_ASSEMBLER_NAME (ti, name); TREE_TYPE (name) = type; reset_decl_linkage (ti); } for (tree m = TYPE_FIELDS (type); m; m = DECL_CHAIN (m)) if (TREE_CODE (m) == VAR_DECL) reset_decl_linkage (m); for (tree m = TYPE_METHODS (type); m; m = DECL_CHAIN (m)) reset_decl_linkage (m); binding_table_foreach (CLASSTYPE_NESTED_UTDS (type), bt_reset_linkage_2, NULL); } } static void bt_reset_linkage_2 (binding_entry b, void */*data*/) { reset_type_linkage_2 (b->type); } void reset_type_linkage (tree type) { reset_type_linkage_1 (type); reset_type_linkage_2 (type); } /* Set up our initial idea of what the linkage of DECL should be. */ void tentative_decl_linkage (tree decl) { if (DECL_INTERFACE_KNOWN (decl)) /* We've already made a decision as to how this function will be handled. */; else if (vague_linkage_p (decl)) { if (TREE_CODE (decl) == FUNCTION_DECL && decl_defined_p (decl)) { DECL_EXTERNAL (decl) = 1; DECL_NOT_REALLY_EXTERN (decl) = 1; note_vague_linkage_fn (decl); /* A non-template inline function with external linkage will always be COMDAT. As we must eventually determine the linkage of all functions, and as that causes writes to the data mapped in from the PCH file, it's advantageous to mark the functions at this point. */ if (DECL_DECLARED_INLINE_P (decl) && (!DECL_IMPLICIT_INSTANTIATION (decl) || DECL_DEFAULTED_FN (decl))) { /* This function must have external linkage, as otherwise DECL_INTERFACE_KNOWN would have been set. */ gcc_assert (TREE_PUBLIC (decl)); comdat_linkage (decl); DECL_INTERFACE_KNOWN (decl) = 1; } } else if (TREE_CODE (decl) == VAR_DECL) maybe_commonize_var (decl); } } /* DECL is a FUNCTION_DECL or VAR_DECL. If the object file linkage for DECL has not already been determined, do so now by setting DECL_EXTERNAL, DECL_COMDAT and other related flags. Until this function is called entities with vague linkage whose definitions are available must have TREE_PUBLIC set. If this function decides to place DECL in COMDAT, it will set appropriate flags -- but will not clear DECL_EXTERNAL. It is up to the caller to decide whether or not to clear DECL_EXTERNAL. Some callers defer that decision until it is clear that DECL is actually required. */ void import_export_decl (tree decl) { int emit_p; bool comdat_p; bool import_p; tree class_type = NULL_TREE; if (DECL_INTERFACE_KNOWN (decl)) return; /* We cannot determine what linkage to give to an entity with vague linkage until the end of the file. For example, a virtual table for a class will be defined if and only if the key method is defined in this translation unit. As a further example, consider that when compiling a translation unit that uses PCH file with "-frepo" it would be incorrect to make decisions about what entities to emit when building the PCH; those decisions must be delayed until the repository information has been processed. */ gcc_assert (at_eof); /* Object file linkage for explicit instantiations is handled in mark_decl_instantiated. For static variables in functions with vague linkage, maybe_commonize_var is used. Therefore, the only declarations that should be provided to this function are those with external linkage that are: * implicit instantiations of function templates * inline function * implicit instantiations of static data members of class templates * virtual tables * typeinfo objects Furthermore, all entities that reach this point must have a definition available in this translation unit. The following assertions check these conditions. */ gcc_assert (VAR_OR_FUNCTION_DECL_P (decl)); /* Any code that creates entities with TREE_PUBLIC cleared should also set DECL_INTERFACE_KNOWN. */ gcc_assert (TREE_PUBLIC (decl)); if (TREE_CODE (decl) == FUNCTION_DECL) gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl) || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl) || DECL_DECLARED_INLINE_P (decl)); else gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl) || DECL_VTABLE_OR_VTT_P (decl) || DECL_TINFO_P (decl)); /* Check that a definition of DECL is available in this translation unit. */ gcc_assert (!DECL_REALLY_EXTERN (decl)); /* Assume that DECL will not have COMDAT linkage. */ comdat_p = false; /* Assume that DECL will not be imported into this translation unit. */ import_p = false; /* See if the repository tells us whether or not to emit DECL in this translation unit. */ emit_p = repo_emit_p (decl); if (emit_p == 0) import_p = true; else if (emit_p == 1) { /* The repository indicates that this entity should be defined here. Make sure the back end honors that request. */ mark_needed (decl); /* Output the definition as an ordinary strong definition. */ DECL_EXTERNAL (decl) = 0; DECL_INTERFACE_KNOWN (decl) = 1; return; } if (import_p) /* We have already decided what to do with this DECL; there is no need to check anything further. */ ; else if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl)) { class_type = DECL_CONTEXT (decl); import_export_class (class_type); if (TYPE_FOR_JAVA (class_type)) import_p = true; else if (CLASSTYPE_INTERFACE_KNOWN (class_type) && CLASSTYPE_INTERFACE_ONLY (class_type)) import_p = true; else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC) && !CLASSTYPE_USE_TEMPLATE (class_type) && CLASSTYPE_KEY_METHOD (class_type) && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))) /* The ABI requires that all virtual tables be emitted with COMDAT linkage. However, on systems where COMDAT symbols don't show up in the table of contents for a static archive, or on systems without weak symbols (where we approximate COMDAT linkage by using internal linkage), the linker will report errors about undefined symbols because it will not see the virtual table definition. Therefore, in the case that we know that the virtual table will be emitted in only one translation unit, we make the virtual table an ordinary definition with external linkage. */ DECL_EXTERNAL (decl) = 0; else if (CLASSTYPE_INTERFACE_KNOWN (class_type)) { /* CLASS_TYPE is being exported from this translation unit, so DECL should be defined here. */ if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type)) /* If a class is declared in a header with the "extern template" extension, then it will not be instantiated, even in translation units that would normally require it. Often such classes are explicitly instantiated in one translation unit. Therefore, the explicit instantiation must be made visible to other translation units. */ DECL_EXTERNAL (decl) = 0; else { /* The generic C++ ABI says that class data is always COMDAT, even if there is a key function. Some variants (e.g., the ARM EABI) says that class data only has COMDAT linkage if the class data might be emitted in more than one translation unit. When the key method can be inline and is inline, we still have to arrange for comdat even though class_data_always_comdat is false. */ if (!CLASSTYPE_KEY_METHOD (class_type) || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)) || targetm.cxx.class_data_always_comdat ()) { /* The ABI requires COMDAT linkage. Normally, we only emit COMDAT things when they are needed; make sure that we realize that this entity is indeed needed. */ comdat_p = true; mark_needed (decl); } } } else if (!flag_implicit_templates && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type)) import_p = true; else comdat_p = true; } else if (VAR_P (decl) && DECL_TINFO_P (decl)) { tree type = TREE_TYPE (DECL_NAME (decl)); if (CLASS_TYPE_P (type)) { class_type = type; import_export_class (type); if (CLASSTYPE_INTERFACE_KNOWN (type) && TYPE_POLYMORPHIC_P (type) && CLASSTYPE_INTERFACE_ONLY (type) /* If -fno-rtti was specified, then we cannot be sure that RTTI information will be emitted with the virtual table of the class, so we must emit it wherever it is used. */ && flag_rtti) import_p = true; else { if (CLASSTYPE_INTERFACE_KNOWN (type) && !CLASSTYPE_INTERFACE_ONLY (type)) { comdat_p = (targetm.cxx.class_data_always_comdat () || (CLASSTYPE_KEY_METHOD (type) && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type)))); mark_needed (decl); if (!flag_weak) { comdat_p = false; DECL_EXTERNAL (decl) = 0; } } else comdat_p = true; } } else comdat_p = true; } else if (DECL_TEMPLOID_INSTANTIATION (decl)) { /* DECL is an implicit instantiation of a function or static data member. */ if ((flag_implicit_templates && !flag_use_repository) || (flag_implicit_inline_templates && TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl))) comdat_p = true; else /* If we are not implicitly generating templates, then mark this entity as undefined in this translation unit. */ import_p = true; } else if (DECL_FUNCTION_MEMBER_P (decl)) { if (!DECL_DECLARED_INLINE_P (decl)) { tree ctype = DECL_CONTEXT (decl); import_export_class (ctype); if (CLASSTYPE_INTERFACE_KNOWN (ctype)) { DECL_NOT_REALLY_EXTERN (decl) = ! (CLASSTYPE_INTERFACE_ONLY (ctype) || (DECL_DECLARED_INLINE_P (decl) && ! flag_implement_inlines && !DECL_VINDEX (decl))); if (!DECL_NOT_REALLY_EXTERN (decl)) DECL_EXTERNAL (decl) = 1; /* Always make artificials weak. */ if (DECL_ARTIFICIAL (decl) && flag_weak) comdat_p = true; else maybe_make_one_only (decl); } } else comdat_p = true; } else comdat_p = true; if (import_p) { /* If we are importing DECL into this translation unit, mark is an undefined here. */ DECL_EXTERNAL (decl) = 1; DECL_NOT_REALLY_EXTERN (decl) = 0; } else if (comdat_p) { /* If we decided to put DECL in COMDAT, mark it accordingly at this point. */ comdat_linkage (decl); } DECL_INTERFACE_KNOWN (decl) = 1; } /* Return an expression that performs the destruction of DECL, which must be a VAR_DECL whose type has a non-trivial destructor, or is an array whose (innermost) elements have a non-trivial destructor. */ tree build_cleanup (tree decl) { tree clean = cxx_maybe_build_cleanup (decl, tf_warning_or_error); gcc_assert (clean != NULL_TREE); return clean; } /* Returns the initialization guard variable for the variable DECL, which has static storage duration. */ tree get_guard (tree decl) { tree sname; tree guard; sname = mangle_guard_variable (decl); guard = IDENTIFIER_GLOBAL_VALUE (sname); if (! guard) { tree guard_type; /* We use a type that is big enough to contain a mutex as well as an integer counter. */ guard_type = targetm.cxx.guard_type (); guard = build_decl (DECL_SOURCE_LOCATION (decl), VAR_DECL, sname, guard_type); /* The guard should have the same linkage as what it guards. */ TREE_PUBLIC (guard) = TREE_PUBLIC (decl); TREE_STATIC (guard) = TREE_STATIC (decl); DECL_COMMON (guard) = DECL_COMMON (decl); DECL_COMDAT (guard) = DECL_COMDAT (decl); set_decl_tls_model (guard, DECL_TLS_MODEL (decl)); if (DECL_ONE_ONLY (decl)) make_decl_one_only (guard, cxx_comdat_group (guard)); if (TREE_PUBLIC (decl)) DECL_WEAK (guard) = DECL_WEAK (decl); DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl); DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl); DECL_ARTIFICIAL (guard) = 1; DECL_IGNORED_P (guard) = 1; TREE_USED (guard) = 1; pushdecl_top_level_and_finish (guard, NULL_TREE); } return guard; } /* Return those bits of the GUARD variable that should be set when the guarded entity is actually initialized. */ static tree get_guard_bits (tree guard) { if (!targetm.cxx.guard_mask_bit ()) { /* We only set the first byte of the guard, in order to leave room for a mutex in the high-order bits. */ guard = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (guard)), guard); guard = build1 (NOP_EXPR, build_pointer_type (char_type_node), guard); guard = build1 (INDIRECT_REF, char_type_node, guard); } return guard; } /* Return an expression which determines whether or not the GUARD variable has already been initialized. */ tree get_guard_cond (tree guard) { tree guard_value; /* Check to see if the GUARD is zero. */ guard = get_guard_bits (guard); /* Mask off all but the low bit. */ if (targetm.cxx.guard_mask_bit ()) { guard_value = integer_one_node; if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard))) guard_value = convert (TREE_TYPE (guard), guard_value); guard = cp_build_binary_op (input_location, BIT_AND_EXPR, guard, guard_value, tf_warning_or_error); } guard_value = integer_zero_node; if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard))) guard_value = convert (TREE_TYPE (guard), guard_value); return cp_build_binary_op (input_location, EQ_EXPR, guard, guard_value, tf_warning_or_error); } /* Return an expression which sets the GUARD variable, indicating that the variable being guarded has been initialized. */ tree set_guard (tree guard) { tree guard_init; /* Set the GUARD to one. */ guard = get_guard_bits (guard); guard_init = integer_one_node; if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard))) guard_init = convert (TREE_TYPE (guard), guard_init); return cp_build_modify_expr (guard, NOP_EXPR, guard_init, tf_warning_or_error); } /* Returns true iff we can tell that VAR does not have a dynamic initializer. */ static bool var_defined_without_dynamic_init (tree var) { /* If it's defined in another TU, we can't tell. */ if (DECL_EXTERNAL (var)) return false; /* If it has a non-trivial destructor, registering the destructor counts as dynamic initialization. */ if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var))) return false; /* If it's in this TU, its initializer has been processed, unless it's a case of self-initialization, then DECL_INITIALIZED_P is false while the initializer is handled by finish_id_expression. */ if (!DECL_INITIALIZED_P (var)) return false; /* If it has no initializer or a constant one, it's not dynamic. */ return (!DECL_NONTRIVIALLY_INITIALIZED_P (var) || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var)); } /* Returns true iff VAR is a variable that needs uses to be wrapped for possible dynamic initialization. */ static bool var_needs_tls_wrapper (tree var) { return (!error_operand_p (var) && DECL_THREAD_LOCAL_P (var) && !DECL_GNU_TLS_P (var) && !DECL_FUNCTION_SCOPE_P (var) && !var_defined_without_dynamic_init (var)); } /* Get the FUNCTION_DECL for the shared TLS init function for this translation unit. */ static tree get_local_tls_init_fn (void) { tree sname = get_identifier ("__tls_init"); tree fn = IDENTIFIER_GLOBAL_VALUE (sname); if (!fn) { fn = build_lang_decl (FUNCTION_DECL, sname, build_function_type (void_type_node, void_list_node)); SET_DECL_LANGUAGE (fn, lang_c); TREE_PUBLIC (fn) = false; DECL_ARTIFICIAL (fn) = true; mark_used (fn); SET_IDENTIFIER_GLOBAL_VALUE (sname, fn); } return fn; } /* Get a FUNCTION_DECL for the init function for the thread_local variable VAR. The init function will be an alias to the function that initializes all the non-local TLS variables in the translation unit. The init function is only used by the wrapper function. */ static tree get_tls_init_fn (tree var) { /* Only C++11 TLS vars need this init fn. */ if (!var_needs_tls_wrapper (var)) return NULL_TREE; /* If -fno-extern-tls-init, assume that we don't need to call a tls init function for a variable defined in another TU. */ if (!flag_extern_tls_init && DECL_EXTERNAL (var)) return NULL_TREE; #ifdef ASM_OUTPUT_DEF /* If the variable is internal, or if we can't generate aliases, call the local init function directly. */ if (!TREE_PUBLIC (var)) #endif return get_local_tls_init_fn (); tree sname = mangle_tls_init_fn (var); tree fn = IDENTIFIER_GLOBAL_VALUE (sname); if (!fn) { fn = build_lang_decl (FUNCTION_DECL, sname, build_function_type (void_type_node, void_list_node)); SET_DECL_LANGUAGE (fn, lang_c); TREE_PUBLIC (fn) = TREE_PUBLIC (var); DECL_ARTIFICIAL (fn) = true; DECL_COMDAT (fn) = DECL_COMDAT (var); DECL_EXTERNAL (fn) = DECL_EXTERNAL (var); if (DECL_ONE_ONLY (var)) make_decl_one_only (fn, cxx_comdat_group (fn)); if (TREE_PUBLIC (var)) { tree obtype = strip_array_types (non_reference (TREE_TYPE (var))); /* If the variable is defined somewhere else and might have static initialization, make the init function a weak reference. */ if ((!TYPE_NEEDS_CONSTRUCTING (obtype) || TYPE_HAS_CONSTEXPR_CTOR (obtype)) && TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype) && DECL_EXTERNAL (var)) declare_weak (fn); else DECL_WEAK (fn) = DECL_WEAK (var); } DECL_VISIBILITY (fn) = DECL_VISIBILITY (var); DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var); DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var); DECL_IGNORED_P (fn) = 1; mark_used (fn); DECL_BEFRIENDING_CLASSES (fn) = var; SET_IDENTIFIER_GLOBAL_VALUE (sname, fn); } return fn; } /* Get a FUNCTION_DECL for the init wrapper function for the thread_local variable VAR. The wrapper function calls the init function (if any) for VAR and then returns a reference to VAR. The wrapper function is used in place of VAR everywhere VAR is mentioned. */ tree get_tls_wrapper_fn (tree var) { /* Only C++11 TLS vars need this wrapper fn. */ if (!var_needs_tls_wrapper (var)) return NULL_TREE; tree sname = mangle_tls_wrapper_fn (var); tree fn = IDENTIFIER_GLOBAL_VALUE (sname); if (!fn) { /* A named rvalue reference is an lvalue, so the wrapper should always return an lvalue reference. */ tree type = non_reference (TREE_TYPE (var)); type = build_reference_type (type); tree fntype = build_function_type (type, void_list_node); fn = build_lang_decl (FUNCTION_DECL, sname, fntype); SET_DECL_LANGUAGE (fn, lang_c); TREE_PUBLIC (fn) = TREE_PUBLIC (var); DECL_ARTIFICIAL (fn) = true; DECL_IGNORED_P (fn) = 1; /* The wrapper is inline and emitted everywhere var is used. */ DECL_DECLARED_INLINE_P (fn) = true; if (TREE_PUBLIC (var)) { comdat_linkage (fn); #ifdef HAVE_GAS_HIDDEN /* Make the wrapper bind locally; there's no reason to share the wrapper between multiple shared objects. */ DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL; DECL_VISIBILITY_SPECIFIED (fn) = true; #endif } if (!TREE_PUBLIC (fn)) DECL_INTERFACE_KNOWN (fn) = true; mark_used (fn); note_vague_linkage_fn (fn); #if 0 /* We want CSE to commonize calls to the wrapper, but marking it as pure is unsafe since it has side-effects. I guess we need a new ECF flag even weaker than ECF_PURE. FIXME! */ DECL_PURE_P (fn) = true; #endif DECL_BEFRIENDING_CLASSES (fn) = var; SET_IDENTIFIER_GLOBAL_VALUE (sname, fn); } return fn; } /* At EOF, generate the definition for the TLS wrapper function FN: T& var_wrapper() { if (init_fn) init_fn(); return var; } */ static void generate_tls_wrapper (tree fn) { tree var = DECL_BEFRIENDING_CLASSES (fn); start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED); tree body = begin_function_body (); /* Only call the init fn if there might be one. */ if (tree init_fn = get_tls_init_fn (var)) { tree if_stmt = NULL_TREE; /* If init_fn is a weakref, make sure it exists before calling. */ if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn))) { if_stmt = begin_if_stmt (); tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error); tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var), NE_EXPR, addr, nullptr_node, tf_warning_or_error); finish_if_stmt_cond (cond, if_stmt); } finish_expr_stmt (build_cxx_call (init_fn, 0, NULL, tf_warning_or_error)); if (if_stmt) { finish_then_clause (if_stmt); finish_if_stmt (if_stmt); } } else /* If there's no initialization, the wrapper is a constant function. */ TREE_READONLY (fn) = true; finish_return_stmt (convert_from_reference (var)); finish_function_body (body); expand_or_defer_fn (finish_function (0)); } /* Start the process of running a particular set of global constructors or destructors. Subroutine of do_[cd]tors. Also called from vtv_start_verification_constructor_init_function. */ static tree start_objects (int method_type, int initp) { tree body; tree fndecl; char type[14]; /* Make ctor or dtor function. METHOD_TYPE may be 'I' or 'D'. */ if (initp != DEFAULT_INIT_PRIORITY) { char joiner; #ifdef JOINER joiner = JOINER; #else joiner = '_'; #endif sprintf (type, "sub_%c%c%.5u", method_type, joiner, initp); } else sprintf (type, "sub_%c", method_type); fndecl = build_lang_decl (FUNCTION_DECL, get_file_function_name (type), build_function_type_list (void_type_node, NULL_TREE)); start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED); TREE_PUBLIC (current_function_decl) = 0; /* Mark as artificial because it's not explicitly in the user's source code. */ DECL_ARTIFICIAL (current_function_decl) = 1; /* Mark this declaration as used to avoid spurious warnings. */ TREE_USED (current_function_decl) = 1; /* Mark this function as a global constructor or destructor. */ if (method_type == 'I') DECL_GLOBAL_CTOR_P (current_function_decl) = 1; else DECL_GLOBAL_DTOR_P (current_function_decl) = 1; body = begin_compound_stmt (BCS_FN_BODY); return body; } /* Finish the process of running a particular set of global constructors or destructors. Subroutine of do_[cd]tors. */ static void finish_objects (int method_type, int initp, tree body) { tree fn; /* Finish up. */ finish_compound_stmt (body); fn = finish_function (0); if (method_type == 'I') { DECL_STATIC_CONSTRUCTOR (fn) = 1; decl_init_priority_insert (fn, initp); } else { DECL_STATIC_DESTRUCTOR (fn) = 1; decl_fini_priority_insert (fn, initp); } expand_or_defer_fn (fn); } /* The names of the parameters to the function created to handle initializations and destructions for objects with static storage duration. */ #define INITIALIZE_P_IDENTIFIER "__initialize_p" #define PRIORITY_IDENTIFIER "__priority" /* The name of the function we create to handle initializations and destructions for objects with static storage duration. */ #define SSDF_IDENTIFIER "__static_initialization_and_destruction" /* The declaration for the __INITIALIZE_P argument. */ static GTY(()) tree initialize_p_decl; /* The declaration for the __PRIORITY argument. */ static GTY(()) tree priority_decl; /* The declaration for the static storage duration function. */ static GTY(()) tree ssdf_decl; /* All the static storage duration functions created in this translation unit. */ static GTY(()) vec<tree, va_gc> *ssdf_decls; /* A map from priority levels to information about that priority level. There may be many such levels, so efficient lookup is important. */ static splay_tree priority_info_map; /* Begins the generation of the function that will handle all initialization and destruction of objects with static storage duration. The function generated takes two parameters of type `int': __INITIALIZE_P and __PRIORITY. If __INITIALIZE_P is nonzero, it performs initializations. Otherwise, it performs destructions. It only performs those initializations or destructions with the indicated __PRIORITY. The generated function returns no value. It is assumed that this function will only be called once per translation unit. */ static tree start_static_storage_duration_function (unsigned count) { tree type; tree body; char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32]; /* Create the identifier for this function. It will be of the form SSDF_IDENTIFIER_<number>. */ sprintf (id, "%s_%u", SSDF_IDENTIFIER, count); type = build_function_type_list (void_type_node, integer_type_node, integer_type_node, NULL_TREE); /* Create the FUNCTION_DECL itself. */ ssdf_decl = build_lang_decl (FUNCTION_DECL, get_identifier (id), type); TREE_PUBLIC (ssdf_decl) = 0; DECL_ARTIFICIAL (ssdf_decl) = 1; /* Put this function in the list of functions to be called from the static constructors and destructors. */ if (!ssdf_decls) { vec_alloc (ssdf_decls, 32); /* Take this opportunity to initialize the map from priority numbers to information about that priority level. */ priority_info_map = splay_tree_new (splay_tree_compare_ints, /*delete_key_fn=*/0, /*delete_value_fn=*/ (splay_tree_delete_value_fn) &free); /* We always need to generate functions for the DEFAULT_INIT_PRIORITY so enter it now. That way when we walk priorities later, we'll be sure to find the DEFAULT_INIT_PRIORITY. */ get_priority_info (DEFAULT_INIT_PRIORITY); } vec_safe_push (ssdf_decls, ssdf_decl); /* Create the argument list. */ initialize_p_decl = cp_build_parm_decl (get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node); DECL_CONTEXT (initialize_p_decl) = ssdf_decl; TREE_USED (initialize_p_decl) = 1; priority_decl = cp_build_parm_decl (get_identifier (PRIORITY_IDENTIFIER), integer_type_node); DECL_CONTEXT (priority_decl) = ssdf_decl; TREE_USED (priority_decl) = 1; DECL_CHAIN (initialize_p_decl) = priority_decl; DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl; /* Put the function in the global scope. */ pushdecl (ssdf_decl); /* Start the function itself. This is equivalent to declaring the function as: static void __ssdf (int __initialize_p, init __priority_p); It is static because we only need to call this function from the various constructor and destructor functions for this module. */ start_preparsed_function (ssdf_decl, /*attrs=*/NULL_TREE, SF_PRE_PARSED); /* Set up the scope of the outermost block in the function. */ body = begin_compound_stmt (BCS_FN_BODY); return body; } /* Finish the generation of the function which performs initialization and destruction of objects with static storage duration. After this point, no more such objects can be created. */ static void finish_static_storage_duration_function (tree body) { /* Close out the function. */ finish_compound_stmt (body); expand_or_defer_fn (finish_function (0)); } /* Return the information about the indicated PRIORITY level. If no code to handle this level has yet been generated, generate the appropriate prologue. */ static priority_info get_priority_info (int priority) { priority_info pi; splay_tree_node n; n = splay_tree_lookup (priority_info_map, (splay_tree_key) priority); if (!n) { /* Create a new priority information structure, and insert it into the map. */ pi = XNEW (struct priority_info_s); pi->initializations_p = 0; pi->destructions_p = 0; splay_tree_insert (priority_info_map, (splay_tree_key) priority, (splay_tree_value) pi); } else pi = (priority_info) n->value; return pi; } /* The effective initialization priority of a DECL. */ #define DECL_EFFECTIVE_INIT_PRIORITY(decl) \ ((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \ ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl)) /* Whether a DECL needs a guard to protect it against multiple initialization. */ #define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl) \ || DECL_ONE_ONLY (decl) \ || DECL_WEAK (decl))) /* Called from one_static_initialization_or_destruction(), via walk_tree. Walks the initializer list of a global variable and looks for temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0) and that have their DECL_CONTEXT() == NULL. For each such temporary variable, set their DECL_CONTEXT() to the current function. This is necessary because otherwise some optimizers (enabled by -O2 -fprofile-arcs) might crash when trying to refer to a temporary variable that does not have it's DECL_CONTECT() properly set. */ static tree fix_temporary_vars_context_r (tree *node, int * /*unused*/, void * /*unused1*/) { gcc_assert (current_function_decl); if (TREE_CODE (*node) == BIND_EXPR) { tree var; for (var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var)) if (VAR_P (var) && !DECL_NAME (var) && DECL_ARTIFICIAL (var) && !DECL_CONTEXT (var)) DECL_CONTEXT (var) = current_function_decl; } return NULL_TREE; } /* Set up to handle the initialization or destruction of DECL. If INITP is nonzero, we are initializing the variable. Otherwise, we are destroying it. */ static void one_static_initialization_or_destruction (tree decl, tree init, bool initp) { tree guard_if_stmt = NULL_TREE; tree guard; /* If we are supposed to destruct and there's a trivial destructor, nothing has to be done. */ if (!initp && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl))) return; /* Trick the compiler into thinking we are at the file and line where DECL was declared so that error-messages make sense, and so that the debugger will show somewhat sensible file and line information. */ input_location = DECL_SOURCE_LOCATION (decl); /* Make sure temporary variables in the initialiser all have their DECL_CONTEXT() set to a value different from NULL_TREE. This can happen when global variables initialisers are built. In that case, the DECL_CONTEXT() of the global variables _AND_ of all the temporary variables that might have been generated in the accompagning initialisers is NULL_TREE, meaning the variables have been declared in the global namespace. What we want to do here is to fix that and make sure the DECL_CONTEXT() of the temporaries are set to the current function decl. */ cp_walk_tree_without_duplicates (&init, fix_temporary_vars_context_r, NULL); /* Because of: [class.access.spec] Access control for implicit calls to the constructors, the conversion functions, or the destructor called to create and destroy a static data member is performed as if these calls appeared in the scope of the member's class. we pretend we are in a static member function of the class of which the DECL is a member. */ if (member_p (decl)) { DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl); DECL_STATIC_FUNCTION_P (current_function_decl) = 1; } /* Assume we don't need a guard. */ guard = NULL_TREE; /* We need a guard if this is an object with external linkage that might be initialized in more than one place. (For example, a static data member of a template, when the data member requires construction.) */ if (NEEDS_GUARD_P (decl)) { tree guard_cond; guard = get_guard (decl); /* When using __cxa_atexit, we just check the GUARD as we would for a local static. */ if (flag_use_cxa_atexit) { /* When using __cxa_atexit, we never try to destroy anything from a static destructor. */ gcc_assert (initp); guard_cond = get_guard_cond (guard); } /* If we don't have __cxa_atexit, then we will be running destructors from .fini sections, or their equivalents. So, we need to know how many times we've tried to initialize this object. We do initializations only if the GUARD is zero, i.e., if we are the first to initialize the variable. We do destructions only if the GUARD is one, i.e., if we are the last to destroy the variable. */ else if (initp) guard_cond = cp_build_binary_op (input_location, EQ_EXPR, cp_build_unary_op (PREINCREMENT_EXPR, guard, /*noconvert=*/1, tf_warning_or_error), integer_one_node, tf_warning_or_error); else guard_cond = cp_build_binary_op (input_location, EQ_EXPR, cp_build_unary_op (PREDECREMENT_EXPR, guard, /*noconvert=*/1, tf_warning_or_error), integer_zero_node, tf_warning_or_error); guard_if_stmt = begin_if_stmt (); finish_if_stmt_cond (guard_cond, guard_if_stmt); } /* If we're using __cxa_atexit, we have not already set the GUARD, so we must do so now. */ if (guard && initp && flag_use_cxa_atexit) finish_expr_stmt (set_guard (guard)); /* Perform the initialization or destruction. */ if (initp) { if (init) { finish_expr_stmt (init); if (flag_sanitize & SANITIZE_ADDRESS) { varpool_node *vnode = varpool_node::get (decl); if (vnode) vnode->dynamically_initialized = 1; } } /* If we're using __cxa_atexit, register a function that calls the destructor for the object. */ if (flag_use_cxa_atexit) finish_expr_stmt (register_dtor_fn (decl)); } else finish_expr_stmt (build_cleanup (decl)); /* Finish the guard if-stmt, if necessary. */ if (guard) { finish_then_clause (guard_if_stmt); finish_if_stmt (guard_if_stmt); } /* Now that we're done with DECL we don't need to pretend to be a member of its class any longer. */ DECL_CONTEXT (current_function_decl) = NULL_TREE; DECL_STATIC_FUNCTION_P (current_function_decl) = 0; } /* Generate code to do the initialization or destruction of the decls in VARS, a TREE_LIST of VAR_DECL with static storage duration. Whether initialization or destruction is performed is specified by INITP. */ static void do_static_initialization_or_destruction (tree vars, bool initp) { tree node, init_if_stmt, cond; /* Build the outer if-stmt to check for initialization or destruction. */ init_if_stmt = begin_if_stmt (); cond = initp ? integer_one_node : integer_zero_node; cond = cp_build_binary_op (input_location, EQ_EXPR, initialize_p_decl, cond, tf_warning_or_error); finish_if_stmt_cond (cond, init_if_stmt); /* To make sure dynamic construction doesn't access globals from other compilation units where they might not be yet constructed, for -fsanitize=address insert __asan_before_dynamic_init call that prevents access to either all global variables that need construction in other compilation units, or at least those that haven't been initialized yet. Variables that need dynamic construction in the current compilation unit are kept accessible. */ if (flag_sanitize & SANITIZE_ADDRESS) finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/false)); node = vars; do { tree decl = TREE_VALUE (node); tree priority_if_stmt; int priority; priority_info pi; /* If we don't need a destructor, there's nothing to do. Avoid creating a possibly empty if-stmt. */ if (!initp && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl))) { node = TREE_CHAIN (node); continue; } /* Remember that we had an initialization or finalization at this priority. */ priority = DECL_EFFECTIVE_INIT_PRIORITY (decl); pi = get_priority_info (priority); if (initp) pi->initializations_p = 1; else pi->destructions_p = 1; /* Conditionalize this initialization on being in the right priority and being initializing/finalizing appropriately. */ priority_if_stmt = begin_if_stmt (); cond = cp_build_binary_op (input_location, EQ_EXPR, priority_decl, build_int_cst (NULL_TREE, priority), tf_warning_or_error); finish_if_stmt_cond (cond, priority_if_stmt); /* Process initializers with same priority. */ for (; node && DECL_EFFECTIVE_INIT_PRIORITY (TREE_VALUE (node)) == priority; node = TREE_CHAIN (node)) /* Do one initialization or destruction. */ one_static_initialization_or_destruction (TREE_VALUE (node), TREE_PURPOSE (node), initp); /* Finish up the priority if-stmt body. */ finish_then_clause (priority_if_stmt); finish_if_stmt (priority_if_stmt); } while (node); /* Revert what __asan_before_dynamic_init did by calling __asan_after_dynamic_init. */ if (flag_sanitize & SANITIZE_ADDRESS) finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/true)); /* Finish up the init/destruct if-stmt body. */ finish_then_clause (init_if_stmt); finish_if_stmt (init_if_stmt); } /* VARS is a list of variables with static storage duration which may need initialization and/or finalization. Remove those variables that don't really need to be initialized or finalized, and return the resulting list. The order in which the variables appear in VARS is in reverse order of the order in which they should actually be initialized. The list we return is in the unreversed order; i.e., the first variable should be initialized first. */ static tree prune_vars_needing_no_initialization (tree *vars) { tree *var = vars; tree result = NULL_TREE; while (*var) { tree t = *var; tree decl = TREE_VALUE (t); tree init = TREE_PURPOSE (t); /* Deal gracefully with error. */ if (decl == error_mark_node) { var = &TREE_CHAIN (t); continue; } /* The only things that can be initialized are variables. */ gcc_assert (VAR_P (decl)); /* If this object is not defined, we don't need to do anything here. */ if (DECL_EXTERNAL (decl)) { var = &TREE_CHAIN (t); continue; } /* Also, if the initializer already contains errors, we can bail out now. */ if (init && TREE_CODE (init) == TREE_LIST && value_member (error_mark_node, init)) { var = &TREE_CHAIN (t); continue; } /* This variable is going to need initialization and/or finalization, so we add it to the list. */ *var = TREE_CHAIN (t); TREE_CHAIN (t) = result; result = t; } return result; } /* Make sure we have told the back end about all the variables in VARS. */ static void write_out_vars (tree vars) { tree v; for (v = vars; v; v = TREE_CHAIN (v)) { tree var = TREE_VALUE (v); if (!var_finalized_p (var)) { import_export_decl (var); rest_of_decl_compilation (var, 1, 1); } } } /* Generate a static constructor (if CONSTRUCTOR_P) or destructor (otherwise) that will initialize all global objects with static storage duration having the indicated PRIORITY. */ static void generate_ctor_or_dtor_function (bool constructor_p, int priority, location_t *locus) { char function_key; tree fndecl; tree body; size_t i; input_location = *locus; /* ??? */ /* Was: locus->line++; */ /* We use `I' to indicate initialization and `D' to indicate destruction. */ function_key = constructor_p ? 'I' : 'D'; /* We emit the function lazily, to avoid generating empty global constructors and destructors. */ body = NULL_TREE; /* For Objective-C++, we may need to initialize metadata found in this module. This must be done _before_ any other static initializations. */ if (c_dialect_objc () && (priority == DEFAULT_INIT_PRIORITY) && constructor_p && objc_static_init_needed_p ()) { body = start_objects (function_key, priority); objc_generate_static_init_call (NULL_TREE); } /* Call the static storage duration function with appropriate arguments. */ FOR_EACH_VEC_SAFE_ELT (ssdf_decls, i, fndecl) { /* Calls to pure or const functions will expand to nothing. */ if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE))) { tree call; if (! body) body = start_objects (function_key, priority); call = cp_build_function_call_nary (fndecl, tf_warning_or_error, build_int_cst (NULL_TREE, constructor_p), build_int_cst (NULL_TREE, priority), NULL_TREE); finish_expr_stmt (call); } } /* Close out the function. */ if (body) finish_objects (function_key, priority, body); } /* Generate constructor and destructor functions for the priority indicated by N. */ static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data) { location_t *locus = (location_t *) data; int priority = (int) n->key; priority_info pi = (priority_info) n->value; /* Generate the functions themselves, but only if they are really needed. */ if (pi->initializations_p) generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus); if (pi->destructions_p) generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus); /* Keep iterating. */ return 0; } /* Java requires that we be able to reference a local address for a method, and not be confused by PLT entries. If hidden aliases are supported, collect and return all the functions for which we should emit a hidden alias. */ static hash_set<tree> * collect_candidates_for_java_method_aliases (void) { struct cgraph_node *node; hash_set<tree> *candidates = NULL; #ifndef HAVE_GAS_HIDDEN return candidates; #endif FOR_EACH_FUNCTION (node) { tree fndecl = node->decl; if (DECL_CLASS_SCOPE_P (fndecl) && TYPE_FOR_JAVA (DECL_CONTEXT (fndecl)) && TARGET_USE_LOCAL_THUNK_ALIAS_P (fndecl)) { if (candidates == NULL) candidates = new hash_set<tree>; candidates->add (fndecl); } } return candidates; } /* Java requires that we be able to reference a local address for a method, and not be confused by PLT entries. If hidden aliases are supported, emit one for each java function that we've emitted. CANDIDATES is the set of FUNCTION_DECLs that were gathered by collect_candidates_for_java_method_aliases. */ static void build_java_method_aliases (hash_set<tree> *candidates) { struct cgraph_node *node; #ifndef HAVE_GAS_HIDDEN return; #endif FOR_EACH_FUNCTION (node) { tree fndecl = node->decl; if (TREE_ASM_WRITTEN (fndecl) && candidates->contains (fndecl)) { /* Mangle the name in a predictable way; we need to reference this from a java compiled object file. */ tree oid, nid, alias; const char *oname; char *nname; oid = DECL_ASSEMBLER_NAME (fndecl); oname = IDENTIFIER_POINTER (oid); gcc_assert (oname[0] == '_' && oname[1] == 'Z'); nname = ACONCAT (("_ZGA", oname+2, NULL)); nid = get_identifier (nname); alias = make_alias_for (fndecl, nid); TREE_PUBLIC (alias) = 1; DECL_VISIBILITY (alias) = VISIBILITY_HIDDEN; assemble_alias (alias, oid); } } } /* Return C++ property of T, based on given operation OP. */ static int cpp_check (tree t, cpp_operation op) { switch (op) { case IS_ABSTRACT: return DECL_PURE_VIRTUAL_P (t); case IS_CONSTRUCTOR: return DECL_CONSTRUCTOR_P (t); case IS_DESTRUCTOR: return DECL_DESTRUCTOR_P (t); case IS_COPY_CONSTRUCTOR: return DECL_COPY_CONSTRUCTOR_P (t); case IS_TEMPLATE: return TREE_CODE (t) == TEMPLATE_DECL; case IS_TRIVIAL: return trivial_type_p (t); default: return 0; } } /* Collect source file references recursively, starting from NAMESPC. */ static void collect_source_refs (tree namespc) { tree t; if (!namespc) return; /* Iterate over names in this name space. */ for (t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t)) if (!DECL_IS_BUILTIN (t) ) collect_source_ref (DECL_SOURCE_FILE (t)); /* Dump siblings, if any */ collect_source_refs (TREE_CHAIN (namespc)); /* Dump children, if any */ collect_source_refs (NAMESPACE_LEVEL (namespc)->namespaces); } /* Collect decls relevant to SOURCE_FILE from all namespaces recursively, starting from NAMESPC. */ static void collect_ada_namespace (tree namespc, const char *source_file) { if (!namespc) return; /* Collect decls from this namespace */ collect_ada_nodes (NAMESPACE_LEVEL (namespc)->names, source_file); /* Collect siblings, if any */ collect_ada_namespace (TREE_CHAIN (namespc), source_file); /* Collect children, if any */ collect_ada_namespace (NAMESPACE_LEVEL (namespc)->namespaces, source_file); } /* Returns true iff there is a definition available for variable or function DECL. */ static bool decl_defined_p (tree decl) { if (TREE_CODE (decl) == FUNCTION_DECL) return (DECL_INITIAL (decl) != NULL_TREE); else { gcc_assert (VAR_P (decl)); return !DECL_EXTERNAL (decl); } } /* Nonzero for a VAR_DECL whose value can be used in a constant expression. [expr.const] An integral constant-expression can only involve ... const variables of integral or enumeration types initialized with constant expressions ... C++0x also allows constexpr variables and temporaries initialized with constant expressions. We handle the former here, but the latter are just folded away in cxx_eval_constant_expression. The standard does not require that the expression be non-volatile. G++ implements the proposed correction in DR 457. */ bool decl_constant_var_p (tree decl) { if (!decl_maybe_constant_var_p (decl)) return false; /* We don't know if a template static data member is initialized with a constant expression until we instantiate its initializer. Even in the case of a constexpr variable, we can't treat it as a constant until its initializer is complete in case it's used in its own initializer. */ mark_used (decl); return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl); } /* Returns true if DECL could be a symbolic constant variable, depending on its initializer. */ bool decl_maybe_constant_var_p (tree decl) { tree type = TREE_TYPE (decl); if (!VAR_P (decl)) return false; if (DECL_DECLARED_CONSTEXPR_P (decl)) return true; return (CP_TYPE_CONST_NON_VOLATILE_P (type) && INTEGRAL_OR_ENUMERATION_TYPE_P (type)); } /* Complain that DECL uses a type with no linkage. In C++98 mode this is called from grokfndecl and grokvardecl; in all modes it is called from cp_write_global_declarations. */ void no_linkage_error (tree decl) { if (cxx_dialect >= cxx11 && decl_defined_p (decl)) /* In C++11 it's ok if the decl is defined. */ return; tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false); if (t == NULL_TREE) /* The type that got us on no_linkage_decls must have gotten a name for linkage purposes. */; else if (CLASS_TYPE_P (t) && TYPE_BEING_DEFINED (t)) /* The type might end up having a typedef name for linkage purposes. */ vec_safe_push (no_linkage_decls, decl); else if (TYPE_ANONYMOUS_P (t)) { bool d = false; if (cxx_dialect >= cxx11) d = permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using " "anonymous type, is used but never defined", decl); else if (DECL_EXTERN_C_P (decl)) /* Allow this; it's pretty common in C. */; else if (TREE_CODE (decl) == VAR_DECL) /* DRs 132, 319 and 389 seem to indicate types with no linkage can only be used to declare extern "C" entities. Since it's not always an error in the ISO C++ 90 Standard, we only issue a warning. */ d = warning_at (DECL_SOURCE_LOCATION (decl), 0, "anonymous type " "with no linkage used to declare variable %q#D with " "linkage", decl); else d = permerror (DECL_SOURCE_LOCATION (decl), "anonymous type with no " "linkage used to declare function %q#D with linkage", decl); if (d && is_typedef_decl (TYPE_NAME (t))) inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "%q#D does not refer " "to the unqualified type, so it is not used for linkage", TYPE_NAME (t)); } else if (cxx_dialect >= cxx11) permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using local type " "%qT, is used but never defined", decl, t); else if (TREE_CODE (decl) == VAR_DECL) warning_at (DECL_SOURCE_LOCATION (decl), 0, "type %qT with no linkage " "used to declare variable %q#D with linkage", t, decl); else permerror (DECL_SOURCE_LOCATION (decl), "type %qT with no linkage used " "to declare function %q#D with linkage", t, decl); } /* Collect declarations from all namespaces relevant to SOURCE_FILE. */ static void collect_all_refs (const char *source_file) { collect_ada_namespace (global_namespace, source_file); } /* Clear DECL_EXTERNAL for NODE. */ static bool clear_decl_external (struct cgraph_node *node, void * /*data*/) { DECL_EXTERNAL (node->decl) = 0; return false; } /* Build up the function to run dynamic initializers for thread_local variables in this translation unit and alias the init functions for the individual variables to it. */ static void handle_tls_init (void) { tree vars = prune_vars_needing_no_initialization (&tls_aggregates); if (vars == NULL_TREE) return; location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars)); write_out_vars (vars); tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"), boolean_type_node); TREE_PUBLIC (guard) = false; TREE_STATIC (guard) = true; DECL_ARTIFICIAL (guard) = true; DECL_IGNORED_P (guard) = true; TREE_USED (guard) = true; set_decl_tls_model (guard, decl_default_tls_model (guard)); pushdecl_top_level_and_finish (guard, NULL_TREE); tree fn = get_local_tls_init_fn (); start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED); tree body = begin_function_body (); tree if_stmt = begin_if_stmt (); tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false, tf_warning_or_error); finish_if_stmt_cond (cond, if_stmt); finish_expr_stmt (cp_build_modify_expr (guard, NOP_EXPR, boolean_true_node, tf_warning_or_error)); for (; vars; vars = TREE_CHAIN (vars)) { tree var = TREE_VALUE (vars); tree init = TREE_PURPOSE (vars); one_static_initialization_or_destruction (var, init, true); #ifdef ASM_OUTPUT_DEF /* Output init aliases even with -fno-extern-tls-init. */ if (TREE_PUBLIC (var)) { tree single_init_fn = get_tls_init_fn (var); if (single_init_fn == NULL_TREE) continue; cgraph_node *alias = cgraph_node::get_create (fn)->create_same_body_alias (single_init_fn, fn); gcc_assert (alias != NULL); } #endif } finish_then_clause (if_stmt); finish_if_stmt (if_stmt); finish_function_body (body); expand_or_defer_fn (finish_function (0)); } /* The entire file is now complete. If requested, dump everything to a file. */ static void dump_tu (void) { int flags; FILE *stream = dump_begin (TDI_tu, &flags); if (stream) { dump_node (global_namespace, flags & ~TDF_SLIM, stream); dump_end (TDI_tu, stream); } } /* Check the deallocation functions for CODE to see if we want to warn that only one was defined. */ static void maybe_warn_sized_delete (enum tree_code code) { tree sized = NULL_TREE; tree unsized = NULL_TREE; for (tree ovl = IDENTIFIER_GLOBAL_VALUE (ansi_opname (code)); ovl; ovl = OVL_NEXT (ovl)) { tree fn = OVL_CURRENT (ovl); /* We're only interested in usual deallocation functions. */ if (!non_placement_deallocation_fn_p (fn)) continue; if (FUNCTION_ARG_CHAIN (fn) == void_list_node) unsized = fn; else sized = fn; } if (DECL_INITIAL (unsized) && !DECL_INITIAL (sized)) warning_at (DECL_SOURCE_LOCATION (unsized), OPT_Wsized_deallocation, "the program should also define %qD", sized); else if (!DECL_INITIAL (unsized) && DECL_INITIAL (sized)) warning_at (DECL_SOURCE_LOCATION (sized), OPT_Wsized_deallocation, "the program should also define %qD", unsized); } /* Check the global deallocation functions to see if we want to warn about defining unsized without sized (or vice versa). */ static void maybe_warn_sized_delete () { if (!flag_sized_deallocation || !warn_sized_deallocation) return; maybe_warn_sized_delete (DELETE_EXPR); maybe_warn_sized_delete (VEC_DELETE_EXPR); } /* This routine is called at the end of compilation. Its job is to create all the code needed to initialize and destroy the global aggregates. We do the destruction first, since that way we only need to reverse the decls once. */ void cp_write_global_declarations (void) { tree vars; bool reconsider; size_t i; location_t locus; unsigned ssdf_count = 0; int retries = 0; tree decl; hash_set<tree> *candidates; locus = input_location; at_eof = 1; /* Bad parse errors. Just forget about it. */ if (! global_bindings_p () || current_class_type || !vec_safe_is_empty (decl_namespace_list)) return; /* This is the point to write out a PCH if we're doing that. In that case we do not want to do anything else. */ if (pch_file) { c_common_write_pch (); dump_tu (); return; } symtab->process_same_body_aliases (); /* Handle -fdump-ada-spec[-slim] */ if (flag_dump_ada_spec || flag_dump_ada_spec_slim) { if (flag_dump_ada_spec_slim) collect_source_ref (main_input_filename); else collect_source_refs (global_namespace); dump_ada_specs (collect_all_refs, cpp_check); } /* FIXME - huh? was input_line -= 1;*/ timevar_start (TV_PHASE_DEFERRED); /* We now have to write out all the stuff we put off writing out. These include: o Template specializations that we have not yet instantiated, but which are needed. o Initialization and destruction for non-local objects with static storage duration. (Local objects with static storage duration are initialized when their scope is first entered, and are cleaned up via atexit.) o Virtual function tables. All of these may cause others to be needed. For example, instantiating one function may cause another to be needed, and generating the initializer for an object may cause templates to be instantiated, etc., etc. */ emit_support_tinfos (); do { tree t; tree decl; reconsider = false; /* If there are templates that we've put off instantiating, do them now. */ instantiate_pending_templates (retries); ggc_collect (); /* Write out virtual tables as required. Note that writing out the virtual table for a template class may cause the instantiation of members of that class. If we write out vtables then we remove the class from our list so we don't have to look at it again. */ while (keyed_classes != NULL_TREE && maybe_emit_vtables (TREE_VALUE (keyed_classes))) { reconsider = true; keyed_classes = TREE_CHAIN (keyed_classes); } t = keyed_classes; if (t != NULL_TREE) { tree next = TREE_CHAIN (t); while (next) { if (maybe_emit_vtables (TREE_VALUE (next))) { reconsider = true; TREE_CHAIN (t) = TREE_CHAIN (next); } else t = next; next = TREE_CHAIN (t); } } /* Write out needed type info variables. We have to be careful looping through unemitted decls, because emit_tinfo_decl may cause other variables to be needed. New elements will be appended, and we remove from the vector those that actually get emitted. */ for (i = unemitted_tinfo_decls->length (); unemitted_tinfo_decls->iterate (--i, &t);) if (emit_tinfo_decl (t)) { reconsider = true; unemitted_tinfo_decls->unordered_remove (i); } /* The list of objects with static storage duration is built up in reverse order. We clear STATIC_AGGREGATES so that any new aggregates added during the initialization of these will be initialized in the correct order when we next come around the loop. */ vars = prune_vars_needing_no_initialization (&static_aggregates); if (vars) { /* We need to start a new initialization function each time through the loop. That's because we need to know which vtables have been referenced, and TREE_SYMBOL_REFERENCED isn't computed until a function is finished, and written out. That's a deficiency in the back end. When this is fixed, these initialization functions could all become inline, with resulting performance improvements. */ tree ssdf_body; /* Set the line and file, so that it is obviously not from the source file. */ input_location = locus; ssdf_body = start_static_storage_duration_function (ssdf_count); /* Make sure the back end knows about all the variables. */ write_out_vars (vars); /* First generate code to do all the initializations. */ if (vars) do_static_initialization_or_destruction (vars, /*initp=*/true); /* Then, generate code to do all the destructions. Do these in reverse order so that the most recently constructed variable is the first destroyed. If we're using __cxa_atexit, then we don't need to do this; functions were registered at initialization time to destroy the local statics. */ if (!flag_use_cxa_atexit && vars) { vars = nreverse (vars); do_static_initialization_or_destruction (vars, /*initp=*/false); } else vars = NULL_TREE; /* Finish up the static storage duration function for this round. */ input_location = locus; finish_static_storage_duration_function (ssdf_body); /* All those initializations and finalizations might cause us to need more inline functions, more template instantiations, etc. */ reconsider = true; ssdf_count++; /* ??? was: locus.line++; */ } /* Now do the same for thread_local variables. */ handle_tls_init (); /* Go through the set of inline functions whose bodies have not been emitted yet. If out-of-line copies of these functions are required, emit them. */ FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl) { /* Does it need synthesizing? */ if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl) && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl))) { /* Even though we're already at the top-level, we push there again. That way, when we pop back a few lines hence, all of our state is restored. Otherwise, finish_function doesn't clean things up, and we end up with CURRENT_FUNCTION_DECL set. */ push_to_top_level (); /* The decl's location will mark where it was first needed. Save that so synthesize method can indicate where it was needed from, in case of error */ input_location = DECL_SOURCE_LOCATION (decl); synthesize_method (decl); pop_from_top_level (); reconsider = true; } if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl)) generate_tls_wrapper (decl); if (!DECL_SAVED_TREE (decl)) continue; /* We lie to the back end, pretending that some functions are not defined when they really are. This keeps these functions from being put out unnecessarily. But, we must stop lying when the functions are referenced, or if they are not comdat since they need to be put out now. If DECL_INTERFACE_KNOWN, then we have already set DECL_EXTERNAL appropriately, so there's no need to check again, and we do not want to clear DECL_EXTERNAL if a previous call to import_export_decl set it. This is done in a separate for cycle, because if some deferred function is contained in another deferred function later in deferred_fns varray, rest_of_compilation would skip this function and we really cannot expand the same function twice. */ import_export_decl (decl); if (DECL_NOT_REALLY_EXTERN (decl) && DECL_INITIAL (decl) && decl_needed_p (decl)) { struct cgraph_node *node, *next; node = cgraph_node::get (decl); if (node->cpp_implicit_alias) node = node->get_alias_target (); node->call_for_symbol_thunks_and_aliases (clear_decl_external, NULL, true); /* If we mark !DECL_EXTERNAL one of the symbols in some comdat group, we need to mark all symbols in the same comdat group that way. */ if (node->same_comdat_group) for (next = dyn_cast<cgraph_node *> (node->same_comdat_group); next != node; next = dyn_cast<cgraph_node *> (next->same_comdat_group)) next->call_for_symbol_thunks_and_aliases (clear_decl_external, NULL, true); } /* If we're going to need to write this function out, and there's already a body for it, create RTL for it now. (There might be no body if this is a method we haven't gotten around to synthesizing yet.) */ if (!DECL_EXTERNAL (decl) && decl_needed_p (decl) && !TREE_ASM_WRITTEN (decl) && !cgraph_node::get (decl)->definition) { /* We will output the function; no longer consider it in this loop. */ DECL_DEFER_OUTPUT (decl) = 0; /* Generate RTL for this function now that we know we need it. */ expand_or_defer_fn (decl); /* If we're compiling -fsyntax-only pretend that this function has been written out so that we don't try to expand it again. */ if (flag_syntax_only) TREE_ASM_WRITTEN (decl) = 1; reconsider = true; } } if (walk_namespaces (wrapup_globals_for_namespace, /*data=*/0)) reconsider = true; /* Static data members are just like namespace-scope globals. */ FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl) { if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl) /* Don't write it out if we haven't seen a definition. */ || DECL_IN_AGGR_P (decl)) continue; import_export_decl (decl); /* If this static data member is needed, provide it to the back end. */ if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl)) DECL_EXTERNAL (decl) = 0; } if (vec_safe_length (pending_statics) != 0 && wrapup_global_declarations (pending_statics->address (), pending_statics->length ())) reconsider = true; retries++; } while (reconsider); /* All used inline functions must have a definition at this point. */ FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl) { if (/* Check online inline functions that were actually used. */ DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl) /* If the definition actually was available here, then the fact that the function was not defined merely represents that for some reason (use of a template repository, #pragma interface, etc.) we decided not to emit the definition here. */ && !DECL_INITIAL (decl) /* Don't complain if the template was defined. */ && !(DECL_TEMPLATE_INSTANTIATION (decl) && DECL_INITIAL (DECL_TEMPLATE_RESULT (template_for_substitution (decl))))) { warning (0, "inline function %q+D used but never defined", decl); /* Avoid a duplicate warning from check_global_declaration_1. */ TREE_NO_WARNING (decl) = 1; } } /* So must decls that use a type with no linkage. */ FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl) no_linkage_error (decl); maybe_warn_sized_delete (); /* Then, do the Objective-C stuff. This is where all the Objective-C module stuff gets generated (symtab, class/protocol/selector lists etc). This must be done after C++ templates, destructors etc. so that selectors used in C++ templates are properly allocated. */ if (c_dialect_objc ()) objc_write_global_declarations (); /* We give C linkage to static constructors and destructors. */ push_lang_context (lang_name_c); /* Generate initialization and destruction functions for all priorities for which they are required. */ if (priority_info_map) splay_tree_foreach (priority_info_map, generate_ctor_and_dtor_functions_for_priority, /*data=*/&locus); else if (c_dialect_objc () && objc_static_init_needed_p ()) /* If this is obj-c++ and we need a static init, call generate_ctor_or_dtor_function. */ generate_ctor_or_dtor_function (/*constructor_p=*/true, DEFAULT_INIT_PRIORITY, &locus); /* We're done with the splay-tree now. */ if (priority_info_map) splay_tree_delete (priority_info_map); /* Generate any missing aliases. */ maybe_apply_pending_pragma_weaks (); /* We're done with static constructors, so we can go back to "C++" linkage now. */ pop_lang_context (); /* Collect candidates for Java hidden aliases. */ candidates = collect_candidates_for_java_method_aliases (); timevar_stop (TV_PHASE_DEFERRED); timevar_start (TV_PHASE_OPT_GEN); if (flag_vtable_verify) { vtv_recover_class_info (); vtv_compute_class_hierarchy_transitive_closure (); vtv_build_vtable_verify_fndecl (); } symtab->finalize_compilation_unit (); if (flag_vtable_verify) { /* Generate the special constructor initialization function that calls __VLTRegisterPairs, and give it a very high initialization priority. This must be done after finalize_compilation_unit so that we have accurate information about which vtable will actually be emitted. */ vtv_generate_init_routine (); } timevar_stop (TV_PHASE_OPT_GEN); timevar_start (TV_PHASE_CHECK_DBGINFO); /* Now, issue warnings about static, but not defined, functions, etc., and emit debugging information. */ walk_namespaces (wrapup_globals_for_namespace, /*data=*/&reconsider); if (vec_safe_length (pending_statics) != 0) { check_global_declarations (pending_statics->address (), pending_statics->length ()); emit_debug_global_declarations (pending_statics->address (), pending_statics->length ()); } perform_deferred_noexcept_checks (); /* Generate hidden aliases for Java. */ if (candidates) { build_java_method_aliases (candidates); delete candidates; } finish_repo (); /* The entire file is now complete. If requested, dump everything to a file. */ dump_tu (); if (flag_detailed_statistics) { dump_tree_statistics (); dump_time_statistics (); } input_location = locus; #ifdef ENABLE_CHECKING validate_conversion_obstack (); #endif /* ENABLE_CHECKING */ timevar_stop (TV_PHASE_CHECK_DBGINFO); } /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the function to call in parse-tree form; it has not yet been semantically analyzed. ARGS are the arguments to the function. They have already been semantically analyzed. This may change ARGS. */ tree build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args, tsubst_flags_t complain) { tree orig_fn; vec<tree, va_gc> *orig_args = NULL; tree expr; tree object; orig_fn = fn; object = TREE_OPERAND (fn, 0); if (processing_template_decl) { gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR || TREE_CODE (fn) == MEMBER_REF); if (type_dependent_expression_p (fn) || any_type_dependent_arguments_p (*args)) return build_nt_call_vec (fn, *args); orig_args = make_tree_vector_copy (*args); /* Transform the arguments and add the implicit "this" parameter. That must be done before the FN is transformed because we depend on the form of FN. */ make_args_non_dependent (*args); object = build_non_dependent_expr (object); if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE) { if (TREE_CODE (fn) == DOTSTAR_EXPR) object = cp_build_addr_expr (object, complain); vec_safe_insert (*args, 0, object); } /* Now that the arguments are done, transform FN. */ fn = build_non_dependent_expr (fn); } /* A qualified name corresponding to a bound pointer-to-member is represented as an OFFSET_REF: struct B { void g(); }; void (B::*p)(); void B::g() { (this->*p)(); } */ if (TREE_CODE (fn) == OFFSET_REF) { tree object_addr = cp_build_addr_expr (object, complain); fn = TREE_OPERAND (fn, 1); fn = get_member_function_from_ptrfunc (&object_addr, fn, complain); vec_safe_insert (*args, 0, object_addr); } if (CLASS_TYPE_P (TREE_TYPE (fn))) expr = build_op_call (fn, args, complain); else expr = cp_build_function_call_vec (fn, args, complain); if (processing_template_decl && expr != error_mark_node) expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args); if (orig_args != NULL) release_tree_vector (orig_args); return expr; } void check_default_args (tree x) { tree arg = TYPE_ARG_TYPES (TREE_TYPE (x)); bool saw_def = false; int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE); for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i) { if (TREE_PURPOSE (arg)) saw_def = true; else if (saw_def && !PACK_EXPANSION_P (TREE_VALUE (arg))) { error ("default argument missing for parameter %P of %q+#D", i, x); TREE_PURPOSE (arg) = error_mark_node; } } } /* Return true if function DECL can be inlined. This is used to force instantiation of methods that might be interesting for inlining. */ bool possibly_inlined_p (tree decl) { gcc_assert (TREE_CODE (decl) == FUNCTION_DECL); if (DECL_UNINLINABLE (decl)) return false; if (!optimize || pragma_java_exceptions) return DECL_DECLARED_INLINE_P (decl); /* When optimizing, we might inline everything when flatten attribute or heuristics inlining for size or autoinlining is used. */ return true; } /* Mark DECL (either a _DECL or a BASELINK) as "used" in the program. If DECL is a specialization or implicitly declared class member, generate the actual definition. Return false if something goes wrong, true otherwise. */ bool mark_used (tree decl, tsubst_flags_t complain) { /* If DECL is a BASELINK for a single function, then treat it just like the DECL for the function. Otherwise, if the BASELINK is for an overloaded function, we don't know which function was actually used until after overload resolution. */ if (BASELINK_P (decl)) { decl = BASELINK_FUNCTIONS (decl); if (really_overloaded_fn (decl)) return true; decl = OVL_CURRENT (decl); } /* Set TREE_USED for the benefit of -Wunused. */ TREE_USED (decl) = 1; if (DECL_CLONED_FUNCTION_P (decl)) TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1; /* Mark enumeration types as used. */ if (TREE_CODE (decl) == CONST_DECL) used_types_insert (DECL_CONTEXT (decl)); if (TREE_CODE (decl) == FUNCTION_DECL) maybe_instantiate_noexcept (decl); if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DELETED_FN (decl)) { if (DECL_ARTIFICIAL (decl)) { if (DECL_OVERLOADED_OPERATOR_P (decl) == TYPE_EXPR && LAMBDA_TYPE_P (DECL_CONTEXT (decl))) { /* We mark a lambda conversion op as deleted if we can't generate it properly; see maybe_add_lambda_conv_op. */ sorry ("converting lambda which uses %<...%> to " "function pointer"); return false; } } if (complain & tf_error) { error ("use of deleted function %qD", decl); if (!maybe_explain_implicit_delete (decl)) inform (DECL_SOURCE_LOCATION (decl), "declared here"); } return false; } if (TREE_DEPRECATED (decl) && (complain & tf_warning) && deprecated_state != DEPRECATED_SUPPRESS) warn_deprecated_use (decl, NULL_TREE); /* We can only check DECL_ODR_USED on variables or functions with DECL_LANG_SPECIFIC set, and these are also the only decls that we might need special handling for. */ if (!VAR_OR_FUNCTION_DECL_P (decl) || DECL_LANG_SPECIFIC (decl) == NULL || DECL_THUNK_P (decl)) { if (!processing_template_decl && type_uses_auto (TREE_TYPE (decl))) { if (complain & tf_error) error ("use of %qD before deduction of %<auto%>", decl); return false; } return true; } /* We only want to do this processing once. We don't need to keep trying to instantiate inline templates, because unit-at-a-time will make sure we get them compiled before functions that want to inline them. */ if (DECL_ODR_USED (decl)) return true; /* If within finish_function, defer the rest until that function finishes, otherwise it might recurse. */ if (defer_mark_used_calls) { vec_safe_push (deferred_mark_used_calls, decl); return true; } /* Normally, we can wait until instantiation-time to synthesize DECL. However, if DECL is a static data member initialized with a constant or a constexpr function, we need it right now because a reference to such a data member or a call to such function is not value-dependent. For a function that uses auto in the return type, we need to instantiate it to find out its type. For OpenMP user defined reductions, we need them instantiated for reduction clauses which inline them by hand directly. */ if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl) && (decl_maybe_constant_var_p (decl) || (TREE_CODE (decl) == FUNCTION_DECL && (DECL_DECLARED_CONSTEXPR_P (decl) || DECL_OMP_DECLARE_REDUCTION_P (decl))) || undeduced_auto_decl (decl)) && !uses_template_parms (DECL_TI_ARGS (decl))) { /* Instantiating a function will result in garbage collection. We must treat this situation as if we were within the body of a function so as to avoid collecting live data only referenced from the stack (such as overload resolution candidates). */ ++function_depth; instantiate_decl (decl, /*defer_ok=*/false, /*expl_inst_class_mem_p=*/false); --function_depth; } if (processing_template_decl || in_template_function ()) return true; /* Check this too in case we're within instantiate_non_dependent_expr. */ if (DECL_TEMPLATE_INFO (decl) && uses_template_parms (DECL_TI_ARGS (decl))) return true; if (undeduced_auto_decl (decl)) { if (complain & tf_error) error ("use of %qD before deduction of %<auto%>", decl); return false; } /* If we don't need a value, then we don't need to synthesize DECL. */ if (cp_unevaluated_operand != 0) return true; DECL_ODR_USED (decl) = 1; if (DECL_CLONED_FUNCTION_P (decl)) DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1; /* DR 757: A type without linkage shall not be used as the type of a variable or function with linkage, unless o the variable or function has extern "C" linkage (7.5 [dcl.link]), or o the variable or function is not used (3.2 [basic.def.odr]) or is defined in the same translation unit. */ if (cxx_dialect > cxx98 && decl_linkage (decl) != lk_none && !DECL_EXTERN_C_P (decl) && !DECL_ARTIFICIAL (decl) && !decl_defined_p (decl) && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false)) { if (is_local_extern (decl)) /* There's no way to define a local extern, and adding it to the vector interferes with GC, so give an error now. */ no_linkage_error (decl); else vec_safe_push (no_linkage_decls, decl); } if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl) && !DECL_INITIAL (decl) && !DECL_ARTIFICIAL (decl)) /* Remember it, so we can check it was defined. */ note_vague_linkage_fn (decl); /* Is it a synthesized method that needs to be synthesized? */ if (TREE_CODE (decl) == FUNCTION_DECL && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl) && DECL_DEFAULTED_FN (decl) /* A function defaulted outside the class is synthesized either by cp_finish_decl or instantiate_decl. */ && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl) && ! DECL_INITIAL (decl)) { /* Defer virtual destructors so that thunks get the right linkage. */ if (DECL_VIRTUAL_P (decl) && !at_eof) { note_vague_linkage_fn (decl); return true; } /* Remember the current location for a function we will end up synthesizing. Then we can inform the user where it was required in the case of error. */ DECL_SOURCE_LOCATION (decl) = input_location; /* Synthesizing an implicitly defined member function will result in garbage collection. We must treat this situation as if we were within the body of a function so as to avoid collecting live data on the stack (such as overload resolution candidates). We could just let cp_write_global_declarations handle synthesizing this function by adding it to deferred_fns, but doing it at the use site produces better error messages. */ ++function_depth; synthesize_method (decl); --function_depth; /* If this is a synthesized method we don't need to do the instantiation test below. */ } else if (VAR_OR_FUNCTION_DECL_P (decl) && DECL_TEMPLATE_INFO (decl) && (!DECL_EXPLICIT_INSTANTIATION (decl) || always_instantiate_p (decl))) /* If this is a function or variable that is an instance of some template, we now know that we will need to actually do the instantiation. We check that DECL is not an explicit instantiation because that is not checked in instantiate_decl. We put off instantiating functions in order to improve compile times. Maintaining a stack of active functions is expensive, and the inliner knows to instantiate any functions it might need. Therefore, we always try to defer instantiation. */ { ++function_depth; instantiate_decl (decl, /*defer_ok=*/true, /*expl_inst_class_mem_p=*/false); --function_depth; } return true; } bool mark_used (tree decl) { return mark_used (decl, tf_warning_or_error); } tree vtv_start_verification_constructor_init_function (void) { return start_objects ('I', MAX_RESERVED_INIT_PRIORITY - 1); } tree vtv_finish_verification_constructor_init_function (tree function_body) { tree fn; finish_compound_stmt (function_body); fn = finish_function (0); DECL_STATIC_CONSTRUCTOR (fn) = 1; decl_init_priority_insert (fn, MAX_RESERVED_INIT_PRIORITY - 1); return fn; } #include "gt-cp-decl2.h"
openmp_yield.c
#include <omp.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #define NUM_TASKS 1000 #define VERBOSE static volatile int flag_one_cntr = 0; static volatile int flag_two_cntr = 0; int main(int argc, char **argv) { #pragma omp parallel #pragma omp master for (int i = 0; i < NUM_TASKS+omp_get_num_threads()-1; ++i) { #pragma omp task untied firstprivate(i) { if (omp_get_thread_num() > 0) { // trap all but thread 0 printf("Trapping thread %d\n", omp_get_thread_num()); while(flag_two_cntr != NUM_TASKS) { } printf("Un-Trapping thread %d\n", omp_get_thread_num()); } else { int task_id = ++flag_one_cntr; #pragma omp taskyield // when we come back we first check the counter if (task_id == 1) { if (task_id == flag_one_cntr) { printf("NOOP\n"); } // some other tasks were running in between else if (flag_two_cntr == (NUM_TASKS - 1)) { printf("STACK (unlimited)\n"); } else if (flag_two_cntr == flag_one_cntr-1) { printf("STACK(depth=%d)\n", flag_one_cntr); } else if (flag_one_cntr == (NUM_TASKS) /*&& flag_two_cntr == 0*/) { printf("CYCLIC\n"); } else if (flag_one_cntr > 0 /*&& flag_two_cntr == 0*/) { printf("N-CYCLIC (N=%d)\n", flag_one_cntr); } else { printf("UNKNOWN: flag_one_cntr: %d, flag_two_cntr: %d\n", flag_one_cntr, flag_two_cntr); } } // quirk for Cray compiler (void)flag_two_cntr; #pragma omp taskyield ++flag_two_cntr; } // thread-trap } // pragma omp task } // for() return 0; }
omp_threadprivate.c
// RUN: %libomp-compile-and-run // REQUIRES: !(abt && (clang || gcc)) /* * Threadprivate is tested in 2 ways: * 1. The global variable declared as threadprivate should have * local copy for each thread. Otherwise race condition and * wrong result. * 2. If the value of local copy is retained for the two adjacent * parallel regions */ #include "omp_testsuite.h" #include <stdlib.h> #include <stdio.h> static int sum0=0; static int myvalue = 0; #pragma omp threadprivate(sum0) #pragma omp threadprivate(myvalue) int test_omp_threadprivate() { int sum = 0; int known_sum; int i; int iter; int *data; int size; int num_failed = 0; int my_random; omp_set_dynamic(0); #pragma omp parallel private(i) { sum0 = 0; #pragma omp for for (i = 1; i <= LOOPCOUNT; i++) { sum0 = sum0 + i; } /*end of for*/ #pragma omp critical { sum = sum + sum0; } /*end of critical */ } /* end of parallel */ known_sum = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; if (known_sum != sum ) { fprintf (stderr, " known_sum = %d, sum = %d\n", known_sum, sum); } /* the next parallel region is just used to get the number of threads*/ omp_set_dynamic(0); #pragma omp parallel { #pragma omp master { size=omp_get_num_threads(); data=(int*) malloc(size*sizeof(int)); } }/* end parallel*/ srand(45); for (iter = 0; iter < 100; iter++) { my_random = rand(); /* random number generator is called inside serial region*/ /* the first parallel region is used to initialize myvalue and the array with my_random+rank */ #pragma omp parallel { int rank; rank = omp_get_thread_num (); myvalue = data[rank] = my_random + rank; } /* the second parallel region verifies that the value of "myvalue" is retained */ #pragma omp parallel reduction(+:num_failed) { int rank; rank = omp_get_thread_num (); num_failed = num_failed + (myvalue != data[rank]); if(myvalue != data[rank]) { fprintf (stderr, " myvalue = %d, data[rank]= %d\n", myvalue, data[rank]); } } } free (data); return (known_sum == sum) && !num_failed; } /* end of check_threadprivate*/ int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_threadprivate()) { num_failed++; } } return num_failed; }
GB_binop__isne_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isne_int32) // A.*B function (eWiseMult): GB (_AemultB_08__isne_int32) // A.*B function (eWiseMult): GB (_AemultB_02__isne_int32) // A.*B function (eWiseMult): GB (_AemultB_04__isne_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isne_int32) // A*D function (colscale): GB (_AxD__isne_int32) // D*A function (rowscale): GB (_DxB__isne_int32) // C+=B function (dense accum): GB (_Cdense_accumB__isne_int32) // C+=b function (dense accum): GB (_Cdense_accumb__isne_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isne_int32) // C=scalar+B GB (_bind1st__isne_int32) // C=scalar+B' GB (_bind1st_tran__isne_int32) // C=A+scalar GB (_bind2nd__isne_int32) // C=A'+scalar GB (_bind2nd_tran__isne_int32) // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x != y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISNE || GxB_NO_INT32 || GxB_NO_ISNE_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__isne_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isne_int32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isne_int32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isne_int32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isne_int32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isne_int32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isne_int32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isne_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__isne_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isne_int32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isne_int32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int32_t bij = GBX (Bx, p, false) ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isne_int32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = GBX (Ax, p, false) ; Cx [p] = (aij != y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__isne_int32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__isne_int32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_concat_hyper.c
//------------------------------------------------------------------------------ // GB_concat_hyper: concatenate an array of matrices into a hypersparse matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #define GB_FREE_ALL \ { \ GB_FREE (&Wi, Wi_size) ; \ GB_FREE_WORK (&Wj, Wj_size) ; \ GB_FREE_WORK (&Wx, Wx_size) ; \ GB_phbix_free (C) ; \ } #include "GB_concat.h" GrB_Info GB_concat_hyper // concatenate into a hypersparse matrix ( GrB_Matrix C, // input/output matrix for results const bool C_iso, // if true, construct C as iso const GB_void *cscalar, // iso value of C, if C is iso const int64_t cnz, // # of entries in C const GrB_Matrix *Tiles, // 2D row-major array of size m-by-n, const GrB_Index m, const GrB_Index n, const int64_t *restrict Tile_rows, // size m+1 const int64_t *restrict Tile_cols, // size n+1 GB_Context Context ) { //-------------------------------------------------------------------------- // allocate triplet workspace to construct C as hypersparse //-------------------------------------------------------------------------- GrB_Info info ; GrB_Matrix A = NULL ; ASSERT_MATRIX_OK (C, "C input to concat hyper", GB0) ; int64_t *restrict Wi = NULL ; size_t Wi_size = 0 ; int64_t *restrict Wj = NULL ; size_t Wj_size = 0 ; GB_void *restrict Wx = NULL ; size_t Wx_size = 0 ; GrB_Type ctype = C->type ; int64_t cvlen = C->vlen ; int64_t cvdim = C->vdim ; bool csc = C->is_csc ; size_t csize = ctype->size ; GB_Type_code ccode = ctype->code ; float hyper_switch = C->hyper_switch ; float bitmap_switch = C->bitmap_switch ; int sparsity_control = C->sparsity_control ; bool static_header = C->static_header ; GB_phbix_free (C) ; Wi = GB_MALLOC (cnz, int64_t, &Wi_size) ; // becomes C->i Wj = GB_MALLOC_WORK (cnz, int64_t, &Wj_size) ; // freed below if (!C_iso) { Wx = GB_MALLOC_WORK (cnz * csize, GB_void, &Wx_size) ; // freed below } if (Wi == NULL || Wj == NULL || (!C_iso && Wx == NULL)) { // out of memory GB_FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int64_t nouter = csc ? n : m ; int64_t ninner = csc ? m : n ; //-------------------------------------------------------------------------- // concatenate all matrices into the list of triplets //-------------------------------------------------------------------------- int64_t pC = 0 ; for (int64_t outer = 0 ; outer < nouter ; outer++) { for (int64_t inner = 0 ; inner < ninner ; inner++) { //------------------------------------------------------------------ // get the tile A //------------------------------------------------------------------ A = csc ? GB_TILE (Tiles, inner, outer) : GB_TILE (Tiles, outer, inner) ; ASSERT (!GB_ANY_PENDING_WORK (A)) ; //------------------------------------------------------------------ // determine where to place the tile in C //------------------------------------------------------------------ // The tile A appears in vectors cvstart:cvend-1 of C, and indices // cistart:ciend-1. int64_t cvstart, cistart ; if (csc) { // C is held by column // Tiles is row-major and accessed in column order cvstart = Tile_cols [outer] ; cistart = Tile_rows [inner] ; } else { // C is held by row // Tiles is row-major and accessed in row order cvstart = Tile_rows [outer] ; cistart = Tile_cols [inner] ; } //------------------------------------------------------------------ // extract the tuples from tile A //------------------------------------------------------------------ // if A is iso but C is not, extractTuples expands A->x [0] into // all Wx [...]. If both A and C are iso, then all tiles are iso, // and Wx is not extracted. int64_t anz = GB_nnz (A) ; GB_OK (GB_extractTuples ( (GrB_Index *) ((csc ? Wi : Wj) + pC), (GrB_Index *) ((csc ? Wj : Wi) + pC), (C_iso) ? NULL : (Wx + pC * csize), (GrB_Index *) (&anz), ccode, A, Context)) ; //------------------------------------------------------------------ // adjust the indices to reflect their new place in C //------------------------------------------------------------------ int nth = GB_nthreads (anz, chunk, nthreads_max) ; if (cistart > 0 && cvstart > 0) { int64_t pA ; #pragma omp parallel for num_threads(nth) schedule(static) for (pA = 0 ; pA < anz ; pA++) { Wi [pC + pA] += cistart ; Wj [pC + pA] += cvstart ; } } else if (cistart > 0) { int64_t pA ; #pragma omp parallel for num_threads(nth) schedule(static) for (pA = 0 ; pA < anz ; pA++) { Wi [pC + pA] += cistart ; } } else if (cvstart > 0) { int64_t pA ; #pragma omp parallel for num_threads(nth) schedule(static) for (pA = 0 ; pA < anz ; pA++) { Wj [pC + pA] += cvstart ; } } //------------------------------------------------------------------ // advance the tuple counter //------------------------------------------------------------------ pC += anz ; } } //-------------------------------------------------------------------------- // build C from the triplets //-------------------------------------------------------------------------- const GB_void *S_input = NULL ; if (C_iso) { S_input = cscalar ; } GB_OK (GB_builder ( C, // create C using a static or dynamic header ctype, // C->type cvlen, // C->vlen cvdim, // C->vdim csc, // C->is_csc (int64_t **) &Wi, // Wi is C->i on output, or freed on error &Wi_size, (int64_t **) &Wj, // Wj, free on output &Wj_size, (GB_void **) &Wx, // Wx, free on output; or NULL if C is iso &Wx_size, false, // tuples need to be sorted true, // no duplicates cnz, // size of Wi and Wj in # of tuples true, // is_matrix: unused NULL, NULL, // original I,J tuples S_input, // cscalar if C is iso, or NULL C_iso, // true if C is iso cnz, // # of tuples NULL, // no duplicates, so dup is NUL ctype, // the type of Wx (no typecasting) Context )) ; C->hyper_switch = hyper_switch ; C->bitmap_switch = bitmap_switch ; C->sparsity_control = sparsity_control ; ASSERT (C->static_header == static_header) ; ASSERT (GB_IS_HYPERSPARSE (C)) ; ASSERT_MATRIX_OK (C, "C from concat hyper", GB0) ; // workspace has been freed by GB_builder, or transplanted into C ASSERT (Wi == NULL) ; ASSERT (Wj == NULL) ; ASSERT (Wx == NULL) ; return (GrB_SUCCESS) ; }
test6.c
int g1; void foo () { g1=0; #pragma omp barrier 1+g1; } int main() { #pragma omp parallel { int p; g1=2; if (3) { p=4; g1 = 10; foo (); 5+g1; } else { p=6+g1; //#pragma omp atomic read // p = g1; #pragma omp barrier g1=7; } if (8) { 9=g1; foo(); g1=10+g1; } else { 11+g1; #pragma omp barrier 12=g1; } g1; 13; } }
drhook.c
/** * (C) Copyright 2014- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #define _DRHOOK_C_ 1 #define _GNU_SOURCE /* drhook.c Author: Sami Saarinen, ECMWF, 14..24-Nov-2003 Thanks to Bob Walkup & John Hague for IBM Power4 version Thanks to Bob Carruthers for Cray X1 (SV2), XD1 and XT3 versions, as well as David Tanqueray for the flop routines Also thanks to Roland Richter for suggesting the use of "call tracebackqq()" function. In our environment this is accomplished by calling fortran routine intel_trbk() from ifsaux/utilities/gentrbk.F90. */ /* If intending to run on IBM P4+ or newer systems the following definition should be activated to use pm_initialize() instead of pm_init() of PMAPI-lib ($LIBHPM) #define PMAPI_POST_P4 */ /* If *ALSO* intending to run on IBM P5+ systems, then set also BOTH #define PMAPI_POST_P4 #define PMAPI_P5_PLUS */ /* Thanks to John Hague (IBM) If intending to run on IBM p6 systems, then set also BOTH #define PMAPI_POST_P4 #define PMAPI_P6 */ #if defined(PMAPI_P7) #define ENTRY_4 5 #define ENTRY_6 4 #elif defined(PMAPI_P6) #define ENTRY_4 5 #define ENTRY_6 4 #elif defined(PMAPI_P5_PLUS) #define ENTRY_4 5 #define ENTRY_6 4 #else #define ENTRY_4 4 #define ENTRY_6 6 #endif #if defined(SV2) || defined(XD1) || defined(XT3) #define DT_FLOP #define HPM #define MAX_COUNTERS 6 #endif #ifdef RS6K #pragma options opt=3 halt=e #include <pthread.h> #endif #include <unistd.h> #if defined(DARWIN) #include <pthread.h> #endif #define EC_HOST_NAME_MAX 512 /* === This doesn't handle recursive calls correctly (yet) === */ #include "drhook.h" #include "cas.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifdef __USE_GNU #include <dlfcn.h> #endif static void set_timed_kill(); static void process_options(); static char *TimeStr(char *s, int slen); int drhook_memtrace = 0; /* set to 1, if opt_memprof or opt_timeline ; used in getcurheap.c to lock stuff */ #if !defined(CACHELINESIZE) #if defined(LEVEL1_DCACHE_LINESIZE) #define CACHELINESIZE LEVEL1_DCACHE_LINESIZE #else /* ***Note: A hardcoded cache line size in bytes !!! */ #ifdef RS6K #define CACHELINESIZE 128 #else #define CACHELINESIZE 64 #endif #endif #endif #include "crc.h" #include <time.h> static char *start_stamp = NULL; static char *end_stamp = NULL; static int numthreads = 0; static int myproc = 1; static int nproc = -1; static int max_threads = 1; extern int get_thread_id_(); typedef struct drhook_prefix_t { char s[3840]; char timestr[256]; int nsigs; } drhook_prefix_t; static drhook_prefix_t *ec_drhook = NULL; static int timestr_len = 0; #define PREFIX(tid) (ec_drhook && tid >= 1 && tid <= numthreads) ? ec_drhook[tid-1].s : "" #define TIDNSIGS(tid) (ec_drhook && tid >= 1 && tid <= numthreads) ? ec_drhook[tid-1].nsigs : -1 #define TIMESTR(tid) (timestr_len > 0 && ec_drhook && tid >= 1 && tid <= numthreads) ? TimeStr(ec_drhook[tid-1].timestr,timestr_len) : "" #define FFL __FUNCTION__,__FILE__,__LINE__ static int drhook_trapfpe_master_init = 0; static int drhook_trapfpe = 1; static int drhook_trapfpe_invalid = 1; static int drhook_trapfpe_divbyzero = 1; static int drhook_trapfpe_overflow = 1; #if defined(NECSX) #pragma cdir options -Nv -Csopt extern void necsx_trbk_(const char *msg, int msglen); /* from ../utilities/gentrbk.F90 */ #endif #if defined(LINUX) && !defined(XT3) && !defined(XD1) && !defined(CYGWIN) #if defined(__GNUC__) && !defined(NO_TRAPFPE) #if defined(CYGWIN) #include <mingw/fenv.h> #else #include <fenv.h> #endif extern int feenableexcept(int excepts); extern int fedisableexcept(int excepts); extern int fegetexcept(void); #if defined(DARWIN) /* A temporary fix to link on MacIntosh. Something more clever will be done later -REK. */ int feenableexcept (int excepts) { return 0; } int fedisableexcept(int excepts) { return 0; } int fegetexcept(void) { return 0; } #endif #if defined(__NEC__) int fegetexcept(void) { return 0; } #endif static void trapfpe(int silent) { /* Enable some exceptions. At startup all exceptions are masked. */ #if 1 /* New coding -- honours DR_HOOK_TRAPFPE_{INVALID,DIVBYZERO,OVERLOW} set to 1 (or 0) */ int tid = get_thread_id_(); int enable = 0; int disable = 0; int dummy; int rc_enable = 0; int rc_disable = 0; int excepts_before, excepts_after; dummy = drhook_trapfpe_invalid ? (enable |= FE_INVALID) : (disable |= FE_INVALID); dummy = drhook_trapfpe_divbyzero ? (enable |= FE_DIVBYZERO) : (disable |= FE_DIVBYZERO); dummy = drhook_trapfpe_overflow ? (enable |= FE_OVERFLOW) : (disable |= FE_OVERFLOW); if (!silent && myproc == 1) { excepts_before = fegetexcept(); } if (enable) rc_enable = feenableexcept(enable); // Turn ON these if (disable) rc_disable = fedisableexcept(disable); // Turn OFF these if (!silent && myproc == 1) { char *pfx = PREFIX(tid); excepts_after = fegetexcept(); fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK trapfpe() : Exceptions before = 0x%x [%d] -- after = 0x%x [%d]\n", pfx,TIMESTR(tid),FFL, excepts_before, excepts_before, excepts_after, excepts_after); fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK trapfpe() : with FE_INVALID = 0x%x [%d] -- FE_DIVBYZERO = 0x%x [%d] -- FE_OVERFLOW = 0x%x [%d]\n", pfx,TIMESTR(tid),FFL, (int)FE_INVALID, (int)FE_INVALID, (int)FE_DIVBYZERO, (int)FE_DIVBYZERO, (int)FE_OVERFLOW, (int)FE_OVERFLOW); if (enable) { fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK trapfpe() : feenableexcept(0x%x [%d]) returns rc=%d\n", pfx,TIMESTR(tid),FFL, enable,enable,rc_enable); } if (disable) { fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK trapfpe() : fedisableexcept(0x%x [%d]) returns rc=%d\n", pfx,TIMESTR(tid),FFL, disable,disable,rc_disable); } if (tid == 1) drhook_trapfpe_master_init = 1; // go-ahead for slave threads in trapfpe_slave_threads() } #else #if defined(PARKIND1_SINGLE) && !defined(SGEMM) /* For now ... we have issues in SGEMM with IEEE-invalid ... especially with LIBSCI from Cray */ int rc = feenableexcept(FE_DIVBYZERO|FE_OVERFLOW); #else int rc = feenableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW); #endif #endif } static void untrapfpe(int silent) { /* Disable some exceptions. At startup all exceptions are masked. */ int rc = fedisableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW); } #endif /* defined(__GNUC__) */ #endif /* defined(LINUX) && !defined(XT3) && !defined(XD1) */ #if (!defined(LINUX) || defined(CYGWIN) || defined(NO_TRAPFPE)) && defined(__GNUC__) /* For example Solaris with gcc */ #define trapfpe(x) #define untrapfpe(x) #endif #ifndef drhook_harakiri_timeout_default #define drhook_harakiri_timeout_default 500 #endif static int drhook_harakiri_timeout = drhook_harakiri_timeout_default; static int drhook_use_lockfile = 1; static int atp_enabled = 0; /* Cray ATP specific */ static int atp_max_cores = 20; /* Cray ATP specific */ static int atp_max_analysis_time = 300; /* Cray ATP specific */ static int atp_ignore_sigterm = 0; /* Cray ATP specific */ static int any_memstat = 0; static int opt_gethwm = 0; static int opt_getstk = 0; static int opt_getrss = 0; static int opt_getpag = 0; static int opt_walltime = 0; static int opt_cputime = 0; static int opt_wallprof = 0; static int opt_cpuprof = 0; static int opt_hpmprof = 0; static int opt_memprof = 0; static int opt_trim = 0; static int opt_calls = 0; static int opt_self = 1; /* 0=exclude drhook altogether, 1=include, but don't print, 2=also print */ static int opt_propagate_signals = 1; static int opt_sizeinfo = 1; static int opt_clusterinfo = 0; static int opt_callpath = 0; #define callpath_indent_default 2 static int callpath_indent = callpath_indent_default; #define callpath_depth_default 50 static int callpath_depth = callpath_depth_default; static int callpath_packed = 0; static int opt_calltrace = 0; static int opt_funcenter = 0; static int opt_funcexit = 0; static int opt_timeline = 0; /* myproc or -1 [or 0 for --> timeline feature off (default)] */ static int opt_timeline_thread = 1; /* thread-id control : <= 0 print for all threads 1 -> #1 only [but curheap still SUM of all threads] (default), n -> print for increasing number of threads separately : [1..n] */ static int opt_timeline_format = 1; /* if 1, print only {wall,hwm,rss,curheap} w/o labels "wall=" etc.; else fully expanded fmt */ static int opt_timeline_unitno = 6; /* Fortran unit number : default = 6 i.e. stdout */ static long long int opt_timeline_freq = 1000000; /* How often to print : every n-th call : default = every 10^6 th call or ... */ static double opt_timeline_MB = 1.0; /* ... rss or curheap jumps up/down by more than this many MBytes (default = 1) : unit MBytes */ static volatile sig_atomic_t opt_gencore = 0; static int opt_gencore_signal = 0; static int hpm_grp = 0; static int opt_random_memstat = 0; /* > 0 if to obtain random memory stats (maxhwm, maxstk) for tid=1. Updated when rand() % opt_random_memstat == 0 */ static double opt_trace_stack = 0; /* if > 0, a multiplier for OMP_STACKSIZE to monitor high master thread stack usage -- -- implies opt_random_memstat = 1 (regardless of DR_HOOK_RANDOM_MEMSTAT setting) -- for master MPI task only (for the moment) */ static long long int drhook_omp_stacksize = 0; /* Slave stack size -- an indicative stack size even master thread should not exceed */ static long long int drhook_stacksize_threshold = 0; static long long int slave_stacksize(); /* Begin of developer options */ static char *drhook_timed_kill = NULL; /* Timer assisted simulated kill of procs/threads by signal */ static int drhook_dump_maps = 0; /* Print /proc/<tid>/maps from signal handler (before moving to ATP or below) */ static int drhook_dump_smaps = 0; /* Print /proc/<tid>/smaps from signal handler (before moving to ATP or below) */ static int drhook_dump_buddyinfo = 0; /* Print /proc/buddyinfo from signal handler (before moving to ATP or below) */ static int drhook_dump_meminfo = 0; /* Print /proc/meminfo from signal handler (before moving to ATP or below) */ static int drhook_dump_hugepages = 0; static double drhook_dump_hugepages_freq = 0; /* End of developer options */ typedef struct drhook_timeline_t { unsigned long long int calls[2]; /* 0=drhook_begin , 1=drhook_end */ double last_curheap_MB; double last_rss_MB; double last_stack_MB; double last_vmpeak_MB; //#if CACHELINESIZE > (2*sizeof(unsigned long long int) + 4*sizeof(double)) -- disallowed #if CACHELINESIZE > (2*8 + 4*8) char pad[CACHELINESIZE - (2*sizeof(unsigned long long int) + 4*sizeof(double))]; /* padding : e.g. 64 bytes - 6*8 bytes */ #endif } drhook_timeline_t; /* cachelinesize optimized --> less false sharing when running with OpenMP */ static drhook_timeline_t *timeline = NULL; /* HPM-specific */ static long long int opt_hpmstop_threshold = -1; static double opt_hpmstop_mflops = 1000000.0; /* Yes, 1 PetaFlop/s !! */ #define DRHOOK_STRBUF 1000 #ifndef SA_SIGINFO #define SA_SIGINFO 0 #define SIG_EXTRA_ARGS /* empty */ #define SIG_PASS_EXTRA_ARGS /* empty */ #else #define SIG_EXTRA_ARGS , siginfo_t *sigcode, void *sigcontextptr #define SIG_PASS_EXTRA_ARGS , sigcode, sigcontextptr #endif #define NIL "(nil)" #undef MIN #define MIN(a,b) ( (a) < (b) ? (a) : (b) ) #undef MAX #define MAX(a,b) ( (a) > (b) ? (a) : (b) ) #undef ABS #define ABS(x) ( (x) >= 0 ? (x) : -(x) ) #define strequ(s1,s2) ((void *)s1 && (void *)s2 && strcmp(s1,s2) == 0) #define strnequ(s1,s2,n) ((void *)s1 && (void *)s2 && memcmp(s1,s2,n) == 0) extern long long int getstk_(); extern long long int getmaxstk_(); extern long long int gethwm_(); extern long long int getmaxhwm_(); extern long long int getrss_(); extern long long int getmaxrss_(); extern long long int getcurheap_(); extern long long int getmaxcurheap_(); extern long long int getcurheap_thread_(const int *tidnum); /* *tidnum >= 1 && <= max_threads */ extern long long int getmaxcurheap_thread_(const int *tidnum); /* *tidnum >= 1 && <= max_threads */ extern long long int getpag_(); extern long long int getvmpeak_(); extern void ec_set_umask_(); #if defined(DT_FLOP) extern double flop_(); #endif extern double util_cputime_(); extern double util_walltime_(); #ifdef RS6K static long long int irtc_start = 0; extern long long int irtc(); #define WALLTIME() ((double)(irtc() - irtc_start)*1.0e-9) #define CPUTIME() util_cputime_() #elif defined(CRAYXT) /* Cray XT3/XT4 with catamount microkernel */ #include <catamount/dclock.h> static double dclock_start = 0; #define WALLTIME() (dclock() - dclock_start) #define CPUTIME() WALLTIME() #else #if defined(SV2) #include <intrinsics.h> #endif #if defined(XD1) || defined(XT3) extern long long int irtc_(); /* integer*8 irtc() */ extern long long int irtc_rate_(); /* integer*8 irtc_rate() */ #endif #if defined(SV2) || defined(XD1) || defined(XT3) static long long int irtc_start = 0; static double my_irtc_rate = 0; static double my_inv_irtc_rate = 0; #if defined(SV2) #define WALLTIME() ((double)(_rtc() - irtc_start)*my_inv_irtc_rate) #else #define WALLTIME() ((double)(irtc_() - irtc_start)*my_inv_irtc_rate) #endif #define CPUTIME() util_cputime_() #else #define WALLTIME() util_walltime_() #define CPUTIME() util_cputime_() #endif #endif /* #define RAISE(x) { int tmp = x; c_drhook_raise_(&tmp); } */ #include "raise.h" #include "cargs.h" extern void LinuxTraceBack(const char *prefix, const char *timestr, void *sigcontextptr); /*** typedefs ***/ typedef union { struct drhook_key_t *keyptr; double d; unsigned long long int ull; } equivalence_t; typedef struct drhook_key_t { char *name; unsigned short name_len; const equivalence_t *callpath; /* parent's tree down to callpath_depth */ int callpath_len; unsigned int callpath_fullhash; unsigned short status; /* 0=inactive, >1 active */ unsigned long long int calls; long long int hwm, maxrss, rssnow, stack, maxstack, paging; double wall_in, delta_wall_all, delta_wall_child; double cpu_in, delta_cpu_all, delta_cpu_child; #ifdef HPM unsigned char hpm_stopped, counter_stopped; double this_delta_wall_child; double avg_mipsrate, avg_mflops; unsigned long long int hpm_calls; double mip_count_in, mflop_count_in; long long int *counter_in, *counter_sum; #endif char *filename; /* the filename where the 1st call (on this routine-name) to dr_hook() occurred */ long long int sizeinfo; /* # of data elements, bytes, etc. */ long long int min_sizeinfo, max_sizeinfo; /* min & max of # of data elements, bytes, etc. */ /* memprof specific */ long long int mem_seenmax; long long int mem_child, mem_curdelta; long long int maxmem_selfdelta, maxmem_alldelta; long long int mem_maxhwm, mem_maxrss, mem_maxstk, mem_maxpagdelta; long long int paging_in; unsigned long long int alloc_count, free_count; struct drhook_key_t *next; } drhook_key_t; typedef struct drhook_calltree_t { int active; drhook_key_t *keyptr; struct drhook_calltree_t *next; struct drhook_calltree_t *prev; } drhook_calltree_t; typedef struct drhook_sig_t { char name[32]; struct sigaction new; struct sigaction old; int active; int ignore_atexit; } drhook_sig_t; typedef union { void (*func1args)(int sig); void (*func3args)(int sig SIG_EXTRA_ARGS); } drhook_sigfunc_t; typedef struct drhook_prof_t { double pc; double total; double self; unsigned long long int calls; double percall_ms_self; double percall_ms_total; double mipsrate, mflops, divpc; int index; int tid; int cluster; double *maxval; unsigned char is_max; char *name; char *filename; long long int sizeinfo; long long int min_sizeinfo, max_sizeinfo; double sizespeed, sizeavg; const equivalence_t *callpath; /* parent's tree down to callpath_depth */ int callpath_len; } drhook_prof_t; typedef struct drhook_memprof_t { double pc; long long int self; long long int children; long long int hwm, rss, stk, pag, leaked; unsigned long long int calls, alloc_count, free_count; int index; int tid; int cluster; long long int *maxval; unsigned char is_max; char *name; char *filename; const equivalence_t *callpath; /* parent's tree down to callpath_depth */ int callpath_len; } drhook_memprof_t; #define MAX_WATCH_FIRST_NBYTES 8 typedef struct drhook_watch_t { char *name; int tid; int active; int abort_if_changed; const char *ptr; int nbytes; int watch_first_nbytes; char first_nbytes[MAX_WATCH_FIRST_NBYTES]; unsigned int crc32; int printkey; int nvals; struct drhook_watch_t *next; } drhook_watch_t; /*** static (local) variables ***/ static o_lock_t DRHOOK_lock = 0; static pid_t pid = -1; static drhook_key_t **keydata = NULL; static drhook_calltree_t **calltree = NULL; static drhook_calltree_t **thiscall = NULL; static int signals_set = 0; static volatile sig_atomic_t signal_handler_called = 0; static volatile sig_atomic_t signal_handler_ignore_atexit = 0; static volatile sig_atomic_t unlimited_corefile_retcode = 9999; static volatile unsigned long long int saved_corefile_hardlimit = 0; static int allow_coredump = -1; /* -1 denotes ALL MPI-tasks, 1..NPES == myproc, 0 = coredump will not be enabled by DrHook at init */ static drhook_sig_t siglist[1+NSIG] = { 0 }; static char *a_out = NULL; static char *mon_out = NULL; static int mon_out_procs = -1; static double percent_limit = -10; /* Lowest percentage accepted into the printouts */ static drhook_key_t **keyself = NULL; /* pointers to itself (per thread) */ static double *overhead; /* Total Dr.Hook-overhead for every thread in either WALL or CPU secs */ static drhook_key_t **curkeyptr = NULL; /* pointers to current keyptr (per thread) */ static drhook_watch_t *watch = NULL; static drhook_watch_t *last_watch = NULL; static int watch_count = 0; /* No. of *active* watch points */ #ifndef SYS_gettid #define SYS_gettid __NR_gettid #endif /* In GLIBC >= 2.30 the gettid function is declared in unistd.h so we call it my_gettid here */ static pid_t my_gettid() { #if defined(DARWIN) uint64_t tid64; pthread_threadid_np(NULL, &tid64); pid_t tid = (pid_t)tid64; #else pid_t tid = syscall(SYS_gettid); #endif return tid; } // Fortran callable : CALL GETTID_C(ITID) where INTEGER(KIND=4) :: ITID void gettid_c_(int *tid) { if (tid) *tid = (int)my_gettid(); } void gettid_c(int *tid) { gettid_c_(tid); } static void set_ec_drhook_label(const char *hostname, int hlen) { int tid = get_thread_id_(); int j = tid - 1; int slen = sizeof(ec_drhook[j].s); pid_t unixtid = my_gettid(); snprintf(ec_drhook[j].s,slen,"[EC_DRHOOK:%*s:%d:%d:%lld:%lld]", hlen,hostname,myproc,tid, (long long int)pid, (long long int)unixtid); } #define SECS(x) ((int)(x)) #define NSECS(x) ((int)(1000000000 * ((x) - SECS(x)))) #ifndef __timer_t_defined static void set_killer_timer(const int *ntids, const int *target_omptid, const int *target_sig, const double *start_time, const char *p, int lenp) { // Definition of timer_t, timer_create, timer_set // is a POSIX extention, not available on e.g. Darwin } #else static void set_killer_timer(const int *ntids, const int *target_omptid, const int *target_sig, const double *start_time, const char *p, int lenp) { static volatile sig_atomic_t TimedKill = 0; if (ntids && target_omptid && target_sig && start_time && p) { int tid = get_thread_id_(); if (*target_omptid == -1 || *target_omptid == tid) { char *pfx = PREFIX(tid); timer_t timerid = { 0 }; struct itimerspec its = { 0 } ; struct sigevent sev = { 0 } ; sev.sigev_signo = *target_sig; #if defined(SIGEV_THREAD_ID) sev.sigev_notify = SIGEV_THREAD_ID | SIGEV_SIGNAL; /* sev.sigev_notify_thread_id = my_gettid(); */ sev._sigev_un._tid = my_gettid(); #elif defined(SIGEV_THREAD) sev.sigev_notify = SIGEV_THREAD | SIGEV_SIGNAL; #else sev.sigev_notify = SIGEV_SIGNAL; #endif sev.sigev_value.sival_ptr = &timerid; its.it_value.tv_sec = SECS(*start_time); its.it_value.tv_nsec = NSECS(*start_time); its.it_interval.tv_sec = 0; its.it_interval.tv_nsec = 0; timer_create(CLOCK_MONOTONIC, &sev, &timerid); /* timer_create(CLOCK_REALTIME, &sev, &timerid); */ timer_settime(timerid, 0, &its, NULL); cas_lock(&TimedKill); { fprintf(stderr, "%s %s [%s@%s:%d] Developer timer (%s) expires" " after %.3fs through signal#%d (ntids=%d)\n", pfx,TIMESTR(tid),FFL, p, *start_time, *target_sig, *ntids); fflush(NULL); } cas_unlock(&TimedKill); } /* if (target_omptid == -1 || target_omptid == tid) */ } } #endif #if !defined(NCALLSTACK) #ifdef PARKIND1_SINGLE /* > 0 : USE call stack approach : needed for single precision version */ #define NCALLSTACK 64 #else /* == 0 : do NOT use call stack approach : usually for double precision version */ #define NCALLSTACK 0 #endif #endif static int cstklen = NCALLSTACK; #define HASHSIZE(n) ((unsigned int)1<<(n)) #define HASHMASK(n) (HASHSIZE(n)-1) #define NHASH 16 #define NHASHMAX 24 static int nhash = NHASH; static unsigned int hashsize = HASHSIZE(NHASH); static unsigned int hashmask = HASHMASK(NHASH); #ifdef HPM /* HPM-specific (static) protos */ static void stopstart_hpm(int tid, drhook_key_t *pstop, drhook_key_t *pstart); static void stop_only_hpm(int tid, drhook_key_t *pstop); static void init_hpm(int tid); static double mflops_hpm(const drhook_key_t *keyptr); static double mips_hpm(const drhook_key_t *keyptr); static double divpc_hpm(const drhook_key_t *keyptr); static double mflop_count(const drhook_key_t *keyptr); static double mip_count(const drhook_key_t *keyptr); #else /* Dummies for HPM as macros that do nothing */ #define stopstart_hpm(tid, pstop, pstart) #define stop_only_hpm(tid, pstop) #define init_hpm(tid) #define mflops_hpm(keyptr) 0 #define mips_hpm(keyptr) 0 #define divpc_hpm(keyptr) 0 #define mflop_count(keyptr) 0 #define mip_count(keyptr) 0 #endif /*--- spin ---*/ static int nanospin(int secs, int nanosecs) { struct timespec req, rem; req.tv_sec = secs; req.tv_nsec = nanosecs; return nanosleep(&req, &rem); } static int spin(int secs) { return nanospin(secs, 0); } /*--- dump_file ---*/ static void dump_file(const char *pfx, int tid, int sig, int nsigs, const char filename[]) { /* Developer option: Will this spoil our ATP trace ... ? */ FILE *fp; char in[256]; char *tst = TIMESTR(tid); if (sig > 0 && nsigs >= 1) { fprintf(stderr, "%s %s [%s@%s:%d] Content of the file '%s', signal#%d, nsigs = %d\n", pfx,tst,FFL,filename,sig,nsigs); } else { fprintf(stderr, "%s %s [%s@%s:%d] Content of the file '%s'\n", pfx,tst,FFL,filename); } fp = fopen(filename,"r"); if (fp) { while (fgets(in,sizeof(in),fp) == in) { fprintf(stderr,"%s %s [%s@%s:%d] %s",pfx,tst,FFL,in); /* fprintf(stderr,"%s",in); */ } fclose(fp); } } /*--- dump_hugepages ---*/ // Forward declaration of subroutine in ec_meminfo.F90 void ec_meminfo_( const int* ku, const char* cdstring, const int* kcomm, const int* kbarr, const int* kiotask, const int* kcall, int cdstring_strlen ); static void dump_hugepages(int enforce, const char *pfx, int tid, int sig, int nsigs) { if (enforce || drhook_dump_hugepages) { if (enforce || tid == 1) { /* OML-thread id >= 1 */ static double next_scheduled = -1; double wt = WALLTIME(); if (enforce || wt > next_scheduled) { const int kcomm = -1; const int kbarr = 0; const int kiotask = 0; const int kcall = -1; const int ftnunitno = 0; /* stderr */ fflush(NULL); ec_meminfo_(&ftnunitno,pfx,&kcomm,&kbarr,&kiotask,&kcall,strlen(pfx)); fflush(NULL); if (drhook_dump_buddyinfo) { dump_file(pfx,tid,sig,nsigs,"/proc/buddyinfo"); } if (drhook_dump_meminfo) { dump_file(pfx,tid,sig,nsigs,"/proc/meminfo"); } wt = WALLTIME(); next_scheduled = wt + drhook_dump_hugepages_freq; } } } } /*--- set_default_handler ---*/ static int set_unlimited_corefile(unsigned long long int *hardlimit); static int set_default_handler(int sig, int unlimited_corefile, int verbose) { int rc = -2; if (sig >= 1 && sig <= NSIG) { unsigned long long int hardlimit = 0; struct sigaction sa = { 0 }; sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); /* sigfillset(&sa.sa_mask); -- if we wanted to block all (catchable) signals whilst in subsequent signal handler SIG_DFL sigaddset(&sa.sa_mask, some_signal_to_be_blocked); ... just in case */ sigaction(sig, &sa, NULL); if (unlimited_corefile) rc = set_unlimited_corefile(&hardlimit); /* unconditionally */ if (verbose) { int tid = get_thread_id_(); char *pfx = PREFIX(tid); char buf[128] = ""; if (unlimited_corefile && rc == 0) snprintf(buf,sizeof(buf)," -- hardlimit for core file is now %llu (0x%llx)", hardlimit, hardlimit); fprintf(stderr, "%s %s [%s@%s:%d] " "Enabled default signal handler (SIG_DFL) for signal#%d%s\n", pfx,TIMESTR(tid),FFL, sig,buf); } } return rc; } /*--- malloc_drhook ---*/ static void * malloc_drhook(size_t size) { size_t size1 = MAX(1,size); void *p = malloc(size1); if (!p) { fprintf(stderr, "***Error in malloc_drhook(): Unable to allocate space for %lld bytes\n", (long long int)size1); RAISE(SIGABRT); } return p; } /*--- calloc_drhook ---*/ static void * calloc_drhook(size_t nmemb, size_t size) { size_t n = nmemb * size; void *p = malloc_drhook(n); memset(p,0,n); return p; } /*--- free_drhook ---*/ #define free_drhook(x) { if (x) { free(x); x = NULL; } } /*--- callstack ---*/ /* Note: For single precision calls -- small performance penalty */ typedef struct callstack_t { drhook_key_t **keyptr; unsigned int next; unsigned int maxdepth; } callstack_t; static callstack_t **cstk = NULL; static drhook_key_t *callstack(int tid, void *key, drhook_key_t *keyptr) { /* Single routine -- two usages: (1) Upon c_drhook_start_() we call: (void) callstack(tid, key, u.keyptr); - store keyptr into thread specific call stack - fill *key up to 4-bytes index stating the position in the aforementioned call stack (2) Upon c_drhook_end_() we call: u.keyptr = callstack(tid, (void *)key, NULL); - pass 4-byte index in - obtain keyptr from call stack - decrement call stack */ static const unsigned int inc = 64; unsigned int idx, *Index = key; callstack_t *c = cstk[tid-1]; if (keyptr) { if (!c) { cstk[tid-1] = c = calloc_drhook(1, sizeof(*c)); c->keyptr = (drhook_key_t **) calloc_drhook(cstklen, sizeof(drhook_key_t *)); c->next = 0; c->maxdepth = cstklen; } idx = (c->next)++; if (idx >= c->maxdepth) { drhook_key_t **kptr; unsigned int maxdepth = idx + inc; char *pfx = PREFIX(tid); fprintf(stderr, "%s %s [%s@%s:%d] " "Call stack index %u out of range [0,%u) : extending the range to [0,%u) for this thread\n", pfx,TIMESTR(tid),FFL, idx,c->maxdepth,maxdepth); kptr = (drhook_key_t **) calloc_drhook(maxdepth, sizeof(drhook_key_t *)); memcpy(kptr,c->keyptr,c->maxdepth * sizeof(drhook_key_t *)); free_drhook(c->keyptr); c->keyptr = kptr; c->maxdepth = maxdepth; } if (idx >= c->maxdepth) { char *pfx = PREFIX(tid); fprintf(stderr, "%s %s [%s@%s:%d] " "Call stack index %u still out of range [0,%u). Aborting ...\n", pfx,TIMESTR(tid),FFL, idx,c->maxdepth); RAISE(SIGABRT); } c->keyptr[idx] = keyptr; *Index = idx; } else { idx = --(c->next); if (idx != *Index) { char *pfx = PREFIX(tid); fprintf(stderr, "%s %s [%s@%s:%d] " "Invalid index to call stack %u : out of range [0,%u). Expecting the exact value of %u\n", pfx,TIMESTR(tid),FFL, idx,c->maxdepth,*Index); RAISE(SIGABRT); } keyptr = c->keyptr[idx]; } return keyptr; } /*--- strdup_drhook ---*/ static char * strdup_drhook(const char *s) { int n = strlen(s); char *p = malloc_drhook(n+1); memcpy(p,s,n); p[n] = 0; return p; } /*--- strdup2_drhook ---*/ static char * strdup2_drhook(const char *s, int s_len) { int n = s_len; char *p = malloc_drhook(n+1); memcpy(p,s,n); p[n] = 0; return p; } /*--- timestamp ---*/ static char * timestamp() { time_t tp; const int bufsize = 64; char *buf = malloc_drhook(bufsize+1); time(&tp); strftime(buf, bufsize, "%Y%m%d %H%M%S", localtime(&tp)); return buf; } /*--- TimeStr ---*/ static char * TimeStr(char *s, int slen) { if (s) { time_t tp; char buf[64]; time(&tp); strftime(buf, sizeof(buf), "%Y%m%d:%H%M%S", localtime(&tp)); snprintf(s,slen,"[%s:%lld:%.3f]",buf,(long long int)tp,WALLTIME()); } return s; } /* -- These 2 extern's are called primarily from LinuxTrbk() */ const char *drhook_TIMESTR(int tid) { static const char fixed[] = ""; if (tid <= 0) coml_my_thread_(&tid); { char *s = TIMESTR(tid); return strlen(s) > 0 ? (const char *)s : fixed; } } const char *drhook_PREFIX(int tid) { static const char fixed[] = ""; if (tid <= 0) coml_my_thread_(&tid); { char *s = PREFIX(tid); return strlen(s) > 0 ? (const char *)s : fixed; } } /*--- hashfunc ---*/ unsigned int hashfunc(const char *s, int s_len) { unsigned int hashval; if (opt_trim) { for (hashval = 0; s_len>0 ; s++, s_len--) { unsigned char c = islower(*s) ? toupper(*s) : *s; hashval = (hashval<<4)^(hashval>>28)^(c); } } else { for (hashval = s_len; s_len>0 ; s_len--) { hashval = (hashval<<4)^(hashval>>28)^(*s++); } } hashval = (hashval ^ (hashval>>10) ^ (hashval>>20)) & hashmask; return hashval; } /*--- callpath_hashfunc ---*/ unsigned int callpath_hashfunc(unsigned int inithash, /* from hashfunc() */ const equivalence_t *callpath, int callpath_len, unsigned int *fullhash) { unsigned int hashval; for (hashval = inithash; callpath_len>0 ; callpath++, callpath_len--) { hashval = (hashval<<4)^(hashval>>28)^(callpath->ull); } if (fullhash) *fullhash = hashval; hashval = (hashval ^ (hashval>>10) ^ (hashval>>20)) & hashmask; return hashval; } /*--- insert_calltree ---*/ static void insert_calltree(int tid, drhook_key_t *keyptr) { if (tid >= 1 && tid <= numthreads) { drhook_calltree_t *treeptr = thiscall[tid-1]; while (treeptr->active) { if (!treeptr->next) { treeptr->next = calloc_drhook(1,sizeof(drhook_calltree_t)); treeptr->next->prev = treeptr; } treeptr = treeptr->next; } treeptr->keyptr = keyptr; treeptr->active = 1; thiscall[tid-1] = treeptr; #ifdef HPM if (opt_hpmprof) { drhook_key_t *kptr = treeptr->keyptr; if (!kptr->hpm_stopped) { stopstart_hpm(tid, treeptr->prev ? treeptr->prev->keyptr : NULL, /* stop current (i.e. my parent) */ kptr); /* start to gather for me */ kptr->this_delta_wall_child = 0; kptr->mip_count_in = mip_count(kptr); kptr->mflop_count_in = mflop_count(kptr); #ifdef DEBUG fprintf(stderr,"insert[%.*s@%d]: this_delta_wall_child=%.15g, mip#%.15g, mflop#%.15g\n", kptr->name_len,kptr->name, tid,kptr->this_delta_wall_child, kptr->mip_count_in,kptr->mflop_count_in); #endif } else { stop_only_hpm(tid, treeptr->prev ? treeptr->prev->keyptr : NULL /* stop current (i.e. my parent) */); } /* if (!kptr->hpm_stopped) else */ } /* if (opt_hpmprof) */ #endif } } /*--- remove_calltree ---*/ static void remove_calltree(int tid, drhook_key_t *keyptr, const double *delta_wall, const double *delta_cpu) { if (tid >= 1 && tid <= numthreads) { drhook_calltree_t *treeptr = thiscall[tid-1]; if (treeptr->active && treeptr->keyptr == keyptr) { treeptr->active = 0; if (treeptr->prev) { drhook_key_t *parent_keyptr = treeptr->prev->keyptr; if (parent_keyptr) { /* extra security */ if (opt_walltime) { parent_keyptr->delta_wall_child += (*delta_wall); #ifdef HPM if (opt_hpmprof) parent_keyptr->this_delta_wall_child += (*delta_wall); #endif } if (opt_cputime) { parent_keyptr->delta_cpu_child += (*delta_cpu); } if (opt_memprof) { /* const long long int size = 0; c_drhook_memcounter_(&tid, &size, NULL); fprintf(stderr, ">parent(%.*s)->mem_child = %lld ; this(%.*s)->alldelta = %lld, mem_child = %lld\n", parent_keyptr->name_len, parent_keyptr->name, parent_keyptr->mem_child, keyptr->name_len, keyptr->name, keyptr->maxmem_alldelta, keyptr->mem_child); */ parent_keyptr->mem_child = MAX(parent_keyptr->mem_child, keyptr->maxmem_alldelta); /* fprintf(stderr, "<parent(%.*s)->mem_child = %lld ; this(%.*s)->alldelta = %lld, mem_child = %lld\n", parent_keyptr->name_len, parent_keyptr->name, parent_keyptr->mem_child, keyptr->name_len, keyptr->name, keyptr->maxmem_alldelta, keyptr->mem_child); */ } } /* if (parent_keyptr) */ thiscall[tid-1] = treeptr->prev; } else { thiscall[tid-1] = calltree[tid-1]; } #ifdef HPM if (opt_hpmprof) { drhook_key_t *kptr = treeptr->keyptr; if (!kptr->hpm_stopped) { double this_delta_wall_self = *delta_wall - kptr->this_delta_wall_child; stopstart_hpm(tid, kptr, thiscall[tid-1]->keyptr); /* stop current, (re-)start previous */ /* Calculate moving average of mipsrate & mflops ; divpc we don't bother */ #ifdef DEBUG fprintf(stderr,"remove[%.*s@%d]: this_delta_wall_self=%.15g i.e. %.15g - %.15g", kptr->name_len,kptr->name, tid,this_delta_wall_self, *delta_wall,kptr->this_delta_wall_child); #endif if (this_delta_wall_self > 0) { long long int hpm_calls = ++kptr->hpm_calls; double mipsrate, mflops; kptr->mip_count_in = mip_count(kptr) - kptr->mip_count_in; kptr->mflop_count_in = mflop_count(kptr) - kptr->mflop_count_in; mipsrate = kptr->mip_count_in/this_delta_wall_self; kptr->avg_mipsrate = ((hpm_calls-1)*kptr->avg_mipsrate + mipsrate)/hpm_calls; mflops = kptr->mflop_count_in/this_delta_wall_self; kptr->avg_mflops = ((hpm_calls-1)*kptr->avg_mflops + mflops)/hpm_calls; #ifdef DEBUG fprintf(stderr, ", mip#%.15g, mflop#%.15g : mipsrate=%.15g, avg=%.15g; mflops=%.15g, avg=%.15g", kptr->mip_count_in,kptr->mflop_count_in, mipsrate, kptr->avg_mipsrate, mflops, kptr->avg_mflops); #endif } #ifdef DEBUG fprintf(stderr,"\n"); #endif if (opt_hpmstop_threshold > 0 && kptr->calls == opt_hpmstop_threshold) { /* check whether hpm should anymore be called for this routine */ if (kptr->avg_mflops < opt_hpmstop_mflops) kptr->hpm_stopped = 1; } } else { stop_only_hpm(tid,kptr); } /* if (!kptr->hpm_stopped) else ... */ } /* if (opt_hpmprof) */ #endif curkeyptr[tid-1] = thiscall[tid-1]->keyptr; } else { curkeyptr[tid-1] = NULL; } /* if (treeptr->active && treeptr->keyptr == keyptr) else ... */ } } /*--- memstat ---*/ static long long int slave_stacksize() { char *env_omp = getenv("OMP_STACKSIZE"); long long int stacksize = env_omp ? atoll(env_omp) : 0; if (env_omp) { if (strchr(env_omp,'G')) stacksize *= (long long int)1073741824; /* hence, in GiB */ else if (strchr(env_omp,'M')) stacksize *= (long long int)1048576; /* hence, in MiB */ else if (strchr(env_omp,'K')) stacksize *= (long long int)1024; /* hence, in KiB */ } if (stacksize < 0) stacksize = 0; return stacksize; } static void memstat(drhook_key_t *keyptr, const int *thread_id, int in_getkey) { if (any_memstat && keyptr) { if (opt_gethwm) keyptr->hwm = gethwm_(); if (opt_getrss) { keyptr->maxrss = getrss_(); keyptr->rssnow = getcurheap_thread_(thread_id); } if (opt_getstk) { long long int stk = getstk_(); keyptr->stack = stk; keyptr->maxstack = MAX(keyptr->maxstack,stk); } if (opt_getpag) keyptr->paging = getpag_(); if (opt_memprof) { keyptr->mem_seenmax = getmaxcurheap_thread_(thread_id); if (in_getkey) { /* Upon enter of a Dr.Hook'ed routine */ /* A note for "keyptr->mem_curdelta": 1) do not reset to 0 2) initially calloc'ed to 0 while initializing the keydata[] ~ alias keyptr 3) remember the previous value --> catches memory leaks, too !! */ /* keyptr->mem_curdelta = 0; */ /* Nearly the same holds for "keyptr->mem_child"; we need to capture the maximum/hwm for child */ /* keyptr->mem_child = 0; */ keyptr->paging_in = keyptr->paging; } else { /* Upon exit of a Dr.Hook'ed routine */ long long int alldelta = keyptr->mem_curdelta + keyptr->mem_child; if (alldelta > keyptr->maxmem_alldelta) keyptr->maxmem_alldelta = alldelta; if (keyptr->paging - keyptr->paging_in > keyptr->mem_maxpagdelta) keyptr->mem_maxpagdelta = keyptr->paging - keyptr->paging_in; } if (keyptr->hwm > keyptr->mem_maxhwm) keyptr->mem_maxhwm = keyptr->hwm; if (keyptr->maxrss > keyptr->mem_maxrss) keyptr->mem_maxrss = keyptr->maxrss; if (keyptr->maxstack > keyptr->mem_maxstk) keyptr->mem_maxstk = keyptr->maxstack; } } } /*--- flptrap ---*/ /* ----------------------------------------------------------------------- If we are trapping Floating-Point Error, then set the processor in SYNC modes and enable TRP_INVALID, TRP_DIV_BY_ZERO and TRP_OVERFLOW. ----------------------------------------------------------------------- */ #ifdef RS6K static void flptrap(int sig, int silent) { if (sig == SIGFPE) { /* From John Hague, IBM, UK (--> thanks a lot, John !!)*/ int ret = fp_trap(FP_TRAP_FASTMODE); if ((ret == FP_TRAP_UNIMPL) || (ret == FP_TRAP_ERROR)) { char errmsg[4096]; sprintf(errmsg, "flptrap(): Call to 'fp_trap' in signal_trap failed (return code = %d)\n (line %d in file %s)\n", ret, __LINE__, __FILE__); perror(errmsg); RAISE(SIGABRT); } fp_enable(TRP_INVALID | TRP_DIV_BY_ZERO | TRP_OVERFLOW); } } #elif defined(__GNUC__) && !defined(NO_TRAPFPE) static void flptrap(int sig, int silent) { if (sig == SIGFPE) { /* Adapted from www.twinkle.ws/arnaud/CompilerTricks.html#Glibc_FP */ trapfpe(silent); /* No need for pgf90's -Ktrap=fp now ? */ } } #else static void flptrap(int sig, int silent) { return; /* A dummy */ } #endif static void signal_gencore(int sig SIG_EXTRA_ARGS); static void signal_harakiri(int sig SIG_EXTRA_ARGS); static void signal_drhook(int sig SIG_EXTRA_ARGS); static void trapfpe_treatment(int sig, int silent); /*--- catch_signals ---*/ #define CATCHSIG(x) {\ drhook_sig_t *sl = &siglist[x];\ if (sl->active == 0) {\ drhook_sigfunc_t u;\ u.func3args = signal_drhook;\ sl->active = 1;\ sigemptyset(&sl->new.sa_mask);\ sl->new.sa_handler = u.func1args;\ sl->new.sa_flags = SA_SIGINFO;\ sigaction(x,&sl->new,&sl->old);\ trapfpe_treatment(x,silent); \ if (!silent && myproc == 1) {\ int tid = get_thread_id_(); \ char *pfx = PREFIX(tid); \ fprintf(stderr,\ "%s %s [%s@%s:%d] DR_HOOK also catches signal#%d : New handler '%s' installed at %p (old at %p)\n", \ pfx,TIMESTR(tid),FFL, \ x, "signal_drhook", sl->new.sa_handler, sl->old.sa_handler); \ }\ }\ } static void catch_signals(int silent) { char *env = getenv("DR_HOOK_CATCH_SIGNALS"); if (!silent && myproc == 1) { int tid = get_thread_id_(); char *pfx = PREFIX(tid); fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK_CATCH_SIGNALS=%s\n", pfx,TIMESTR(tid),FFL, env ? env : "<undef>"); } if (env) { const char delim[] = ", \t/"; char *p, *s = strdup_drhook(env); p = strtok(s,delim); while (p) { int sig = atoi(p); if (sig >= 1 && sig <= NSIG) { CATCHSIG(sig); } else if (sig == -1) { /* Makes ALL (catchable) signals available to DR_HOOK */ int j; for (j=1; j<=NSIG; j++) { CATCHSIG(j); } /* for (j=1; j<=NSIG; j++) */ break; } p = strtok(NULL,delim); } free_drhook(s); } } /*--- trapfpe_treatment ---*/ static void trapfpe_treatment(int sig, int silent) { if (sig == SIGFPE) { #if defined(__GNUC__) && !defined(NO_TRAPFPE) int tid = get_thread_id_(); char *pfx = PREFIX(tid); if (drhook_trapfpe) { if (!silent && myproc == 1) { fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK enables SIGFPE-related floating point trapping since DRHOOK_TRAPFPE=%d\n", pfx,TIMESTR(tid),FFL, drhook_trapfpe); } flptrap(sig,silent); /* Has FLP-trapping on, regardless */ } else { if (!silent && myproc == 1) { fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK turns SIGFPE-related floating point trapping off since DRHOOK_TRAPFPE=%d\n", pfx,TIMESTR(tid),FFL, drhook_trapfpe); } untrapfpe(silent); /* Turns off a possible -Ktrap=fp from pgf90 */ } #endif } } /* Fortran callable : calls trapfpe() for slave threads if drhook_trapfpe indicated so Called from DR_HOOK_UTIL_MULTI after DR_HOOK_UTIL (master thread) has been called Matters only for slave threads If *silent = 0, then more verbose output */ void trapfpe_slave_threads_(const int *silent) { int tid = get_thread_id_(); if (tid > 1) { // slave threads if (drhook_trapfpe_master_init) trapfpe_treatment(SIGFPE, *silent); } } void trapfpe_slave_threads(const int *silent) { trapfpe_slave_threads_(silent); } /*--- restore_default_signals ---*/ static void restore_default_signals(int silent) { char *env = getenv("DR_HOOK_RESTORE_DEFAULT_SIGNALS"); if (!silent && myproc == 1) { int tid = get_thread_id_(); char *pfx = PREFIX(tid); fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK_RESTORE_DEFAULT_SIGNALS=%s\n", pfx,TIMESTR(tid),FFL, env ? env : "<undef>"); } if (env) { int unlim_core = 1; const char delim[] = ", \t/"; char *p, *s = strdup_drhook(env); p = strtok(s,delim); while (p) { int sig = atoi(p); if (sig >= 1 && sig <= NSIG) { drhook_sig_t *sl = &siglist[sig]; if (sl->active == 0) { /* Not touched yet by ignore_signals() */ set_default_handler(sig,unlim_core,(!silent && myproc == 1)); unlim_core = 0; if (sig == SIGFPE) trapfpe_treatment(sig, (!silent && myproc == 1)); sl->active = -2; } } else if (sig == -1) { /* Restore default signals for all available/catchable to DR_HOOK */ int j; for (j=1; j<=NSIG; j++) { drhook_sig_t *sl = &siglist[j]; if (sl->active == 0) { /* Not touched yet by ignore_signals() */ set_default_handler(j,unlim_core,(!silent && myproc == 1)); unlim_core = 0; if (j == SIGFPE) trapfpe_treatment(j, (!silent && myproc == 1)); sl->active = -2; } } /* for (j=1; j<=NSIG; j++) */ break; } p = strtok(NULL,delim); } free_drhook(s); } } /*--- ignore_signals ---*/ static void ignore_signals(int silent) { char *env = getenv("DR_HOOK_IGNORE_SIGNALS"); if (!silent && myproc == 1) { int tid = get_thread_id_(); char *pfx = PREFIX(tid); fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK_IGNORE_SIGNALS=%s\n", pfx,TIMESTR(tid),FFL, env ? env : "<undef>"); } if (env) { int tid = get_thread_id_(); char *pfx = PREFIX(tid); const char delim[] = ", \t/"; char *p, *s = strdup_drhook(env); p = strtok(s,delim); while (p) { int sig = atoi(p); if (sig >= 1 && sig <= NSIG) { drhook_sig_t *sl = &siglist[sig]; if (!silent && myproc == 1) { fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK ignores signal#%d altogether\n", pfx,TIMESTR(tid),FFL, sig); } sl->active = -1; } else if (sig == -1) { /* Switches off ALL signals from DR_HOOK */ int j; for (j=1; j<=NSIG; j++) { drhook_sig_t *sl = &siglist[j]; if (!silent && myproc == 1) { fprintf(stderr, "%s %s [%s@%s:%d] DR_HOOK ignores signal#%d altogether\n", pfx,TIMESTR(tid),FFL, j); } sl->active = -1; } /* for (j=1; j<=NSIG; j++) */ break; } p = strtok(NULL,delim); } free_drhook(s); } } /*--- gdb__sigdump ---*/ #if (defined(LINUX) || defined(SUN4)) && !defined(XT3) && !defined(XD1) && !defined(_CRAYC) static void gdb__sigdump(int sig SIG_EXTRA_ARGS) { static int who = 0; /* Current owner of the lock, if > 0 */ int is_set = 0; int it = get_thread_id_(); drhook_sig_t *sl = &siglist[sig]; char *pfx = PREFIX(it); coml_test_lockid_(&is_set, &DRHOOK_lock); if (is_set && who == it) { fprintf(stderr,"%s %s [%s@%s:%d] Received (another) signal#%d (%s)\n", pfx,TIMESTR(it),FFL, sig,sl->name); fprintf(stderr,"%s %s [%s@%s:%d] Recursive calls by the same thread#%d not allowed. Bailing out\n", pfx,TIMESTR(it),FFL, it); return; } if (!is_set) coml_set_lockid_(&DRHOOK_lock); who = it; fprintf(stderr,"%s %s [%s@%s:%d] Received signal#%d(%s) : sigcontextptr=%p\n", pfx,TIMESTR(it),FFL, sig,sl->name,sigcontextptr); LinuxTraceBack(pfx,TIMESTR(it),sigcontextptr); /* LinuxTraceBack(pfx,TIMESTR(tid),NULL); */ who = 0; coml_unset_lockid_(&DRHOOK_lock); } #endif /*--- signal_drhook ---*/ #define SETSIG5(x,ignore_flag,handler_name,preserve_old,xstr) { \ drhook_sig_t *sl = &siglist[x]; \ if (sl->active == 0) { \ drhook_sigfunc_t u; \ u.func3args = handler_name; \ sl->active = 1; \ strcpy(sl->name,xstr); \ sigemptyset(&sl->new.sa_mask); \ sl->new.sa_handler = u.func1args; \ sl->new.sa_flags = SA_SIGINFO; \ sigaction(x,&sl->new,preserve_old ? &sl->old : NULL); \ sl->ignore_atexit = ignore_flag; \ trapfpe_treatment(x,silent); \ if (!silent && myproc == 1) { \ int tid = get_thread_id_(); \ char *pfx = PREFIX(tid); \ const char fmt[] = "%s %s [%s@%s:%d] New signal handler '%s' for signal#%d (%s) at %p (old at %p)\n"; \ fprintf(stderr,fmt, \ pfx,TIMESTR(tid),FFL, \ #handler_name, \ x, sl->name, \ sl->new.sa_handler, \ preserve_old ? sl->old.sa_handler : NULL); \ } \ } \ } #define SETSIG(x,ignore_flag) SETSIG5(x,ignore_flag,signal_drhook,1,#x) #define JSETSIG(x,ignore_flag) { \ drhook_sig_t *sl = &siglist[x]; \ drhook_sigfunc_t u; \ /* fprintf(stderr,"JSETSIG: sl->active = %d\n",sl->active); */ \ u.func3args = signal_harakiri; \ sl->active = 1; \ strcpy(sl->name,#x); \ sigemptyset(&sl->new.sa_mask); \ sl->new.sa_handler = u.func1args; \ sl->new.sa_flags = SA_SIGINFO; \ sigaction(x,&sl->new,&sl->old); \ sl->ignore_atexit = ignore_flag; \ trapfpe_treatment(x,0); \ } #if 0 { \ int tid = get_thread_id_(); \ char *pfx = PREFIX(tid); \ const char fmt[] = "%s %s [%s@%s:%d] Harakiri signal handler '%s' for signal#%d (%s) installed at %p (old at %p)\n"; \ fprintf(stderr,fmt, \ pfx,TIMESTR(tid),FFL, \ "signal_harakiri", \ x, sl->name, \ sl->new.sa_handler, \ sl->old.sa_handler); \ } \ #endif #if defined(RS6K) && defined(__64BIT__) #define DRH_STRUCT_RLIMIT struct rlimit64 #define DRH_GETRLIMIT getrlimit64 #define DRH_SETRLIMIT setrlimit64 #else #define DRH_STRUCT_RLIMIT struct rlimit #define DRH_GETRLIMIT getrlimit #define DRH_SETRLIMIT setrlimit #endif static int set_unlimited_corefile(unsigned long long int *hardlimit) { /* Make sure we *only* set soft-limit (not hard-limit) to 0 in our scripts i.e. : $ ulimit -S -c 0 but *not* $ ulimit -c 0 See man ksh or man bash for more */ int rc = -1; if (unlimited_corefile_retcode == 9999) { /* Done only once */ DRH_STRUCT_RLIMIT r; if (DRH_GETRLIMIT(RLIMIT_CORE, &r) == 0) { r.rlim_cur = r.rlim_max; if (DRH_SETRLIMIT(RLIMIT_CORE, &r) == 0) { saved_corefile_hardlimit = r.rlim_cur; rc = 0; } } unlimited_corefile_retcode = rc; } if (hardlimit) *hardlimit = saved_corefile_hardlimit; rc = unlimited_corefile_retcode; return rc; } static void signal_gencore(int sig SIG_EXTRA_ARGS) { if (opt_gencore > 0) { opt_gencore = 0; /* A tiny chance for a race condition between threads */ if (sig == opt_gencore_signal && sig >= 1 && sig <= NSIG) { signal(sig, SIG_IGN); signal(SIGABRT, SIG_DFL); { /* Enable unlimited cores (up to hard-limit) and call abort() --> generates core dump */ if (set_unlimited_corefile(NULL) == 0) { int tid = get_thread_id_(); char *pfx = PREFIX(tid); fprintf(stderr, "%s %s [%s@%s:%d] Received signal#%d and now calling abort() ...\n", pfx,TIMESTR(tid),FFL, sig); LinuxTraceBack(pfx,TIMESTR(tid),NULL); abort(); /* Dump core, too */ } } /* Should never end up here */ fflush(NULL); _exit(128+ABS(sig)); } /* if (sig >= 1 && sig <= NSIG && sig == opt_gencore_signal) */ } } static char *safe_llitoa(long long int i, char b[], int blen) { char const digit[] = "0123456789"; char *p = b; long long int shifter; if (i < 0) { *p++ = '-'; i *= -1; } shifter = i; do { /* Move to where representation ends */ ++p; shifter = shifter/10; } while (shifter); *p = '\0'; do{ /* Move back, inserting digits as u go */ *--p = digit[i%10]; i = i/10; } while (i); return b; } static void signal_harakiri(int sig SIG_EXTRA_ARGS) { /* A signal handler that will force to exit the current thread immediately for sure */ /* The following output should be malloc-free */ time_t tp; int idummy; int fd = fileno(stderr); int tid = get_thread_id_(); int nsigs = TIDNSIGS(tid); char *pfx = PREFIX(tid); char buf[128]; char s[1024]; strcpy(s,pfx); /* [%s@%s:%d] for FFL below */ strcat(s," ["); strcat(s,__FUNCTION__); strcat(s,"@"); strcat(s,__FILE__); strcat(s,":"); strcat(s,safe_llitoa(__LINE__,buf,sizeof(buf))); strcat(s,"] [epoch="); time(&tp); strcat(s,safe_llitoa(tp,buf,sizeof(buf))); strcat(s,"] Terminating process to avoid hangs due to signal#"); strcat(s,safe_llitoa(sig,buf,sizeof(buf))); strcat(s," by raising signal SIGKILL = "); strcat(s,safe_llitoa(SIGKILL,buf,sizeof(buf))); strcat(s,", nsigs = "); strcat(s,safe_llitoa(nsigs,buf,sizeof(buf))); idummy = write(fd,s,strlen(s)); #if 0 batch_kill_(); #endif raise(SIGKILL); /* Use raise, not RAISE here */ _exit(128+ABS(sig)); /* Should never reach here, bu' in case it does, then ... */ } static void signal_drhook(int sig SIG_EXTRA_ARGS) { volatile int nfirst = drhook_use_lockfile ? 0 : 1; int nsigs; int trace_size; int tid; pid_t unixtid; char *pfx; void *trace[GNUC_BTRACE]; // Let only one ("fastest") thread per task to this error processing static volatile sig_atomic_t been_here_already = 0; static volatile sig_atomic_t thing = 0; if (sig < 1 || sig > NSIG) return; // .. since have seen this, too :-( if (been_here_already++ > 0) return; // avoid calling more than once ... since it leads more often than not into troubles cas_lock(&thing); trace_size = backtrace(trace, GNUC_BTRACE); unixtid = my_gettid(); tid = get_thread_id_(); pfx = PREFIX(tid); if (signals_set && sig >= 1 && sig <= NSIG) { drhook_sig_t *sl = &siglist[sig]; sigset_t newmask, oldmask; /* A tiny chance for a race condition between threads */ // Using compare-and-swap -stuff from the include cas.h (also in ecProf) /* Signal catching */ { nsigs = (++signal_handler_called); if (sl->ignore_atexit) signal_handler_ignore_atexit++; } if (ec_drhook && tid >= 1 && tid <= numthreads) ec_drhook[tid-1].nsigs = nsigs; /* Store for possible signal_harakiri() */ /*------------------------------------------------------------ Strategy: - drhook intercepts most interrupts. - 1st interupt will - call alarm(10) to try to make sure 2nd interrupt received - try to call tracebacks and exit (which includes atexits) - 2nd (and subsequent) interupts will - spin for 20 sec (to give 1st interrupt time to complete tracebacks) - and then call _exit (bypassing atexit) ------------------------------------------------------------*/ /* if (sig != SIGTERM) signal(SIGTERM, SIG_DFL); */ /* Let the default SIGTERM to occur */ coml_get_max_threads_(&max_threads); if (nsigs == 1) { /*---- First call to signal handler: call alarm(drhook_harakiri_timeout), tracebacks, exit ------*/ if (!nfirst) { const char drhook_lockfile[] = "drhook_lock"; if (access(drhook_lockfile,F_OK) == -1) { int fd = open(drhook_lockfile,O_RDONLY); if (fd == -1) { // File did not exist -- create it fd = open(drhook_lockfile, O_CREAT|O_WRONLY|O_TRUNC|O_EXCL, S_IRUSR|S_IWUSR); if (fd >= 0) { int rc_lock = flock(fd, LOCK_EX | LOCK_NB); if (rc_lock == 0) { size_t count = sizeof(myproc); ssize_t sz = write(fd,&myproc,count); if (sz == count) nfirst = 1; //rc_lock = flock(fd, LOCK_UN); } close(fd); } } else { // after all the file already existed close(fd); } } } if (nfirst) { /* Enjoy some output (only from the first guy that came in) */ long long int hwm = gethwm_(); long long int rss = getmaxrss_(); long long int maxstack = getmaxstk_(); long long int vmpeak = getvmpeak_(); long long int pag = getpag_(); rss /= 1048576; hwm /= 1048576; maxstack /= 1048576; vmpeak /= 1048576; fprintf(stderr, "%s %s [%s@%s:%d] Received signal#%d (%s) :: %lldMB (heap)," " %lldMB (maxrss), %lldMB (maxstack), %lldMB (vmpeak), %lld (paging), nsigs = %d\n", pfx,TIMESTR(tid),FFL, sig, sl->name, hwm, rss, maxstack, vmpeak, pag, nsigs); #if 0 fprintf(stderr, "%s %s [%s@%s:%d] Also activating Harakiri-alarm (SIGALRM=%d) to expire after %ds elapsed to prevent hangs, nsigs = %d\n", pfx,TIMESTR(tid),FFL, SIGALRM,drhook_harakiri_timeout,nsigs); #endif } JSETSIG(SIGALRM,1); /* This will now set another signal handler than signal_drhook */ fflush(NULL); alarm(drhook_harakiri_timeout); #if defined(SA_SIGINFO) && SA_SIGINFO > 0 if (sigcode) { const char *s = NULL; void *addr = sigcode->si_addr; void *bt = addr; ucontext_t *uc = (ucontext_t *)sigcontextptr; #ifdef __powerpc64__ bt = uc ? (void *) uc->uc_mcontext.regs->nip : NULL; // Trick from PAPI_overflow() #elif defined(__x86_64__) && defined(REG_RIP) // gcc specific bt = uc ? (void *) uc->uc_mcontext.gregs[REG_RIP] : NULL; // RIP: x86_64 specific ; only available in 64-bit mode */ #elif defined(__i386__) && defined(REG_EIP) // gcc specific bt = uc ? (void *) uc->uc_mcontext.gregs[REG_EIP] : NULL; // EIP: x86 specific ; only available in 32-bit mode */ #endif if (!addr) addr = bt; if (sig == SIGFPE) { switch (sigcode->si_code) { case FPE_INTDIV: s = "integer divide by zero"; break; case FPE_INTOVF: s = "integer overflow"; break; case FPE_FLTDIV: s = "floating-point divide by zero"; break; case FPE_FLTOVF: s = "floating-point overflow"; break; case FPE_FLTUND: s = "floating-point underflow"; break; case FPE_FLTRES: s = "floating-point inexact result"; break; case FPE_FLTINV: s = "floating-point invalid operation"; break; case FPE_FLTSUB: s = "subscript out of range"; break; default: s = "unrecognized si_code for SIGFPE"; break; } } else if (sig == SIGILL) { switch (sigcode->si_code) { case ILL_ILLOPC: s = "illegal opcode"; break; case ILL_ILLOPN: s = "illegal operand"; break; case ILL_ILLADR: s = "illegal addressing mode"; break; case ILL_ILLTRP: s = "illegal trap"; break; case ILL_PRVOPC: s = "privileged opcode"; break; case ILL_PRVREG: s = "privileged register"; break; case ILL_COPROC: s = "coprocessor error"; break; case ILL_BADSTK: s = "internal stack error"; break; default: s = "unrecognized si_code for SIGILL"; break; } } else if (sig == SIGSEGV) { switch (sigcode->si_code) { case SEGV_MAPERR: s = "address not mapped to object"; break; case SEGV_ACCERR: s = "invalid permissions for mapped object"; break; default: s = "unrecognized si_code for SIGSEGV"; break; } } else if (sig == SIGBUS) { switch (sigcode->si_code) { case BUS_ADRALN: s = "invalid address alignment"; break; case BUS_ADRERR: s = "nonexistent physical address"; break; case BUS_OBJERR: s = "object-specific hardware error"; break; default: s = "unrecognized si_code for SIGBUS"; break; } } else { s = "unrecognized si_code"; } if (s) { #ifdef __USE_GNU int works = 0; Dl_info dlinfo; if (dladdr(bt,&dlinfo) == 0) { dlinfo.dli_fname = NULL; dlinfo.dli_sname = NULL; dlinfo.dli_fbase = 0; } else works = 1; if (sig == SIGFPE) { int excepts = fegetexcept(); fprintf(stderr, "%s %s [%s@%s:%d] Signal#%d was caused by %s [memaddr=%p] [excepts=0x%x [%d]] : %p at %s(%s), nsigs = %d\n", pfx,TIMESTR(tid),FFL, sig, s, addr, excepts, excepts, bt, dlinfo.dli_fname ? dlinfo.dli_fname : "<unknown_object>", dlinfo.dli_sname ? dlinfo.dli_sname : "<unknown_function>", nsigs); } else { fprintf(stderr, "%s %s [%s@%s:%d] Signal#%d was caused by %s [memaddr=%p] : %p at %s(%s), nsigs = %d\n", pfx,TIMESTR(tid),FFL, sig, s, addr, bt, dlinfo.dli_fname ? dlinfo.dli_fname : "<unknown_object>", dlinfo.dli_sname ? dlinfo.dli_sname : "<unknown_function>", nsigs); } if (works && trace_size > 0) { int ndigits = (trace_size > 0) ? 1 + (int)log10(trace_size) : 0; int jt; for (jt = 0; jt < trace_size; ++jt) { void *pbt = trace[jt]; if (dladdr(pbt,&dlinfo) == 0) { dlinfo.dli_fname = NULL; dlinfo.dli_sname = NULL; dlinfo.dli_fbase = 0; } fprintf(stderr, "%s %s [%s@%s:%d] : [%*.*d]: %s %s %p %p # addr2line\n", pfx,TIMESTR(tid),FFL, ndigits, ndigits, jt, dlinfo.dli_sname ? dlinfo.dli_sname : "<unknown_function>", dlinfo.dli_fname ? dlinfo.dli_fname : "<unknown_object>", dlinfo.dli_fbase, pbt); } } #else fprintf(stderr, "%s %s [%s@%s:%d] Signal#%d was caused by %s [memaddr=%p], nsigs = %d\n", pfx,TIMESTR(tid),FFL, sig, s, addr, nsigs); #endif fflush(NULL); } } #endif } if (nsigs > 1 || !nfirst) { /*----- 2nd (and subsequent) calls to signal handler: spin harakiri-timeout + 60 sec, _exit ---------*/ int offset = 60; int secs = drhook_harakiri_timeout+offset; if (!drhook_use_lockfile) { /* Less output if lockfile was used ... */ fprintf(stderr, "%s %s [%s@%s:%d] Calling signal_harakiri upon receipt of signal#%d" " after %ds spin, nsigs = %d, nfirst = %d\n", pfx,TIMESTR(tid),FFL, sig,secs,nsigs,nfirst); fflush(NULL); } spin(secs); signal_harakiri(sig SIG_PASS_EXTRA_ARGS); } /* All below this point should be nsigs == 1 i.e. the first threat arriving signal_drhook() */ #ifdef RS6K /*-- llcancel attempted but sometimes hangs --- { char *env = getenv("LOADL_STEP_ID"); if (env) { char *cancel = "delayed_llcancel "; char cmd[80]; sprintf(cmd,"%s %s &",cancel,env); fprintf(stderr,"tid#%d issuing command: %s\n",tid,cmd; fflush(NULL); system(cmd); } } ------------------------------------*/ #endif /* sigfillset(&newmask); -- dead code since sigprocmask() was not called */ /* sigemptyset(&newmask); sigaddset(&newmask, sig); */ /* Start critical region (we don't want any signals to interfere while doing this) */ /* sigprocmask(SIG_BLOCK, &newmask, &oldmask); */ if (nsigs == 1 && nfirst) { /* Print Dr.Hook traceback */ const int ftnunitno = 0; /* stderr */ const int print_option = 2; /* calling tree */ int level = 0; fprintf(stderr, "%s %s [%s@%s:%d] Starting DrHook backtrace for signal#%d, nsigs = %d\n", pfx,TIMESTR(tid),FFL, sig,nsigs); dump_hugepages(0,pfx,tid,sig,nsigs); /* We don't wanna enforce anymore -- this the first arg == 0 now */ if (drhook_dump_smaps) { char filename[64]; snprintf(filename,sizeof(filename),"/proc/%ld/smaps",(long)unixtid); dump_file(pfx,tid,sig,nsigs,filename); } if (drhook_dump_maps) { char filename[64]; snprintf(filename,sizeof(filename),"/proc/%ld/maps",(long)unixtid); dump_file(pfx,tid,sig,nsigs,filename); } if (drhook_dump_buddyinfo) { dump_file(pfx,tid,sig,nsigs,"/proc/buddyinfo"); } if (drhook_dump_meminfo) { dump_file(pfx,tid,sig,nsigs,"/proc/meminfo"); } fflush(NULL); c_drhook_print_(&ftnunitno, &tid, &print_option, &level); fflush(NULL); /* To make it less likely that another thread generates a signal while we are doing a traceback lets wait a while (seems to fix problems of the traceback terminating abnormally. Probably a better way of doing this involving holding off signals but sigprocmask is not safe in multithreaded code - P Towers Dec 10 2012 This was originally an issue with the Intel compiler but may be of benefit for other compilers. Cannot see it doing harm - P Towers Aug 29 2013 */ spin(MIN(5,tid)); if (sig != SIGABRT && sig != SIGTERM) { #ifdef RS6K xl__sigdump(sig SIG_PASS_EXTRA_ARGS); /* Can't use xl__trce(...), since it also stops */ #endif #if 1 /* Active code ? */ #if (defined(LINUX) || defined(SUN4)) && !defined(XT3) && !defined(XD1) LinuxTraceBack(pfx,TIMESTR(tid),NULL); #endif #else /* Dead code ? */ #if (defined(LINUX) || defined(SUN4)) && !defined(XT3) && !defined(XD1) && !defined(_CRAYC) gdb__sigdump(sig SIG_PASS_EXTRA_ARGS); #endif #endif #ifdef __INTEL_COMPILER intel_trbk_(); /* from ../utilities/gentrbk.F90 */ #endif #if defined(NECSX) necsx_trbk_("signal_drhook",13); /* from ../utilities/gentrbk.F90 */ #endif } #ifdef VPP #if defined(SA_SIGINFO) && SA_SIGINFO > 0 _TraceCalls(sigcontextptr); /* Need VPP's libmp.a by Pierre Lagier */ #endif #endif fprintf(stderr, "%s %s [%s@%s:%d] DrHook backtrace done for signal#%d, nsigs = %d\n", pfx,TIMESTR(tid),FFL, sig,nsigs); fflush(NULL); } /* sigprocmask(SIG_SETMASK, &oldmask, 0); */ /* End critical region : the original signal state restored */ { int restored = 0, tdiff; time_t t1, t2; drhook_sigfunc_t u; u.func3args = signal_drhook; if (opt_propagate_signals && sl->old.sa_handler != SIG_DFL && sl->old.sa_handler != SIG_IGN && sl->old.sa_handler != u.func1args) { u.func1args = sl->old.sa_handler; if (atp_enabled) { /* Restore the default, core-file creating action to these "ATP" recognized signals */ switch (sig) { case SIGTERM: if (atp_ignore_sigterm) break; /* SIGSEGV not reset to SIG_DFL as ATP now ignores SIGTERM */ /* Fall thru (see man atp on Cray) */ case SIGINT: /* Also, see ifssig.c : used as a RESTART signal, confusingly enough */ case SIGFPE: case SIGILL: case SIGTRAP: case SIGABRT: case SIGBUS: case SIGSEGV: case SIGSYS: case SIGXCPU: #if defined(SIGXFSZ) case SIGXFSZ: #endif fprintf(stderr, "%s %s [%s@%s:%d] Resetting SIGSEGV (%d) to " "default signal handler (SIG_DFL) before calling ATP for signal#%d, nsigs = %d\n", pfx,TIMESTR(tid),FFL, SIGSEGV,sig,nsigs); set_default_handler(SIGSEGV,1,1); restored = 1; break; default: break; } } fprintf(stderr, "%s %s [%s@%s:%d] Calling previous signal handler at %p for signal#%d, nsigs = %d\n", pfx,TIMESTR(tid),FFL, u.func1args,sig,nsigs); time(&t1); u.func3args(sig SIG_PASS_EXTRA_ARGS); /* This could now be the ATP */ time(&t2); tdiff = (t2 - t1); fprintf(stderr, "%s %s [%s@%s:%d] Returned from previous signal handler" " (at %p, signal#%d, time taken = %ds), nsigs = %d\n", pfx,TIMESTR(tid),FFL, u.func1args,sig,tdiff,nsigs); if (atp_enabled && restored && atp_max_cores > 0) { /* Assuming it was indeed ATP, then lets spin a bit to allow other cores be dumped */ int secs = MIN(drhook_harakiri_timeout,atp_max_analysis_time); int grace = 60; secs = 60 + MIN(tdiff * (atp_max_cores-1),secs); if (secs > 0) { fprintf(stderr, "%s %s [%s@%s:%d] Before aborting (signal#%d) spin %ds (incl. grace %ds)" " to give ATP time to write all #%d core file(s), nsigs = %d\n", pfx,TIMESTR(tid),FFL, sig,secs,grace,atp_max_cores,nsigs); spin(secs); } } if (sig != SIGABRT && sig != SIGTERM) { if (atp_enabled && atp_max_cores > 0) { fprintf(stderr, "%s %s [%s@%s:%d] DrHook calls abort() and attempts to dump core (signal#%d), nsigs = %d\n", pfx,TIMESTR(tid),FFL, sig,nsigs); set_default_handler(SIGABRT,1,1); abort(); } } /* Now proceed to definitive _exit() */ } else { fprintf(stderr, "%s %s [%s@%s:%d] Not configured (DR_HOOK_PROPAGATE_SIGNALS=%d) or " "can't call previous signal handler (for signal#%d) in the chain at %p, nsigs = %d\n", pfx,TIMESTR(tid),FFL, opt_propagate_signals,sig, sl->old.sa_handler,nsigs); } } } { int errcode = 128 + ABS(sig); /* Make sure that the process/thread really exits now -- immediately !! */ fprintf(stderr, "%s %s [%s@%s:%d] Error _exit(%d) upon receipt of signal#%d, nsigs = %d\n", pfx,TIMESTR(tid),FFL, errcode,sig,nsigs); fflush(NULL); _exit(errcode); } cas_unlock(&thing); } void c_drhook_set_mpi_() { dr_hook_procinfo_(&myproc, &nproc); } void c_drhook_not_mpi_() { /* Emulates in a one call : export DR_HOOK_NOT_MPI=1" */ /* To have a desired effect, call BEFORE the very first call to DR_HOOK */ static char s[] = "DR_HOOK_NOT_MPI=1"; /* note: must be static */ putenv(s); } /*--- signal_drhook_init ---*/ static void signal_drhook_init(int enforce) { char *env = getenv("DR_HOOK_SILENT"); int silent = env ? atoi(env) : 0; int j; dr_hook_procinfo_(&myproc, &nproc); if (myproc < 1) myproc = 1; /* Just to enable output as if myproc was == 1 */ /* Signals may not yet been set, since MPI not initialized Only enforce-parameter can enforce to set these => no output on myproc=1 */ if (!enforce && (myproc < 1 || nproc < 0)) return; if (signals_set) return; /* Extra safety */ /* To present sumpini.F90 (f.ex.) initializing DrHook-signals in case of DR_HOOK was turned off (=0), then set also export DR_HOOK_INIT_SIGNALS=0 */ env = getenv("DR_HOOK_INIT_SIGNALS"); if (env && *env == '0') { signals_set = 2; /* Pretend they are set */ return; /* Never initialize signals via DrHook (dangerous, but sometimes necessary) */ } if (!ec_drhook) { int slen; char hostname[EC_HOST_NAME_MAX]; char *pdot; int ntids = 1; coml_get_max_threads_(&ntids); numthreads = ntids; ec_drhook = calloc_drhook(ntids, sizeof(*ec_drhook)); slen = sizeof(ec_drhook[0].s); timestr_len = sizeof(ec_drhook[0].timestr); if (gethostname(hostname,sizeof(hostname)) != 0) strcpy(hostname,"unknown"); pdot = strchr(hostname,'.'); if (pdot) *pdot = '\0'; // cut short from "." char e.g. hostname.fmi.fi becomes just "hostname" if (myproc == 1) { fprintf(stderr,"[EC_DRHOOK:hostname:myproc:omptid:pid:unixtid] [YYYYMMDD:HHMMSS:epoch:walltime] [function@file:lineno] -- Max OpenMP threads = %d\n",ntids); } #if 1 { extern void run_fortran_omp_parallel_ipfstr_(const int *, void (*func)(const char *, int), const char *, int); run_fortran_omp_parallel_ipfstr_(&ntids,set_ec_drhook_label,hostname,strlen(hostname)); } #else #pragma omp parallel num_threads(ntids) { set_ec_drhook_label(hostname,strlen(hostname)); } #endif } env = getenv("ATP_ENABLED"); atp_enabled = (env && *env == '1') ? 1 : 0; if (atp_enabled) { env = getenv("ATP_MAX_CORES"); if (env) atp_max_cores = atoi(env); env = getenv("ATP_MAX_ANALYSIS_TIME"); if (env) atp_max_analysis_time = atoi(env); env = getenv("ATP_IGNORE_SIGTERM"); if (env) atp_ignore_sigterm = atoi(env); if (!silent && myproc == 1) { int tid = get_thread_id_(); char *pfx = PREFIX(tid); fprintf(stderr,"%s %s [%s@%s:%d] ATP_ENABLED=%d\n",pfx,TIMESTR(tid),FFL,atp_enabled); fprintf(stderr,"%s %s [%s@%s:%d] ATP_MAX_CORES=%d\n",pfx,TIMESTR(tid),FFL,atp_max_cores); fprintf(stderr,"%s %s [%s@%s:%d] ATP_MAX_ANALYSIS_TIME=%d\n",pfx,TIMESTR(tid),FFL,atp_max_analysis_time); fprintf(stderr,"%s %s [%s@%s:%d] ATP_IGNORE_SIGTERM=%d\n",pfx,TIMESTR(tid),FFL,atp_ignore_sigterm); } } process_options(); for (j=1; j<=NSIG; j++) { /* Initialize */ drhook_sig_t *sl = &siglist[j]; sprintf(sl->name, "DR_HOOK_SIG#%d", j); sl->active = 0; sl->ignore_atexit = 0; } ignore_signals(silent); /* These signals will not be handled by DR_HOOK */ restore_default_signals(silent); /* These signals will be restored with SIG_DFL status (regardless if to-be-caught with DrHook or ATP or anyhing else) */ SETSIG(SIGABRT,0); /* Good to be first */ SETSIG(SIGBUS,0); SETSIG(SIGSEGV,0); #if defined(SIGEMT) SETSIG(SIGEMT,0); #endif #if defined(SIGSTKFLT) SETSIG(SIGSTKFLT,0); /* Stack fault */ #endif #if !defined(NECSX) /* For the moment turn off these on NEC SX ... */ SETSIG(SIGFPE,0); SETSIG(SIGILL,0); #endif SETSIG(SIGTRAP,0); /* Should be switched off when used with debuggers */ // SETSIG(SIGINT,0); /* Also, see ifssig.c : used as a RESTART signal, confusingly enough */ if (atp_enabled) { /* We let ATP to catch SIGQUIT (it uses this for non-failed tasks, we think) -- thus commented out */ /* SETSIG(SIGQUIT,0); */ /* Unless ATP ignores SIGTERM, we ignore it from DrHook -- thus conditionally commented out */ if (atp_ignore_sigterm) SETSIG(SIGTERM,0); /* Means: DrHook does NOT ignore SIGTERM -- ATP does */ } else { SETSIG(SIGQUIT,0); SETSIG(SIGTERM,0); } #if defined(SIGIOT) SETSIG(SIGIOT,0); /* Same as SIGABRT; Used to be a typo SIGIO ;-( */ #endif SETSIG(SIGXCPU,1); /* ignore_atexit == 1 i.e. no profile info via atexit() */ #if defined(SIGXFSZ) SETSIG(SIGXFSZ,0); #endif #if defined(SIGDANGER) SETSIG(SIGDANGER,1); /* To catch the place where paging space gets dangerously low */ #endif SETSIG(SIGSYS,0); /* SETSIG(SIGCHLD); we may not want to catch this either; may interfere parallel processing */ /* -- not active SETSIG(SIGCHLD); SETSIG(SIGHUP); SETSIG(SIGCONT); */ #if defined(SIGCORE) SETSIG(SIGCORE,0); /* NEC SX core dumping */ #endif #if defined(SIGDEAD) SETSIG(SIGDEAD,0); /* NEC SX dead lock */ #endif #if defined(SIGXMEM) SETSIG(SIGXMEM,0); /* NEC SX exceeded memory size limit */ #endif #if defined(SIGXDSZ) SETSIG(SIGXDSZ,0); /* NEC SX exceeded data size limit */ #endif #if defined(SIGMEM32) SETSIG(SIGMEM32,0); /* NEC SX exceeded memory size limit of 32KB */ #endif #if defined(SIGNMEM) SETSIG(SIGNMEM,0); /* NEC SX exce error for no memory */ #endif #if defined(SIGXABT) SETSIG(SIGXABT,0); /* NEC SX distributed parallel program aborted */ #endif /* #if defined(SIG) SETSIG(SIG,0); #endif */ catch_signals(silent); /* Additional signals to be seen by DR_HOOK */ if (opt_gencore > 0 && opt_gencore_signal >= 1 && opt_gencore_signal <= NSIG) { drhook_sigfunc_t u; u.func3args = signal_gencore; signal(opt_gencore_signal, u.func1args); /* A facility to dump core */ } signals_set = 1; /* Signals are set now */ } /*--- get_mon_out ---*/ static char * get_mon_out(int me) { char *s = mon_out; if (mon_out_procs == me || (mon_out_procs == -1 && me >= 1 && me <= nproc)) { if (!mon_out) mon_out = strdup_drhook("drhook.prof.%d"); s = malloc_drhook((strlen(mon_out) + 20) * sizeof(*s)); sprintf(s,mon_out,me); } if (!s) s = strdup_drhook("drhook.prof.0"); return s; } /*--- get_memmon_out ---*/ static char * get_memmon_out(int me) { char *s = NULL; char *p = get_mon_out(me); if (p) { s = malloc_drhook((strlen(p) + 5) * sizeof(*s)); sprintf(s,"%s-mem",p); } if (!s) s = strdup_drhook("drhook.prof.0-mem"); return s; } /*--- random_memstat ---*/ static void random_memstat(int tid, int enforce) { if (tid == 1 && opt_random_memstat > 0 && opt_random_memstat <= RAND_MAX) { int random_number = rand(); if (enforce || random_number % opt_random_memstat == 0) { long long int maxhwm = getmaxhwm_(); long long int maxstk = getmaxstk_(); if (drhook_stacksize_threshold > 0 && maxstk > drhook_stacksize_threshold) { /* Abort hopefully with traceback */ char *pfx = PREFIX(tid); long long int vmpeak = getvmpeak_() / (long long int) 1048576; long long int threshold = drhook_stacksize_threshold / (long long int) 1048576; long long int ompstk = drhook_omp_stacksize / (long long int) 1048576; maxstk /= (long long int) 1048576; maxhwm /= (long long int) 1048576; fprintf(stderr, "%s %s [%s@%s:%d] Stack usage [MB] very high : %lld > %lld (= %g x OMP_STACKSIZE=%lld ; maxhwm=%lld ; vmpeak=%lld)\n", pfx,TIMESTR(tid),FFL, maxstk,threshold, opt_trace_stack,ompstk, maxhwm,vmpeak); RAISE(SIGABRT); } } } } /*--- process_options ---*/ static void do_prof(); void /* Fortran callable */ c_drhook_process_options_(const int *lhook, const int *Myproc, const int *Nproc) { c_drhook_set_lhook_(lhook); if (Myproc) myproc = *Myproc; if (Nproc) nproc = *Nproc; process_options(); } #define OPTPRINT(fp,...) if (fp) fprintf(fp,__VA_ARGS__) static void process_options() { char *pfx = ""; char *env; FILE *fp = NULL; int tid, ienv, newline; static int processed = 0; if (processed) return; tid = get_thread_id_(); env = getenv("DR_HOOK_SHOW_PROCESS_OPTIONS"); ienv = env ? atoi(env) : 1; if (ienv == -1 || ienv == myproc) fp = stderr; if (fp) pfx = PREFIX(tid); OPTPRINT(fp,"%s %s [%s@%s:%d] fp = %p\n",pfx,TIMESTR(tid),FFL,fp); env = getenv("DR_HOOK_ALLOW_COREDUMP"); if (env) { ienv = atoi(env); allow_coredump = (ienv == -1 || ienv == myproc) ? ienv : 0; } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_ALLOW_COREDUMP=%d\n",pfx,TIMESTR(tid),FFL,allow_coredump); if (allow_coredump) { unsigned long long int hardlimit = 0; int rc = set_unlimited_corefile(&hardlimit); if (rc == 0) { OPTPRINT(fp,"%s %s [%s@%s:%d] Hardlimit for core file is now %llu (0x%llx)\n", pfx,TIMESTR(tid),FFL,hardlimit,hardlimit); } } env = getenv("DR_HOOK_PROFILE"); if (env) { char *s = calloc_drhook(strlen(env) + 15, sizeof(*s)); strcpy(s,env); if (!strchr(env,'%')) strcat(s,".%d"); mon_out = strdup_drhook(s); free_drhook(s); } if (mon_out) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_PROFILE=%s\n",pfx,TIMESTR(tid),FFL,mon_out); env = getenv("DR_HOOK_PROFILE_PROC"); if (env) { mon_out_procs = atoi(env); } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_PROFILE_PROC=%d\n",pfx,TIMESTR(tid),FFL,mon_out_procs); env = getenv("DR_HOOK_PROFILE_LIMIT"); if (env) { percent_limit = atof(env); } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_PROFILE_LIMIT=%.3f\n",pfx,TIMESTR(tid),FFL,percent_limit); env = getenv("DR_HOOK_FUNCENTER"); if (env) { opt_funcenter = atoi(env); } if (opt_funcenter) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_FUNCENTER=%d\n",pfx,TIMESTR(tid),FFL,opt_funcenter); env = getenv("DR_HOOK_FUNCEXIT"); if (env) { opt_funcexit = atoi(env); } if (opt_funcexit) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_FUNCEXIT=%d\n",pfx,TIMESTR(tid),FFL,opt_funcexit); if (opt_funcenter || opt_funcexit) { opt_gethwm = opt_getstk = 1; } env = getenv("DR_HOOK_TIMELINE"); if (env) { opt_timeline = atoi(env); } if (opt_timeline) { OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TIMELINE=%d\n",pfx,TIMESTR(tid),FFL,opt_timeline); env = getenv("DR_HOOK_TIMELINE_THREAD"); if (env) { opt_timeline_thread = atoi(env); } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TIMELINE_THREAD=%d\n",pfx,TIMESTR(tid),FFL,opt_timeline_thread); env = getenv("DR_HOOK_TIMELINE_FORMAT"); if (env) { opt_timeline_format = atoi(env); } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TIMELINE_FORMAT=%d\n",pfx,TIMESTR(tid),FFL,opt_timeline_format); env = getenv("DR_HOOK_TIMELINE_UNITNO"); if (env) { opt_timeline_unitno = atoi(env); } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TIMELINE_UNITNO=%d\n",pfx,TIMESTR(tid),FFL,opt_timeline_unitno); env = getenv("DR_HOOK_TIMELINE_FREQ"); if (env) { opt_timeline_freq = atoi(env); } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TIMELINE_FREQ=%lld\n",pfx,TIMESTR(tid),FFL,opt_timeline_freq); env = getenv("DR_HOOK_TIMELINE_MB"); if (env) { opt_timeline_MB = atof(env); if (opt_timeline_MB < 0) opt_timeline_MB = 1.0; } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TIMELINE_MB=%g\n",pfx,TIMESTR(tid),FFL,opt_timeline_MB); } if (myproc == 1) { /* Only applicable for master MPI task for now */ env = getenv("DR_HOOK_TRACE_STACK"); if (env) { opt_trace_stack = atof(env); if (opt_trace_stack < 0) opt_trace_stack = 0; else { drhook_omp_stacksize = slave_stacksize(); if (drhook_omp_stacksize > 0) { drhook_stacksize_threshold = opt_trace_stack * drhook_omp_stacksize; opt_random_memstat = 1; random_memstat(1,1); OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TRACE_STACK=%g\n",pfx,TIMESTR(tid),FFL,opt_trace_stack); } else opt_trace_stack = 0; } } } if (!opt_random_memstat) { env = getenv("DR_HOOK_RANDOM_MEMSTAT"); if (env) { opt_random_memstat = atoi(env); if (opt_random_memstat < 0) opt_random_memstat = 0; if (opt_random_memstat > RAND_MAX) opt_random_memstat = RAND_MAX; random_memstat(1,1); } } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_RANDOM_MEMSTAT=%d (RAND_MAX=%d)\n",pfx,TIMESTR(tid),FFL,opt_random_memstat,RAND_MAX); env = getenv("DR_HOOK_HASHBITS"); if (env) { int value = atoi(env); if (value < 1) value = 1; else if (value > NHASHMAX) value = NHASHMAX; nhash = value; hashsize = HASHSIZE(nhash); hashmask = HASHMASK(nhash); } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_HASHBITS=%d\n",pfx,TIMESTR(tid),FFL,nhash); env = getenv("DR_HOOK_NCALLSTACK"); if (env) { int value = atoi(env); if (value < 1) value = NCALLSTACK; cstklen = value; } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_NCALLSTACK=%d\n",pfx,TIMESTR(tid),FFL,cstklen); env = getenv("DR_HOOK_HARAKIRI_TIMEOUT"); if (env) { int value = atoi(env); if (value < 1) value = drhook_harakiri_timeout_default; drhook_harakiri_timeout = value; } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_HARAKIRI_TIMEOUT=%d\n",pfx,TIMESTR(tid),FFL,drhook_harakiri_timeout); env = getenv("DR_HOOK_USE_LOCKFILE"); if (env) { int value = atoi(env); drhook_use_lockfile = (value != 0) ? 1 : 0; /* currently accept just 0 or 1 */ } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_USE_LOCKFILE=%d\n",pfx,TIMESTR(tid),FFL,drhook_use_lockfile); env = getenv("DR_HOOK_TRAPFPE"); if (env) { int value = atoi(env); drhook_trapfpe = (value != 0) ? 1 : 0; /* currently accept just 0 or 1 */ } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TRAPFPE=%d\n",pfx,TIMESTR(tid),FFL,drhook_trapfpe); env = getenv("DR_HOOK_TRAPFPE_INVALID"); if (env) { int value = atoi(env); drhook_trapfpe_invalid = (value != 0) ? 1 : 0; /* currently accept just 0 or 1 */ } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TRAPFPE_INVALID=%d\n",pfx,TIMESTR(tid),FFL,drhook_trapfpe_invalid); env = getenv("DR_HOOK_TRAPFPE_DIVBYZERO"); if (env) { int value = atoi(env); drhook_trapfpe_divbyzero = (value != 0) ? 1 : 0; /* currently accept just 0 or 1 */ } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TRAPFPE_DIVBYZERO=%d\n",pfx,TIMESTR(tid),FFL,drhook_trapfpe_divbyzero); env = getenv("DR_HOOK_TRAPFPE_OVERFLOW"); if (env) { int value = atoi(env); drhook_trapfpe_overflow = (value != 0) ? 1 : 0; /* currently accept just 0 or 1 */ } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TRAPFPE_OVERFLOW=%d\n",pfx,TIMESTR(tid),FFL,drhook_trapfpe_overflow); env = getenv("DR_HOOK_TIMED_KILL"); if (env) { drhook_timed_kill = strdup_drhook(env); } if (drhook_timed_kill) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_TIMED_KILL=%s\n",pfx,TIMESTR(tid),FFL,drhook_timed_kill); env = getenv("DR_HOOK_DUMP_SMAPS"); if (env) { ienv = atoi(env); drhook_dump_smaps = (ienv != 0) ? 1 : 0; } if (drhook_dump_smaps) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_DUMP_SMAPS=%d\n",pfx,TIMESTR(tid),FFL,drhook_dump_smaps); env = getenv("DR_HOOK_DUMP_MAPS"); if (env) { ienv = atoi(env); drhook_dump_maps = (ienv != 0) ? 1 : 0; } if (drhook_dump_maps) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_DUMP_MAPS=%d\n",pfx,TIMESTR(tid),FFL,drhook_dump_maps); env = getenv("DR_HOOK_DUMP_BUDDYINFO"); if (env) { ienv = atoi(env); drhook_dump_buddyinfo = (ienv != 0) ? 1 : 0; } if (drhook_dump_buddyinfo) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_DUMP_BUDDYINFO=%d\n",pfx,TIMESTR(tid),FFL,drhook_dump_buddyinfo); env = getenv("DR_HOOK_DUMP_MEMINFO"); if (env) { ienv = atoi(env); drhook_dump_meminfo = (ienv != 0) ? 1 : 0; } if (drhook_dump_meminfo) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_DUMP_MEMINFO=%d\n",pfx,TIMESTR(tid),FFL,drhook_dump_meminfo); env = getenv("DR_HOOK_DUMP_HUGEPAGES"); if (env) { double freq; int nel = sscanf(env,"%d,%lf",&ienv,&freq); if (nel == 2) { drhook_dump_hugepages = (freq > 0 && (ienv == -1 || ienv == myproc)) ? ienv : 0; if (drhook_dump_hugepages) drhook_dump_hugepages_freq = freq; } } if (drhook_dump_hugepages) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_DUMP_HUGEPAGES=%d,%.6f\n",pfx,TIMESTR(tid),FFL, drhook_dump_hugepages,drhook_dump_hugepages_freq); env = getenv("DR_HOOK_GENCORE"); if (env) { opt_gencore = atoi(env); } if (opt_gencore) { OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_GENCORE=%d\n",pfx,TIMESTR(tid),FFL,opt_gencore); env = getenv("DR_HOOK_GENCORE_SIGNAL"); if (env) { int itmp = atoi(env); if (itmp >= 1 && itmp <= NSIG && itmp != SIGABRT) { opt_gencore_signal = itmp; } } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_GENCORE_SIGNAL=%d\n",pfx,TIMESTR(tid),FFL,opt_gencore_signal); } env = getenv("DR_HOOK_HPMSTOP"); if (env) { char *s = strdup_drhook(env); long long int a; double b; int n = 0; env = s; while (*env) { if (isspace(*env) || *env == ',') *env = ' '; env++; } n = sscanf(s,"%lld %lf",&a,&b); if (n >= 1) opt_hpmstop_threshold = a; if (n >= 2) opt_hpmstop_mflops = b; OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_HPMSTOP=%lld,%.15g\n", pfx,TIMESTR(tid),FFL,opt_hpmstop_threshold,opt_hpmstop_mflops); free_drhook(s); } newline = 0; env = getenv("DR_HOOK_OPT"); if (env) { const char delim[] = ", \t/"; char *comma = " DR_HOOK_OPT=\""; char *s = strdup_drhook(env); char *p = s; while (*p) { if (islower(*p)) *p = toupper(*p); p++; } p = strtok(s,delim); /* if (p) OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_OPT=\"",pfx,TIMESTR(tid)); */ if (p && fp) { fprintf(fp,"%s %s [%s@%s:%d]",pfx,TIMESTR(tid),FFL); newline = 1; } while (p) { /* Assume that everything is OFF by default */ if (strequ(p,"ALL")) { /* all except profiler data */ opt_gethwm = opt_getstk = opt_getrss = opt_getpag = opt_walltime = opt_cputime = 1; opt_calls = 1; any_memstat++; OPTPRINT(fp,"%s%s",comma,"ALL"); comma = ","; } else if (strequ(p,"MEM") || strequ(p,"MEMORY")) { opt_gethwm = opt_getstk = opt_getrss = 1; opt_calls = 1; any_memstat++; OPTPRINT(fp,"%s%s",comma,"MEMORY"); comma = ","; } else if (strequ(p,"TIME") || strequ(p,"TIMES")) { opt_walltime = opt_cputime = 1; opt_calls = 1; OPTPRINT(fp,"%s%s",comma,"TIMES"); comma = ","; } else if (strequ(p,"HWM") || strequ(p,"HEAP")) { opt_gethwm = 1; opt_calls = 1; any_memstat++; OPTPRINT(fp,"%s%s",comma,"HEAP"); comma = ","; } else if (strequ(p,"STK") || strequ(p,"STACK")) { opt_getstk = 1; opt_calls = 1; any_memstat++; OPTPRINT(fp,"%s%s",comma,"STACK"); comma = ","; } else if (strequ(p,"RSS")) { opt_getrss = 1; opt_calls = 1; any_memstat++; OPTPRINT(fp,"%s%s",comma,"RSS"); comma = ","; } else if (strequ(p,"PAG") || strequ(p,"PAGING")) { opt_getpag = 1; opt_calls = 1; any_memstat++; OPTPRINT(fp,"%s%s",comma,"PAGING"); comma = ","; } else if (strequ(p,"WALL") || strequ(p,"WALLTIME")) { opt_walltime = 1; opt_calls = 1; OPTPRINT(fp,"%s%s",comma,"WALLTIME"); comma = ","; } else if (strequ(p,"CPU") || strequ(p,"CPUTIME")) { opt_cputime = 1; opt_calls = 1; OPTPRINT(fp,"%s%s",comma,"CPUTIME"); comma = ","; } else if (strequ(p,"CALLS") || strequ(p,"COUNT")) { opt_calls = 1; OPTPRINT(fp,"%s%s",comma,"CALLS"); comma = ","; } else if (strequ(p,"MEMPROF")) { opt_memprof = 1; drhook_memtrace = 1; opt_gethwm = opt_getstk = opt_getrss = 1; opt_getpag = 1; opt_calls = 1; any_memstat++; OPTPRINT(fp,"%s%s",comma,"MEMPROF"); comma = ","; } else if (strequ(p,"PROF") || strequ(p,"WALLPROF")) { opt_wallprof = 1; opt_walltime = 1; opt_cpuprof = 0; /* Note: Switches cpuprof OFF */ opt_calls = 1; OPTPRINT(fp,"%s%s",comma,"WALLPROF"); comma = ","; } else if (strequ(p,"CPUPROF")) { opt_cpuprof = 1; opt_cputime = 1; opt_wallprof = 0; /* Note: Switches walprof OFF */ opt_calls = 1; OPTPRINT(fp,"%s%s",comma,"CPUPROF"); comma = ","; } else if (strequ(p,"HPM") || strequ(p,"HPMPROF") || strequ(p,"MFLOPS")) { opt_hpmprof = 1; opt_wallprof = 1; /* Note: Implies wallprof (or prof), not cpuprof */ opt_walltime = 1; opt_cpuprof = 0; /* Note: Switches cpuprof OFF */ opt_calls = 1; OPTPRINT(fp,"%s%s",comma,"HPMPROF"); comma = ","; } else if (strequ(p,"TRIM")) { opt_trim = 1; OPTPRINT(fp,"%s%s",comma,"TRIM"); comma = ","; } else if (strequ(p,"SELF")) { opt_self = 2; OPTPRINT(fp,"%s%s",comma,"SELF"); comma = ","; } else if (strequ(p,"NOSELF")) { opt_self = 0; OPTPRINT(fp,"%s%s",comma,"NOSELF"); comma = ","; } else if (strequ(p,"NOPROP") || strequ(p,"NOPROPAGATE") || strequ(p,"NOPROPAGATE_SIGNALS")) { opt_propagate_signals = 0; OPTPRINT(fp,"%s%s",comma,"NOPROPAGATE_SIGNALS"); comma = ","; } else if (strequ(p,"NOSIZE") || strequ(p,"NOSIZEINFO")) { opt_sizeinfo = 0; OPTPRINT(fp,"%s%s",comma,"NOSIZEINFO"); comma = ","; } else if (strequ(p,"CLUSTER") || strequ(p,"CLUSTERINFO")) { opt_clusterinfo = 1; OPTPRINT(fp,"%s%s",comma,"CLUSTERINFO"); comma = ","; } else if (strequ(p,"CALLPATH")) { opt_callpath = 1; OPTPRINT(fp,"%s%s",comma,"CALLPATH"); comma = ","; } p = strtok(NULL,delim); } free_drhook(s); if (*comma == ',') { OPTPRINT(fp,"\"\n"); newline = 0; } if (newline) OPTPRINT(fp,"\n"); if (opt_callpath) { env = getenv("DR_HOOK_CALLPATH_INDENT"); if (env) { callpath_indent = atoi(env); if (callpath_indent < 1 || callpath_indent > 8) callpath_indent = callpath_indent_default; } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_CALLPATH_INDENT=%d\n",pfx,TIMESTR(tid),FFL,callpath_indent); env = getenv("DR_HOOK_CALLPATH_DEPTH"); if (env) { callpath_depth = atoi(env); if (callpath_depth < 0) callpath_depth = callpath_depth_default; } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_CALLPATH_DEPTH=%d\n",pfx,TIMESTR(tid),FFL,callpath_depth); env = getenv("DR_HOOK_CALLPATH_PACKED"); if (env) { callpath_packed = atoi(env); } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_CALLPATH_PACKED=%d\n",pfx,TIMESTR(tid),FFL,callpath_packed); env = getenv("DR_HOOK_CALLTRACE"); if (env) { opt_calltrace = atoi(env); } OPTPRINT(fp,"%s %s [%s@%s:%d] DR_HOOK_CALLTRACE=%d\n",pfx,TIMESTR(tid),FFL,opt_calltrace); } if (opt_wallprof || opt_cpuprof || opt_memprof || opt_timeline) { atexit(do_prof); } } else { if (opt_timeline) atexit(do_prof); } /* if (env) */ processed = 1; } /*--- trim ---*/ static const char * trim(const char *name, int *n) { const char *from; int len; int name_len = *n; while (*name && isspace(*name) && name_len > 0) { /* skip leading blanks */ name++; name_len--; } len = 0; from = name; while (*from && !isspace(*from) && name_len > 0) { /* find first space point, if any */ from++; len++; name_len--; } *n = len; if (!name) { /* Never actually called (unless a true fatality) */ ABOR1("***Fatal error in drhook.c:trim()-function"); } return name; } /*--- insertkey ---*/ static drhook_key_t * insertkey(int tid, const drhook_key_t *keyptr_in) { drhook_key_t *keyptr = NULL; if (tid >= 1 && tid <= numthreads) { /* no trimming available for this; just raw eval & insert */ unsigned int hash = hashfunc(keyptr_in->name, keyptr_in->name_len); keyptr = &keydata[tid-1][hash]; for (;;) { if (!keyptr->name) { /* A free slot */ memcpy(keyptr,keyptr_in,sizeof(*keyptr)); keyptr->next = NULL; break; } else { if (!keyptr->next) { keyptr->next = calloc_drhook(1, sizeof(drhook_key_t)); /* chaining */ } keyptr = keyptr->next; } /* if (!keyptr->name) ... else ... */ } /* for (;;) */ } /* if (tid >= 1 && tid <= numthreads) */ return keyptr; } /*--- getkey ---*/ static drhook_key_t * getkey(int tid, const char *name, int name_len, const char *filename, int filename_len, const double *walltime, const double *cputime, const equivalence_t *callpath, int callpath_len, int *free_callpath) { drhook_key_t *keyptr = NULL; if (tid >= 1 && tid <= numthreads) { unsigned int hash, fullhash; if (opt_trim) name = trim(name, &name_len); hash = hashfunc(name, name_len); if (callpath) { callpath_hashfunc(hash, callpath, callpath_len, &fullhash); #ifdef DEBUG fprintf(stderr, "getkey: name='%.*s', name_len=%d, callpath_len=%d, fullhash=%u\n", name_len, name, name_len, callpath_len, fullhash); #endif } keyptr = &keydata[tid-1][hash]; for (;;) { int found = 0; if (!keyptr->name) { /* A free slot */ keyptr->name = malloc_drhook((name_len+1)*sizeof(*name)); keyptr->name_len = name_len; if (opt_trim) { const char *from = name; char *to = keyptr->name; int len = name_len; for (; len>0; from++, len--) { *to++ = islower(*from) ? toupper(*from) : *from; } *to = 0; } else { memcpy(keyptr->name, name, name_len); keyptr->name[name_len] = 0; } if (filename_len > 0 && filename && *filename) { char *psave = NULL; char *p = psave = malloc_drhook((filename_len+1)*sizeof(*filename)); memcpy(p, filename, filename_len); p[filename_len] = 0; { /* Strip out dirname */ char *s = strrchr(p,'/'); if (s) p = s+1; } keyptr->filename = strdup_drhook(p); free_drhook(psave); } if (callpath) { if (free_callpath) *free_callpath = 0; keyptr->callpath = callpath; keyptr->callpath_len = callpath_len; keyptr->callpath_fullhash = fullhash; } found = 1; } if (found || (keyptr->name_len == name_len && (!callpath || (callpath && keyptr->callpath && keyptr->callpath_len == callpath_len && keyptr->callpath_fullhash == fullhash)) && ((!opt_trim && *keyptr->name == *name && strnequ(keyptr->name, name, name_len)) || (opt_trim && strncasecmp(keyptr->name, name, name_len) == 0)))) { if (opt_walltime) keyptr->wall_in = walltime ? *walltime : WALLTIME(); if (opt_cputime) keyptr->cpu_in = cputime ? *cputime : CPUTIME(); if (any_memstat) memstat(keyptr,&tid,1); if (opt_calls) { keyptr->calls++; keyptr->status++; } insert_calltree(tid, keyptr); break; /* for (;;) */ } else { if (!keyptr->next) { keyptr->next = calloc_drhook(1, sizeof(drhook_key_t)); /* chaining */ } keyptr = keyptr->next; } /* if (found ...) else ... */ } /* for (;;) */ curkeyptr[tid-1] = keyptr; } /* if (tid >= 1 && tid <= numthreads) */ return keyptr; } /*--- putkey ---*/ static void putkey(int tid, drhook_key_t *keyptr, const char *name, int name_len, int sizeinfo, double *walltime, double *cputime) { const int sig = SIGABRT; const char sl_name[] = "SIGABRT"; drhook_calltree_t *treeptr = (tid >= 1 && tid <= numthreads) ? thiscall[tid-1] : NULL; if (!treeptr || !treeptr->active || treeptr->keyptr != keyptr) { char *pfx = PREFIX(tid); char *s; unsigned int hash; if (opt_trim) name = trim(name, &name_len); hash = hashfunc(name, name_len); s = strdup2_drhook(name,name_len); if (opt_trim) { char *p = s; while (*p) { if (islower(*p)) *p = toupper(*p); p++; } } fprintf(stderr, "%s %s [%s@%s:%d] [signal#%d(%s)]: Dr.Hook has detected an invalid" " key-pointer/handle while leaving the routine '%s' [hash=%u]\n", pfx,TIMESTR(tid),FFL, sig,sl_name,s,hash); if (treeptr) { equivalence_t u; u.keyptr = treeptr->keyptr; hash = (u.keyptr && u.keyptr->name) ? hashfunc(u.keyptr->name,u.keyptr->name_len) : 0; fprintf(stderr, "%s %s [%s@%s:%d] [signal#%d(%s)]: Expecting the key-pointer=%p" " and treeptr->active-flag = 1\n", pfx,TIMESTR(tid),FFL, sig,sl_name,u.keyptr); fprintf(stderr, "%s %s [%s@%s:%d] [signal#%d(%s)]: A probable routine missing the closing" " DR_HOOK-call is '%s' [hash=%u]\n", pfx,TIMESTR(tid),FFL, sig,sl_name, (u.keyptr && u.keyptr->name) ? u.keyptr->name : NIL, hash); u.keyptr = keyptr; hash = (u.keyptr && u.keyptr->name) ? hashfunc(u.keyptr->name,u.keyptr->name_len) : 0; fprintf(stderr, "%s %s [%s@%s:%d] [signal#%d(%s)]: Got a key-pointer=%p" " and treeptr->active-flag = %d\n", pfx,TIMESTR(tid),FFL, sig,sl_name,u.keyptr,treeptr->active); fprintf(stderr, "%s %s [%s@%s:%d] [signal#%d(%s)]: This key-pointer maybe associated with" " the routine '%s' [hash=%u]\n", pfx,TIMESTR(tid),FFL, sig,sl_name, (u.keyptr && u.keyptr->name) ? u.keyptr->name : NIL, hash); u.keyptr = curkeyptr[tid-1]; hash = (u.keyptr && u.keyptr->name) ? hashfunc(u.keyptr->name,u.keyptr->name_len) : 0; fprintf(stderr, "%s %s [%s@%s:%d] [signal#%d(%s)]: The current key-pointer (=%p) thinks" " it maybe associated with the routine '%s' [hash=%u]\n", pfx,TIMESTR(tid),FFL, sig,sl_name, u.keyptr, (u.keyptr && u.keyptr->name) ? u.keyptr->name : NIL, hash); } free_drhook(s); fprintf(stderr, "%s %s [%s@%s:%d] [signal#%d(%s)]: Aborting...\n", pfx,TIMESTR(tid),FFL, sig,sl_name); RAISE(SIGABRT); } else if (tid >= 1 && tid <= numthreads) { double delta_wall = 0; double delta_cpu = 0; if (any_memstat) memstat(keyptr,&tid,0); if (opt_calls) keyptr->status--; if (opt_sizeinfo && sizeinfo > 0) { if (keyptr->sizeinfo == 0) { /* First time */ keyptr->min_sizeinfo = sizeinfo; keyptr->max_sizeinfo = sizeinfo; } else { keyptr->min_sizeinfo = MIN(keyptr->min_sizeinfo, sizeinfo); keyptr->max_sizeinfo = MAX(keyptr->max_sizeinfo, sizeinfo); } keyptr->sizeinfo += sizeinfo; } if (opt_cputime && cputime) { *cputime = CPUTIME(); delta_cpu = *cputime - keyptr->cpu_in; } if (opt_walltime && walltime) { *walltime = WALLTIME(); delta_wall = *walltime - keyptr->wall_in; } if (opt_walltime) keyptr->delta_wall_all += delta_wall; if (opt_cputime) keyptr->delta_cpu_all += delta_cpu; remove_calltree(tid, keyptr, &delta_wall, &delta_cpu); } } /*--- init_drhook ---*/ static void init_drhook(int ntids) { if (numthreads == 0 || !keydata || !calltree || !keyself || !overhead || !curkeyptr || !cstk) { int j; if (pid == -1) { /* Ensure that just called once */ { /* Invoke once : timers, memory counters etc. to "wake them up" */ (void) WALLTIME(); (void) CPUTIME(); (void) gethwm_(); (void) getmaxhwm_(); (void) getrss_(); (void) getmaxrss_(); (void) getstk_(); (void) getmaxstk_(); (void) getpag_(); } #ifdef RS6K irtc_start = irtc(); #endif #ifdef CRAYXT dclock_start = dclock(); #endif #if defined(SV2) || defined(XD1) || defined(XT3) #if defined(SV2) irtc_start = _rtc(); #else irtc_start = irtc_(); #endif my_irtc_rate = irtc_rate_(); my_inv_irtc_rate = 1.0/my_irtc_rate; #endif start_stamp = timestamp(); { char *env = getenv("DR_HOOK_SHOW_LOCK"); /* export DR_HOOK_SHOW_LOCK=1 to show the lock-info */ int konoff = env ? atoi(env) : 0; int kret = 0; if (konoff == 1) coml_set_debug_(&konoff, &kret); INIT_LOCKID_WITH_NAME(&DRHOOK_lock,"drhook.c:DRHOOK_lock"); if (kret != 0) { konoff = 0; coml_set_debug_(&konoff, &kret); } } #if defined(NECSX) { /* If C-programs compiled with -traceback, then NEC/F90 MESPUT-call will also includes C-routines in the traceback if in addition 'export C_TRACEBACK=YES' */ char *env = getenv("C_TRACEBACK"); if (!env) { /* Override only if C_TRACEBACK hadn't already been defined */ static char s[] = "C_TRACEBACK=YES"; /* note: must be static */ putenv(s); } } #endif ec_set_umask_(); pid = getpid(); signal_drhook_init(1); /* myproc gets set .. if not earlier */ process_options(); set_timed_kill(); drhook_lhook = 1; } if (!keydata) { keydata = malloc_drhook(sizeof(**keydata) * ntids); for (j=0; j<ntids; j++) { keydata[j] = calloc_drhook(hashsize, sizeof(drhook_key_t)); } } if (!cstk) { cstk = calloc_drhook(ntids, sizeof(**cstk)); } if (!calltree) { calltree = malloc_drhook(sizeof(**calltree) * ntids); thiscall = malloc_drhook(sizeof(**thiscall) * ntids); for (j=0; j<ntids; j++) { thiscall[j] = calltree[j] = calloc_drhook(1,sizeof(drhook_calltree_t)); } } if (!keyself && opt_self && (opt_wallprof || opt_cpuprof || opt_hpmprof)) { const char *name = "$drhook"; int name_len = strlen(name); keyself = malloc_drhook(sizeof(**keyself) * ntids); for (j=0; j<ntids; j++) { drhook_key_t *keyptr = keyself[j] = calloc_drhook(1,sizeof(drhook_key_t)); keyptr->name = strdup_drhook(name); keyptr->name_len = name_len; } } if (!overhead) { overhead = calloc_drhook(ntids,sizeof(*overhead)); } if (!curkeyptr) { curkeyptr = malloc_drhook(sizeof(**curkeyptr) * ntids); for (j=0; j<ntids; j++) { curkeyptr[j] = NULL; } } numthreads = ntids; if (!timeline) { if (opt_timeline_unitno >= 0 && opt_timeline_freq >= 1 && (opt_timeline == myproc || opt_timeline == -1)) { timeline = calloc_drhook(ntids, sizeof(*timeline)); } if (timeline) drhook_memtrace = 1; if (timeline) { /* The first timeline-call */ const int ftnunitno = opt_timeline_unitno; const int master = 1; const int print_option = +7; int initlev = 0; c_drhook_print_(&ftnunitno, &master, &print_option, &initlev); } } init_hpm(1); /* First thread */ } } /*-- overhead-macro --*/ #define OVERHEAD(tid,walltime_in,cputime_in,delta,calc_delta) \ if (overhead && tid >= 1 && tid <= numthreads) { \ if (calc_delta) { \ if (opt_walltime) delta = WALLTIME() - walltime_in; \ else if (opt_cputime) delta = CPUTIME() - cputime_in; \ else delta = 0; \ } \ overhead[tid-1] += delta; \ } /*--- itself ---*/ #define ITSELF_0 \ double delta = 0; \ drhook_key_t *keyptr_self = keyself ? itself(NULL,*thread_id,0,NULL,&walltime,&cputime) : NULL; #define ITSELF_1 \ if (keyptr_self) { \ (void) itself(keyptr_self,*thread_id,1,&delta,&walltime,&cputime); \ if (opt_wallprof) u.keyptr->delta_wall_child += delta; \ else u.keyptr->delta_cpu_child += delta; \ OVERHEAD(*thread_id,walltime,cputime,delta,0); \ } \ else { \ OVERHEAD(*thread_id,walltime,cputime,delta,1); \ } static drhook_key_t * itself(drhook_key_t *keyptr_self, int tid, int opt, double *delta_time, const double *walltime, const double *cputime) { drhook_key_t *keyptr = NULL; if (keyself) { keyptr = keyptr_self ? keyptr_self : keyself[tid-1]; if (opt == 0) { if (opt_wallprof) keyptr->wall_in = walltime ? *walltime : WALLTIME(); else keyptr->cpu_in = cputime ? *cputime : CPUTIME(); keyptr->calls++; } else if (opt == 1) { double delta = 0; if (opt_wallprof) { delta = walltime ? (*walltime - keyptr->wall_in) : (WALLTIME() - keyptr->wall_in); keyptr->delta_wall_all += delta; } else { delta = cputime ? (*cputime - keyptr->cpu_in) : (CPUTIME() - keyptr->cpu_in); keyptr->delta_cpu_all += delta; } if (delta_time) *delta_time = delta; } } return keyptr; } /*--- commie -routines : adds "," i.e. comma after each 3 digit, e.g.: 1234567890 becomes more readable 1,234,567,890 */ static void lld_commie(long long int n, char sd[]) { const char comma = ','; char s[DRHOOK_STRBUF]; char *p; int len, ncommas; sprintf(s,"%lld",n); len = strlen(s); ncommas = (len-1)/3; if (ncommas > 0) { char *pd = sd + len + ncommas; *pd-- = 0; p = s + len - 1; len = 0; while (p-s >= 0) { *pd-- = *p--; len++; if (p-s >= 0 && len%3 == 0) *pd-- = comma; } } else { strcpy(sd,s); } } static void dbl_commie(double n, char sd[]) { const char comma = ','; char s[DRHOOK_STRBUF]; char *p; int len, ncommas; sprintf(s,"%.0f",n); len = strlen(s); ncommas = (len-1)/3; if (ncommas > 0) { char *pd = sd + len + ncommas; *pd-- = 0; p = s + len - 1; len = 0; while (p-s >= 0) { *pd-- = *p--; len++; if (p-s >= 0 && len%3 == 0) *pd-- = comma; } } else { strcpy(sd,s); } } /*--- callpath as a "pathname" ---*/ static void unroll_callpath(FILE *fp, int len, const equivalence_t *callpath, int callpath_len) { if (fp && callpath && callpath_len > 0) { int j; for (j=0; j<callpath_len; callpath++, j++) { if (callpath && callpath->keyptr && callpath->keyptr->name) { const char *name = callpath->keyptr->name; int name_len = callpath->keyptr->name_len; len -= callpath_indent; if (len < 0) len = 0; fprintf(fp,"\n%*s%.*s",len," ",name_len,name); } #ifdef DEBUG else { fprintf(fp, "\n????callpath=%p, callpath->keyptr=%p, callpath->keyptr->name='%s'", callpath, callpath ? callpath->keyptr : 0, (callpath && callpath->keyptr && callpath->keyptr->name) ? callpath->keyptr->name : NIL); } #endif } } /* if (fp) */ } static equivalence_t * get_callpath(int tid, int *callpath_len) { int depth = 0; equivalence_t *callpath = NULL; if (tid >= 1 && tid <= numthreads) { const drhook_calltree_t *treeptr = thiscall[tid-1]; while (treeptr && treeptr->active && depth < callpath_depth) { depth++; treeptr = treeptr->prev; } if (depth > 0) { int j = 0; callpath = malloc_drhook(sizeof(*callpath) * depth); treeptr = thiscall[tid-1]; while (treeptr && treeptr->active && j < callpath_depth) { callpath[j].keyptr = treeptr->keyptr; j++; treeptr = treeptr->prev; } } /* if (depth > 0) */ } /* if (tid >= 1 && tid <= numthreads) */ if (callpath_len) *callpath_len = depth; return callpath; } /*--- profiler output ---*/ static int do_prof_off = 0; static void do_prof() { /* to avoid recursive signals while atexit() (e.g. SIGXCPU) */ if (signal_handler_ignore_atexit) return; if (!do_prof_off && (opt_wallprof || opt_cpuprof)) { /* CPU, wall-clock and/or MFlop/s profiling */ const int ftnunitno = 0; const int master = 1; const int print_option = 3; int initlev = 0; c_drhook_print_(&ftnunitno, &master, &print_option, &initlev); } if (!do_prof_off && opt_memprof) { /* Memory profiling */ const int ftnunitno = 0; const int master = 1; const int print_option = 4; int initlev = 0; c_drhook_print_(&ftnunitno, &master, &print_option, &initlev); } if (!do_prof_off && timeline) { /* The last timeline-call */ const int ftnunitno = opt_timeline_unitno; const int master = 1; const int print_option = -7; int initlev = 0; c_drhook_print_(&ftnunitno, &master, &print_option, &initlev); } } void c_drhook_prof_() { if (ec_drhook) { do_prof(); do_prof_off = 1; } } /*--- Check watch points ---*/ // Forward declarations of subroutines defined in dr_hook_prt.F90 void dr_hook_prt_logical_( const int* kunit, const void* ptr, const int* n ); void dr_hook_prt_char_( const int* kunit, const void* ptr, const int* n ); void dr_hook_prt_i4_( const int* kunit, const void* ptr, const int* n ); void dr_hook_prt_i8_( const int* kunit, const void* ptr, const int* n ); void dr_hook_prt_r4_( const int* kunit, const void* ptr, const int* n ); void dr_hook_prt_r8_( const int* kunit, const void* ptr, const int* n ); typedef enum { /* See dr_hook_watch_mod.F90 */ KEYNONE = 0, KEYLOG = 1, KEYCHAR = 2, KEY_I4 = 4, KEY_I8 = 8, KEY_R4 = 16, KEY_R8 = 32 } PrintWatchKeys_t; static void print_watch(int ftnunitno, int key, const void *ptr, int n) { if (ptr && key > KEYNONE && n > 0) { int nmax = n; if (key == KEYLOG) { dr_hook_prt_logical_(&ftnunitno, ptr, &nmax); } else if (key == KEYCHAR) { dr_hook_prt_char_(&ftnunitno, ptr, &nmax); } else if (key == KEY_I4) { dr_hook_prt_i4_(&ftnunitno, ptr, &nmax); } else if (key == KEY_I8) { dr_hook_prt_i8_(&ftnunitno, ptr, &nmax); } else if (key == KEY_R4) { dr_hook_prt_r4_(&ftnunitno, ptr, &nmax); } else if (key == KEY_R8) { dr_hook_prt_r8_(&ftnunitno, ptr, &nmax); } } } static void check_watch(const char *label, const char *name, int name_len, int allow_abort) { if (watch) { int print_traceback = 1; drhook_watch_t *p = watch; coml_set_lockid_(&DRHOOK_lock); while (p) { if (p->active) { unsigned int crc32 = 0; int calc_crc = 0; const char *first_nbytes = p->ptr; int changed = memcmp(first_nbytes,p->ptr,p->watch_first_nbytes); if (!changed) { /* The first nbytes were still the same; checking if crc has changed ... */ crc32_(p->ptr, &p->nbytes, &crc32); changed = (crc32 != p->crc32); calc_crc = 1; } if (changed) { int tid = get_thread_id_(); char *pfx = PREFIX(tid); if (!calc_crc) crc32_(p->ptr, &p->nbytes, &crc32); fprintf(stderr, "%s %s [%s@%s:%d] ***%s: Changed watch point '%s' at %p (%d bytes [#%d values])" " -- %s %.*s : new crc32=%u\n", pfx,TIMESTR(tid),FFL, p->abort_if_changed ? "Error" : "Warning", p->name, p->ptr, p->nbytes, p->nvals, label, name_len, name, crc32); print_watch(0, p->printkey, p->ptr, p->nvals); if (print_traceback) { LinuxTraceBack(pfx,TIMESTR(tid),NULL); print_traceback = 0; } if (allow_abort && p->abort_if_changed) { coml_unset_lockid_(&DRHOOK_lock); /* An important unlocking on Linux; otherwise hangs (until time-out) */ RAISE(SIGABRT); } #if 0 p->active = 0; /* No more these messages for this array */ watch_count--; #else p->crc32 = crc32; #endif } } p = p->next; } /* while (p) */ coml_unset_lockid_(&DRHOOK_lock); } } void c_drhook_check_watch_(const char *where, const int *allow_abort /* Hidden length */ , int where_len) { if (watch && watch_count > 0) check_watch("whilst at", where, where_len, *allow_abort); } /*** PUBLIC ***/ #define TIMERS \ double walltime = opt_walltime ? WALLTIME() : 0; \ double cputime = opt_cputime ? CPUTIME() : 0; \ long long int hwm = opt_gethwm ? gethwm_() : 0; \ long long int stk = opt_getstk ? getstk_() : 0 /*=== c_drhook_set_lhook_ ===*/ void c_drhook_set_lhook_(const int *lhook) { if (lhook) drhook_lhook = *lhook; } /*=== c_drhook_getenv_ ===*/ void c_drhook_getenv_(const char *s, char *value, /* Hidden arguments */ int slen, const int valuelen) { char *env = NULL; char *p = malloc_drhook(slen+1); if (!p) { fprintf(stderr,"c_drhook_getenv_(): Unable to allocate %d bytes of memory\n", slen+1); RAISE(SIGABRT); } memcpy(p,s,slen); p[slen]='\0'; memset(value, ' ', valuelen); env = getenv(p); if (env) { int len = strlen(env); if (valuelen < len) len = valuelen; memcpy(value,env,len); } free_drhook(p); } /*=== c_drhook_init_ ===*/ void c_drhook_init_(const char *progname, const int *num_threads /* Hidden length */ ,int progname_len) { init_drhook(*num_threads); max_threads = MAX(1,*num_threads); if (a_out) free_drhook(a_out); progname = trim(progname, &progname_len); if (progname_len > 0) { a_out = calloc_drhook(progname_len+1,sizeof(*progname)); memcpy(a_out, progname, progname_len); } else { /* progname is a blank string; this is most likely due to a Fortran-call to getarg from program that has a C-main program, thus Fortran getarg may return a blank string */ const char *arg0 = ec_GetArgs(0); if (arg0) { const char *pc = arg0; progname_len = strlen(pc); pc = trim(pc, &progname_len); a_out = strdup_drhook(pc); } } if (!a_out) { a_out = strdup_drhook("a.out"); /* Failed to obtain the name of the executing program */ } } /*=== c_drhook_watch_ ===*/ void c_drhook_watch_(const int *onoff, const char *array_name, const void *array_ptr, const int *nbytes, const int *abort_if_changed, const int *printkey, const int *nvals, const int *print_traceback_when_set /* Hidden length */ ,int array_name_len) { int tid = get_thread_id_(); drhook_watch_t *p = NULL; if (!drhook_lhook) return; coml_set_lockid_(&DRHOOK_lock); /* check whether this array_ptr is already registered, but maybe inactive */ p = watch; while (p) { if (p->ptr == array_ptr) { if (p->active) watch_count--; free_drhook(p->name); break; } p = p->next; } if (!p) { /* create new branch */ p = calloc_drhook(1, sizeof(*p)); /* Implies p->next = NULL */ if (!last_watch) { last_watch = watch = p; } else { last_watch->next = p; last_watch = p; } } p->name = strdup2_drhook(array_name,array_name_len); p->tid = tid; p->active = *onoff; if (p->active) watch_count++; p->abort_if_changed = *abort_if_changed; p->ptr = array_ptr; p->nbytes = *nbytes; p->watch_first_nbytes = MIN(p->nbytes, MAX_WATCH_FIRST_NBYTES); memcpy(p->first_nbytes,p->ptr,p->watch_first_nbytes); p->crc32 = 0; crc32_(p->ptr, &p->nbytes, &p->crc32); p->printkey = *printkey; p->nvals = *nvals; { char *pfx = PREFIX(p->tid); int ftnunitno = 0; int textlen = strlen(pfx) + strlen(p->name) + 256; char *text = malloc_drhook(textlen * sizeof(*text)); snprintf(text,textlen, "%s ***Warning: Set watch point '%s' at %p (%d bytes [%d values]) : crc32=%u", pfx, p->name, p->ptr, p->nbytes, p->nvals, p->crc32); dr_hook_prt_(&ftnunitno, text, strlen(text)); print_watch(ftnunitno, p->printkey, p->ptr, p->nvals); free_drhook(text); if (*print_traceback_when_set) LinuxTraceBack(pfx,TIMESTR(p->tid),NULL); } coml_unset_lockid_(&DRHOOK_lock); } /*=== c_drhook_start_ ===*/ void c_drhook_start_(const char *name, const int *thread_id, double *key, const char *filename, const int *sizeinfo /* Hidden length */ ,int name_len, int filename_len) { TIMERS; equivalence_t u; ITSELF_0; if (!signals_set) signal_drhook_init(1); if (name_len > 0 && opt_funcenter == *thread_id) { fprintf(stdout,"<e> %d %d %.*s %lld %lld\n",myproc,*thread_id,name_len,name,hwm,stk); fflush(stdout); } if (watch && watch_count > 0) check_watch("when entering routine", name, name_len, 1); if (drhook_dump_hugepages) { int tid = *thread_id; char *pfx = PREFIX(tid); dump_hugepages(0,pfx,tid,0,-1); } if (!opt_callpath) { u.keyptr = getkey(*thread_id, name, name_len, filename, filename_len, &walltime, &cputime, NULL, 0, NULL); } else { /* (Much) more overhead */ int free_callpath = 1; int callpath_len = 0; equivalence_t *callpath = get_callpath(*thread_id, &callpath_len); u.keyptr = getkey(*thread_id, name, name_len, filename, filename_len, &walltime, &cputime, callpath, callpath_len, &free_callpath); if (free_callpath) free_drhook(callpath); } if (cstklen == 0) { /* Double precision */ *key = u.d; } else { /* Single precision : The variable "*key" is treated like max 4-byte entity -- "an index" */ (void) callstack(*thread_id, key, u.keyptr); } ITSELF_1; if (opt_calltrace) { coml_set_lockid_(&DRHOOK_lock); { const int ftnunitno = 0; /* stderr */ const int print_option = 2; /* calling tree */ int level = 0; c_drhook_print_(&ftnunitno, thread_id, &print_option, &level); /* fprintf(stderr,"%d#%d> %*.*s [%llu]\n",myproc,*thread_id,name_len,name_len,name,u.ull); */ } coml_unset_lockid_(&DRHOOK_lock); } if (timeline) { int tid = *thread_id; if (opt_timeline_thread <= 0 || tid <= opt_timeline_thread) { drhook_timeline_t *tl = &timeline[tid-1]; int bigjump = 1; unsigned long long int mod = (tl->calls[0]++)%opt_timeline_freq; double rss = (double)(getrss_()/1048576.0); /* in MBytes */ double curheap = (opt_timeline_thread == 1 && tid == 1) ? (double)(getcurheap_()/1048576.0) : (double)(getcurheap_thread_(&tid)/1048576.0); /* in MBytes */ double stack = (double)(getstk_()/1048576.0); /* in MBytes */ double vmpeak = (double)(getvmpeak_()/1048576.0); /* in MBytes */ if (mod != 0) { double inc_MB; inc_MB = tl->last_rss_MB - rss; if (ABS(inc_MB) < opt_timeline_MB) inc_MB = tl->last_curheap_MB - curheap; if (ABS(inc_MB) < opt_timeline_MB) inc_MB = tl->last_stack_MB - stack; if (ABS(inc_MB) < opt_timeline_MB) inc_MB = tl->last_vmpeak_MB - vmpeak; if (ABS(inc_MB) < opt_timeline_MB) bigjump = 0; } if (mod == 0 || bigjump) { coml_set_lockid_(&DRHOOK_lock); { int ftnunitno = opt_timeline_unitno; const int print_option = 5; /* calling "tree" with just the current entry */ int level = 0; tl->last_rss_MB = rss; tl->last_curheap_MB = curheap; tl->last_stack_MB = stack; tl->last_vmpeak_MB = vmpeak; c_drhook_print_(&ftnunitno, &tid, &print_option, &level); } coml_unset_lockid_(&DRHOOK_lock); } } /* if (opt_timeline_thread <= 0 || tid <= opt_timeline_thread) */ } if (opt_random_memstat > 0) random_memstat(*thread_id,0); } /*=== c_drhook_end_ ===*/ void c_drhook_end_(const char *name, const int *thread_id, const double *key, const char *filename, const int *sizeinfo /* Hidden length */ ,int name_len, int filename_len) { TIMERS; equivalence_t u; ITSELF_0; if (cstklen == 0) { /* Double precision */ u.d = *key; } else { /* Single precision : The variable "*key" is treated like max 4-byte entity -- "an index" */ u.keyptr = callstack(*thread_id, (void *)key, NULL); } /* if (opt_calltrace) { coml_set_lockid_(&DRHOOK_lock); fprintf(stderr,"%d#%d< %*.*s [%llu]\n",myproc,*thread_id,name_len,name_len,name,u.ull); coml_unset_lockid_(&DRHOOK_lock); } */ if (name_len > 0 && opt_funcexit == *thread_id) { fprintf(stdout,"<x> %d %d %.*s %lld %lld\n",myproc,*thread_id,name_len,name,hwm,stk); fflush(stdout); } if (timeline) { int tid = *thread_id; if (opt_timeline_thread <= 0 || tid <= opt_timeline_thread) { drhook_timeline_t *tl = &timeline[tid-1]; int bigjump = 1; unsigned long long int mod = (tl->calls[1]++)%opt_timeline_freq; double rss = (double)(getrss_()/1048576.0); /* in MBytes */ double curheap = (opt_timeline_thread == 1 && tid == 1) ? (double)(getcurheap_()/1048576.0) : (double)(getcurheap_thread_(&tid)/1048576.0); /* in MBytes */ double stack = (double)(getstk_()/1048576.0); /* in MBytes */ double vmpeak = (double)(getvmpeak_()/1048576.0); /* in MBytes */ if (mod != 0) { double inc_MB; inc_MB = tl->last_rss_MB - rss; if (ABS(inc_MB) < opt_timeline_MB) inc_MB = tl->last_curheap_MB - curheap; if (ABS(inc_MB) < opt_timeline_MB) inc_MB = tl->last_stack_MB - stack; if (ABS(inc_MB) < opt_timeline_MB) inc_MB = tl->last_vmpeak_MB - vmpeak; if (ABS(inc_MB) < opt_timeline_MB) bigjump = 0; } if (mod == 0 || bigjump) { coml_set_lockid_(&DRHOOK_lock); { int ftnunitno = opt_timeline_unitno; const int print_option = -5; /* calling "tree" with just the current entry */ int level = 0; tl->last_rss_MB = rss; tl->last_curheap_MB = curheap; tl->last_stack_MB = stack; tl->last_vmpeak_MB = vmpeak; c_drhook_print_(&ftnunitno, &tid, &print_option, &level); } coml_unset_lockid_(&DRHOOK_lock); } } /* if (opt_timeline_thread <= 0 || tid <= opt_timeline_thread) */ } if (watch && watch_count > 0) check_watch("when leaving routine", name, name_len, 1); putkey(*thread_id, u.keyptr, name, name_len, *sizeinfo, &walltime, &cputime); ITSELF_1; } /*=== c_drhook_memcounter_ ===*/ void c_drhook_memcounter_(const int *thread_id, const long long int *size, long long int *keyptr_addr) { int tid = (thread_id && (*thread_id >= 1) && (*thread_id <= numthreads)) ? *thread_id : get_thread_id_(); int has_timeline = (timeline && size) ? opt_timeline : 0; if (has_timeline) { if (opt_timeline_thread <= 1 || tid <= opt_timeline_thread) { double size_MB = (double)((*size)/1048576.0); /* In MBytes */ if (ABS(size_MB) < opt_timeline_MB) has_timeline = 0; /* Do not report */ } else { has_timeline = 0; /* Do not report */ } } /* if (has_timeline) */ if (opt_memprof) { if (size) { union { long long int keyptr_addr; drhook_key_t *keyptr; } u; long long int alldelta; if (*size > 0) { /* Memory is being allocated */ if (curkeyptr[tid-1]) { drhook_key_t *keyptr = curkeyptr[tid-1]; keyptr->mem_curdelta += *size; alldelta = keyptr->mem_curdelta + keyptr->mem_child; if (alldelta > keyptr->maxmem_alldelta) keyptr->maxmem_alldelta = alldelta; if (keyptr->mem_curdelta > keyptr->maxmem_selfdelta) keyptr->maxmem_selfdelta = keyptr->mem_curdelta; if (keyptr_addr) { u.keyptr = keyptr; *keyptr_addr = u.keyptr_addr; } keyptr->alloc_count++; } else { if (keyptr_addr) *keyptr_addr = 0; } /* if (curkeyptr[tid-1]) */ /* fprintf(stderr, "memcounter: allocated %lld bytes ; *keyptr_addr = %lld\n", *size, *keyptr_addr); */ } else { /* Memory is being freed */ drhook_key_t *keyptr; if (keyptr_addr && (*keyptr_addr)) { u.keyptr_addr = *keyptr_addr; keyptr = u.keyptr; } else keyptr = curkeyptr[tid-1]; /* fprintf(stderr, "memcounter: DE-allocated %lld bytes ; *keyptr_addr = %lld\n", *size, *keyptr_addr); */ if (keyptr) { long long int prev_curdelta = keyptr->mem_curdelta; keyptr->mem_curdelta += *size; alldelta = prev_curdelta + keyptr->mem_child; if (alldelta > keyptr->maxmem_alldelta) keyptr->maxmem_alldelta = alldelta; if (*size < 0) keyptr->free_count++; } /* if (keyptr) */ } /* if (*size > 0) ... else */ } /* if (size) */ } /* if (opt_memprof) */ if (has_timeline) { double curheap = (opt_timeline_thread == 1 && tid == 1) ? (double)(getcurheap_()/1048576.0) : (double)(getcurheap_thread_(&tid)/1048576.0); /* in MBytes */ double rss = (double)(getrss_()/1048576.0); /* in MBytes */ double stack = (double)(getstk_()/1048576.0); /* in MBytes */ double vmpeak = (double)(getvmpeak_()/1048576.0); /* in MBytes */ coml_set_lockid_(&DRHOOK_lock); { int ftnunitno = opt_timeline_unitno; double size_MB = (double)((*size)/1048576.0); /* In MBytes */ int print_option = (size_MB > 0) ? 6 : -6; /* timeline upon c_drhook_memcounter_ & (big) ALLOCATE or DEALLOCATE */ int level = 0; drhook_timeline_t *tl = &timeline[tid-1]; tl->last_curheap_MB = curheap; tl->last_rss_MB = rss; tl->last_stack_MB = stack; tl->last_vmpeak_MB = vmpeak; c_drhook_print_(&ftnunitno, &tid, &print_option, &level); } coml_unset_lockid_(&DRHOOK_lock); } /* if (has_timeline) */ } /*=== c_drhook_print_ ===*/ #define PRINT_HWM() \ if (opt_gethwm) { sprintf(s,",hwm=%lldK",keyptr->hwm/1024); s += strlen(s); } #define PRINT_RSS() \ if (opt_getrss) { \ sprintf(s,",rss/max=%lldK/%lldK",keyptr->rssnow/1024, keyptr->maxrss/1024); \ s += strlen(s); \ } #define PRINT_STK() \ if (opt_getstk) { \ sprintf(s,",stack/max=%lldK/%lldK",keyptr->stack/1024, keyptr->maxstack/1024); \ s += strlen(s); \ } #define PRINT_PAG() \ if (opt_getpag) { \ sprintf(s,",pag=%lld",keyptr->paging); \ s += strlen(s); \ } #define PRINT_WALL() \ if (opt_walltime) { \ double self = keyptr->delta_wall_all-keyptr->delta_wall_child; \ if (self < 0) self = 0; \ sprintf(s,",wall=%.3fs/%.3fs", \ keyptr->delta_wall_all, self); \ s += strlen(s); \ } #define PRINT_CPU() \ if (opt_cputime) { \ double self = keyptr->delta_cpu_all-keyptr->delta_cpu_child; \ if (self < 0) self = 0; \ sprintf(s,",cpu=%.3fs/%.3fs", \ keyptr->delta_cpu_all, self); \ s += strlen(s); \ } #define PRINT_CALLS() \ if (opt_calls) { \ sprintf(s,",#%llu,st=%d",keyptr->calls,keyptr->status); \ s += strlen(s); \ } static int prof_name_comp(const void *v1, const void *v2) { const drhook_prof_t *p1 = v1; const drhook_prof_t *p2 = v2; return strcmp(p1->name,p2->name); } static int memprof_name_comp(const void *v1, const void *v2) { const drhook_memprof_t *p1 = v1; const drhook_memprof_t *p2 = v2; return strcmp(p1->name,p2->name); } static int prof_pc_comp_desc(const void *v1, const void *v2) { const drhook_prof_t *p1 = v1; const drhook_prof_t *p2 = v2; if (p1->pc < p2->pc) return 1; else if (p1->pc > p2->pc) return -1; else return 0; } static int memprof_pc_comp_desc(const void *v1, const void *v2) { const drhook_memprof_t *p1 = v1; const drhook_memprof_t *p2 = v2; if (p1->pc < p2->pc) return 1; else if (p1->pc > p2->pc) return -1; else return 0; } static const char * trim_and_adjust_left(const char *p, int *name_len) { int len = strlen(p); if (len > 0) { const char *back = &p[len-1]; while (len > 0 && *back-- == ' ') len--; while (len > 0 && *p == ' ') { p++; len--; } } if (name_len) *name_len = len; return p; } static void print_routine_name0(FILE * fp, const char * p_name, int p_tid, const char * p_filename, int p_cluster, const equivalence_t * p_callpath, int p_callpath_len, int len, int cluster_size) { int name_len = 0; const char *name = trim_and_adjust_left(p_name,&name_len); if (callpath_packed) { if (p_callpath && p_callpath_len > 0) { const equivalence_t * callpath = &p_callpath[p_callpath_len-1]; int j; for (j=0; j<p_callpath_len; callpath--, j++) if (callpath && callpath->keyptr && callpath->keyptr->name) { const char *name = callpath->keyptr->name; int name_len = callpath->keyptr->name_len; fprintf(fp,"%.*s/",name_len,name); } } } fprintf(fp,"%.*s@%d%s%s", name_len, name, p_tid, p_filename ? ":" : "", p_filename ? p_filename : ""); if (opt_clusterinfo) { fprintf(fp," [%d,%d]", p_cluster, ABS(cluster_size)); } if (!callpath_packed) unroll_callpath(fp, len, p_callpath, p_callpath_len); } #define print_routine_name(fp, p, len, cluster_size) \ if (fp && p) { \ print_routine_name0(fp, p->name, p->tid, p->filename, p->cluster, \ p->callpath, p->callpath_len, len, cluster_size);\ } /* if (fp && p) */ static void DrHookPrint(int ftnunitno, const char *line) { if (line) { FILE *fp = NULL; if (ftnunitno <= 0) fp = stderr; else if (ftnunitno == 6) fp = stdout; else dr_hook_prt_(&ftnunitno, line, strlen(line)); OPTPRINT(fp,"%s\n",line); } } void c_drhook_print_(const int *ftnunitno, const int *thread_id, const int *print_option, /* 1=raw call counts 2=calling tree 3=profiling info 4=memory profiling 5=timeline upon entering the routine -5=timeline upon leaving the routine 6=timeline upon c_drhook_memcounter_ & (big) ALLOCATE -6=timeline upon c_drhook_memcounter_ & (big) DEALLOCATE 7=timeline : the very first call (upon setup or dr.hook) -7=timeline : the very last call (in atexit()) */ int *level ) { static int first_time = 0; int tid = (thread_id && (*thread_id >= 1) && (*thread_id <= numthreads)) ? *thread_id : get_thread_id_(); int mytid = get_thread_id_(); char *pfx = PREFIX(tid); if (ftnunitno && keydata && calltree) { char line[4096]; int abs_print_option = ABS(*print_option); int j; /* Mod to call traceback and continue if called with level=99 */ if(*level == 99) { *level=0; } else { if(*print_option == 2) { if(first_time == 1) return; first_time = 1; } } /* end of Mod */ if (*print_option == 1) { /* raw call counts */ for (j=0; j<hashsize; j++) { int nestlevel = 0; drhook_key_t *keyptr = &keydata[tid-1][j]; while (keyptr) { if (keyptr->name) { char *s = line; sprintf(s, "%s %s [%s@%s:%d] [hash#%d,nest=%d] '%s'", pfx,TIMESTR(tid),FFL, j,nestlevel,keyptr->name); s += strlen(s); PRINT_CALLS(); PRINT_HWM(); PRINT_RSS(); PRINT_STK(); PRINT_PAG(); PRINT_WALL(); PRINT_CPU(); *s = 0; DrHookPrint(*ftnunitno, line); } keyptr = keyptr->next; nestlevel++; } /* while (keyptr) */ } /* for (j=0; j<hashsize; j++) */ } else if (*print_option == 2 || abs_print_option == 5 || abs_print_option == 6 || abs_print_option == 7 ) { /* the current calling tree */ drhook_calltree_t *treeptr = calltree[tid-1]; if (*print_option == 2) { long long int hwm = getmaxhwm_()/1048576; long long int rss = getmaxrss_()/1048576; long long int maxstack = getmaxstk_()/1048576; long long int vmpeak = getvmpeak_()/1048576; snprintf(line,sizeof(line), "%s %s [%s@%s:%d] %lld MB (maxheap), %lld MB (maxrss), %lld MB (maxstack), %lld MB (vmpeak)", pfx,TIMESTR(tid),FFL, hwm,rss,maxstack,vmpeak); DrHookPrint(*ftnunitno, line); } if (tid > 1) { if (*print_option == 2) { /* I'm not a master thread, but my master has the beginning of the calltree */ int initlev = 0; const int master = 1; first_time = 0; c_drhook_print_(ftnunitno, &master, print_option, &initlev); *level += initlev; } else if (tid > opt_timeline_thread) { return; } } if (abs_print_option == 7) { treeptr = NULL; } else if (abs_print_option == 5 || abs_print_option == 6) { treeptr = thiscall[tid-1]; } else { treeptr = calltree[tid-1]; } while (abs_print_option == 7 || (treeptr && treeptr->active)) { int do_print = (*print_option == 2 || abs_print_option == 7 || abs_print_option == 5 || abs_print_option == 6); if (do_print) { drhook_key_t *keyptr = (abs_print_option == 7) ? NULL : treeptr->keyptr; char *s = line; char is_timeline = 1, kind; switch (*print_option) { case -5: kind = '<'; break; case -6: kind = '-'; break; case -7: kind = 'E'; break; case 5: kind = '>'; break; case 6: kind = '+'; break; case 7: kind = 'B'; break; default: case 2: kind = ':'; is_timeline = 0; break; } if (*print_option == 2 || (is_timeline && tid > 1 && tid <= opt_timeline_thread)) { sprintf(s,"%s %s [%s@%s:%d] %s%c ", pfx,TIMESTR(tid),FFL, is_timeline ? "tl:" : "", kind); } else if (is_timeline && opt_timeline_thread == 1 && tid == 1) { sprintf(s,"%s %s [%s@%s:%d] %s%c ", pfx,TIMESTR(tid),FFL, is_timeline ? "tl:" : "", kind); } s += strlen(s); (*level)++; for (j=0; j<(*level); j++) *s++ = ' '; if (*print_option == 2) { if(mytid != tid) { /* We are printing the master call tree as far as >OMP*/ if(strncmp(">OMP",keyptr->name,4) == 0) { (*level)--; return; } } sprintf(s,"%s ",keyptr->name); s += strlen(s); } if (is_timeline) { double wall = WALLTIME(); double rss, curheap, stack, vmpeak; drhook_timeline_t *tl = &timeline[tid-1]; if (abs_print_option == 5 || abs_print_option == 6) { /* when called via drhook_begin/_end or memcounter */ curheap = tl->last_curheap_MB; rss = tl->last_rss_MB; stack = tl->last_stack_MB; vmpeak = tl->last_vmpeak_MB; } else { rss = (double)(getrss_()/1048576.0); /* in MBytes */ curheap = (opt_timeline_thread == 1 && tid == 1) ? (double)(getcurheap_()/1048576.0) : (double)(getcurheap_thread_(&tid)/1048576.0); /* in MBytes */ stack = (double)(getstk_()/1048576.0); /* in MBytes */ vmpeak = (double)(getvmpeak_()/1048576.0); /* in MBytes */ tl->last_curheap_MB = curheap; tl->last_rss_MB = rss; tl->last_stack_MB = stack; tl->last_vmpeak_MB = vmpeak; } if (opt_timeline_format == 1) { sprintf(s, "%.6f %.4g %.4g %.4g %.4g", wall, rss, curheap, stack, vmpeak); } else { sprintf(s, "wall=%.6f cpu=%.4g hwm=%.4g rss=%.4g curheap=%.4g stack=%.4g vmpeak=%.4g pag=%lld", wall, CPUTIME(), (double)(gethwm_()/1048576.0), rss, curheap, (double)(getstk_()/1048576.0), (double)(getvmpeak_()/1048576.0), getpag_()); } s += strlen(s); *s++ = ' '; if (keyptr) { sprintf(s,"'%s'",keyptr->name); } else { sprintf(s,"'#PROGRAM %s'",(*print_option == 7) ? "BEGIN" : "END"); } s += strlen(s); { int current_numth = 0; coml_get_num_threads_(&current_numth); sprintf(s,"[#%d]",current_numth); s += strlen(s); } } else { PRINT_CALLS(); PRINT_HWM(); PRINT_RSS(); PRINT_STK(); PRINT_PAG(); PRINT_WALL(); PRINT_CPU(); } *s = 0; DrHookPrint(*ftnunitno, line); } if (abs_print_option == 7 || abs_print_option == 5 || abs_print_option == 6) break; if (treeptr) treeptr = treeptr->next; } /* while (abs_print_option == 7 || (treeptr && treeptr->active)) */ } else if (*print_option == 3) { /* profiling (CPU, wall-clock and/or MFlop/s) */ int len; int t; double cumul; double tottime = 0, max_overhead_pc = 0; double *tot = NULL; int nprof = 0; drhook_prof_t *prof = NULL; drhook_prof_t *p; double flop_tot = 0, instr_tot = 0; double *flop = NULL, *instr = NULL; if (!opt_wallprof && !opt_cpuprof) return; /* no profiling info available */ if (tid > 1) return; /* just master thread allowed ; takes care of siblings, too */ if (numthreads<=0) return; if (do_prof_off) return; do_prof_off = 1; /* Insert "$drhook" */ if (keyself && opt_self > 1) { for (t=0; t<numthreads; t++) (void) insertkey(t+1,keyself[t]); } flop = calloc_drhook(numthreads, sizeof(*flop)); instr = calloc_drhook(numthreads, sizeof(*instr)); tot = calloc_drhook(numthreads, sizeof(*tot)); for (t=0; t<numthreads; t++) { for (j=0; j<hashsize; j++) { drhook_key_t *keyptr = &keydata[t][j]; while (keyptr) { if (keyptr->name && (keyptr->status == 0 || signal_handler_called)) { double self; if (opt_wallprof) { self = keyptr->delta_wall_all - keyptr->delta_wall_child; } else { self = keyptr->delta_cpu_all - keyptr->delta_cpu_child; } /* if (self < 0) self = 0; */ tot[t] += self; #ifdef HPM flop[t] += keyptr->avg_mflops * self; /* mflop_count(keyptr); */ instr[t] += keyptr->avg_mipsrate * self; /* mip_count(keyptr); */ #endif nprof++; } keyptr = keyptr->next; } /* while (keyptr && keyptr->status == 0) */ } /* for (t=0; t<numthreads; t++) */ } /* for (j=0; j<hashsize; j++) */ if (opt_wallprof) { /* a bit unreliable; had not taken max. value of threads wall yet; will be recalculated */ tottime = tot[0] + ((keyself && opt_self > 1) ? keyself[0]->delta_wall_all : 0); for (t=1; t<numthreads; t++) { double tmp = tot[t] + ((keyself && opt_self > 1) ? keyself[t]->delta_wall_all : 0); tottime = MAX(tottime,tmp); } } else { /* ok & reliable (for cpuprof) */ tottime = 0; for (t=0; t<numthreads; t++) tottime += (tot[t] + ((keyself && opt_self > 1) ? keyself[t]->delta_cpu_all : 0)); } if (tottime <= 0) tottime = 1e-10; p = prof = calloc_drhook(nprof + 1, sizeof(*prof)); /* Make sure there is at least one entry */ for (t=0; t<numthreads; t++) { for (j=0; j<hashsize; j++) { drhook_key_t *keyptr = &keydata[t][j]; while (keyptr) { if (keyptr->name && (keyptr->status == 0 || signal_handler_called)) { p->self = opt_wallprof ? keyptr->delta_wall_all - keyptr->delta_wall_child : keyptr->delta_cpu_all - keyptr->delta_cpu_child; p->total = opt_wallprof ? keyptr->delta_wall_all : keyptr->delta_cpu_all; p->calls = keyptr->calls; p->name = keyptr->name; p->pc = (p->self/tottime) * 100.0; if (p->calls > 0) { p->percall_ms_self = (p->self/p->calls) * 1000.0; p->percall_ms_total = (p->total/p->calls) * 1000.0; } p->tid = t+1; p->index = p - prof; #ifdef HPM if (opt_hpmprof) { p->mflops = keyptr->avg_mflops; /* mflops_hpm(keyptr); */ p->mipsrate = keyptr->avg_mipsrate; /* mips_hpm(keyptr); */ p->divpc = divpc_hpm(keyptr); } #endif p->filename = keyptr->filename; p->sizeinfo = keyptr->sizeinfo; p->min_sizeinfo = keyptr->min_sizeinfo; p->max_sizeinfo = keyptr->max_sizeinfo; p->sizespeed = (p->self > 0 && p->sizeinfo > 0) ? p->sizeinfo/p->self : 0; p->sizeavg = (p->calls > 0 && p->sizeinfo > 0) ? p->sizeinfo/p->calls : 0; p->callpath = keyptr->callpath; p->callpath_len = keyptr->callpath_len; p++; } keyptr = keyptr->next; } /* while (keyptr && keyptr->status == 0) */ } /* for (j=0; j<hashsize; j++) */ } /* for (t=0; t<numthreads; t++) */ do { double mflop_rate = 0; double mip_rate = 0; int numroutines = 0; int cluster; double *maxval = calloc_drhook(nprof+1, sizeof(*maxval)); /* make sure at least 1 element */ int *clusize = calloc_drhook(nprof+1, sizeof(*clusize)); /* make sure at least 1 element */ char *prevname = NULL; const char *fmt1 = "%5d %8.2f %12.3f %12.3f %12.3f %14llu %11.2f %11.2f %s"; const char *fmt2 = "%5d %8.2f %12.3f %12.3f %12.3f %14llu %7.0f %7.0f %7.1f %s"; const char *fmt = opt_hpmprof ? fmt2 : fmt1; char *filename = get_mon_out(myproc); FILE *fp = NULL; if (!filename) break; if ((myproc == 1 && mon_out_procs == -1) || mon_out_procs == myproc) { fprintf(stderr, "%s %s [%s@%s:%d] Writing profiling information of proc#%d into file '%s'\n", pfx,TIMESTR(tid),FFL, myproc,filename); } fp = fopen(filename,"w"); if (!fp) goto finish_3; /* alphanumerical sorting to find out clusters of the same routine but on different threads */ /* also find out total wall clock time */ /* calculate percentage values */ p = prof; qsort(p, nprof, sizeof(*p), prof_name_comp); cluster = 0; maxval[cluster] = p->self; p->maxval = &maxval[cluster]; clusize[cluster] = 1; prevname = p->name; p++; for (j=1; j<nprof; j++) { if (!strequ(prevname,p->name)) { (p-1)->cluster = cluster; (p-1)->maxval = &maxval[cluster]; prevname = p->name; cluster++; } if (p->self > maxval[cluster]) maxval[cluster] = p->self; p->cluster = cluster; p->maxval = &maxval[cluster]; clusize[cluster]++; p++; } /* for (j=1; j<nprof; j++) */ numroutines = (nprof > 0) ? (cluster + 1) : 0; /* Active no. of routines */ if (opt_wallprof) tottime = 0; p = prof; for (j=0; j<nprof; j++) { int use_this = 0; cluster = p->cluster; if (clusize[cluster] > 1) { /* multiple threads <= numthreads indeed called this routine */ p->is_max = (p->self == *p->maxval); if (p->is_max) { /* first max found will be used for total time */ clusize[cluster] = -clusize[cluster]; /* ensures that max has been found for this cluster */ use_this = opt_wallprof; } } else if (clusize[cluster] == 1) { use_this = opt_wallprof; } if (use_this && opt_wallprof) tottime += p->self; p++; } if (tottime <= 0) tottime = 1e-10; if (opt_wallprof) { /* use re-calculated tottime to define percentages */ p = prof; for (j=0; j<nprof; j++) { p->pc = (p->self/tottime) * 100.0; p++; } } /* sorting with respect to percentage value */ p = prof; qsort(p, nprof, sizeof(*p), prof_pc_comp_desc); flop_tot = 0; instr_tot = 0; max_overhead_pc = 0; for (t=0; t<numthreads; t++) { flop_tot += flop[t]; instr_tot += instr[t]; if (overhead) { max_overhead_pc = MAX(max_overhead_pc,overhead[t]); #ifdef DEBUG fprintf(fp,"tid#%d: overhead = %.15g s\n",t+1,overhead[t]); #endif } } #ifdef DEBUG fprintf(fp,"max overhead = %.15g s, tottime = %.15g s\n", max_overhead_pc, tottime); #endif if (tottime - max_overhead_pc > 0) { max_overhead_pc = 100.0*(max_overhead_pc/(tottime - max_overhead_pc)); } else { max_overhead_pc = 100; } fprintf(fp, "Profiling information for program='%s', proc#%d:\n",a_out, myproc); fprintf(fp,"\tNo. of instrumented routines called : %d\n", numroutines); fprintf(fp,"\tInstrumentation started : %s\n",start_stamp ? start_stamp : "N/A"); end_stamp = timestamp(); fprintf(fp,"\tInstrumentation ended : %s\n",end_stamp ? end_stamp : "N/A"); fprintf(fp,"\tInstrumentation overhead: %.2f%%\n",max_overhead_pc); { long long int hwm = getmaxhwm_()/1048576; long long int rss = getmaxrss_()/1048576; long long int maxstack = getmaxstk_()/1048576; long long int vmpeak = getvmpeak_()/1048576; long long int pag = getpag_(); fprintf(fp, "\tMemory usage : %lld MB (heap), %lld MB (rss), %lld MB (stack), %lld MB (vmpeak), %lld (paging)\n", hwm,rss,maxstack,vmpeak,pag); } if (opt_hpmprof) { mflop_rate = flop_tot / tottime; mip_rate = instr_tot / tottime; fprintf(fp, "\t%s-time is %.2f sec on proc#%d, %.0f MFlops (ops#%.0f*10^6), %.0f MIPS (ops#%.0f*10^6) (%d procs, %d threads)\n", opt_wallprof ? "Wall" : "Total CPU", tottime, myproc, mflop_rate, flop_tot, mip_rate, instr_tot, nproc, numthreads); } else { fprintf(fp, "\t%s-time is %.2f sec on proc#%d (%d procs, %d threads)\n", opt_wallprof ? "Wall" : "Total CPU", tottime, myproc, nproc, numthreads); } if (myproc == 1) { fprintf(stderr, "Profiling information for program='%s', proc#%d:\n",a_out, myproc); fprintf(stderr,"\tNo. of instrumented routines called : %d\n", numroutines); fprintf(stderr,"\tInstrumentation started : %s\n",start_stamp ? start_stamp : "N/A"); fprintf(stderr,"\tInstrumentation ended : %s\n",end_stamp ? end_stamp : "N/A"); fprintf(stderr,"\tInstrumentation overhead: %.2f%%\n",max_overhead_pc); if (opt_hpmprof) { fprintf(stderr, "\t%s-time is %.2f sec on proc#%d, %.0f MFlops (ops#%.0f*10^6), %.0f MIPS (ops#%.0f*10^6) (%d procs, %d threads)\n", opt_wallprof ? "Wall" : "Total CPU", tottime, myproc, mflop_rate, flop_tot, mip_rate, instr_tot, nproc, numthreads); } else { fprintf(stderr, "\t%s-time is %.2f sec on proc#%d (%d procs, %d threads)\n", opt_wallprof ? "Wall" : "Total CPU", tottime, myproc, nproc, numthreads); } } /* if (myproc == 1) */ free_drhook(end_stamp); for (t=0; t<numthreads; t++) { double tmp = 100.0*(tot[t]/tottime); if (opt_hpmprof && tot[t] > 0) { mflop_rate = flop[t]/tot[t]; mip_rate = instr[t]/tot[t]; } else { mflop_rate = 0; mip_rate = 0; } fprintf( fp,"\tThread#%d: %11.2f sec (%.2f%%)",t+1,tot[t],tmp); if (opt_hpmprof) fprintf( fp,", %.0f MFlops (ops#%.0f*10^6), %.0f MIPS (ops#%.0f*10^6)", mflop_rate, flop[t], mip_rate, instr[t]); fprintf( fp,"\n"); if (myproc == 1) { fprintf(stderr,"\tThread#%d: %11.2f sec (%.2f%%)",t+1,tot[t],tmp); if (opt_hpmprof) fprintf(stderr,", %.0f MFlops (ops#%.0f*10^6), %.0f MIPS (ops#%.0f*10^6)", mflop_rate, flop[t], mip_rate, instr[t]); fprintf(stderr,"\n"); } } fprintf(fp,"\n"); if (opt_hpmprof) { len = fprintf(fp," # %% Time Cumul Self Total # of calls MIPS MFlops Div-%% "); } else { len = fprintf(fp," # %% Time Cumul Self Total # of calls Self Total "); } fprintf(fp,"Routine@<thread-id>"); if (opt_clusterinfo) fprintf(fp," [Cluster:(id,size)]"); fprintf(fp,"\n"); if (opt_sizeinfo) fprintf(fp,"%*s %s\n",len-20," ","(Size; Size/sec; Size/call; MinSize; MaxSize)"); if (opt_hpmprof) { fprintf(fp, " (self) (sec) (sec) (sec) \n"); } else { fprintf(fp, " (self) (sec) (sec) (sec) ms/call ms/call\n"); } fprintf(fp,"\n"); cumul = 0; for (j=0; j<nprof; ) { int cluster_size = clusize[p->cluster]; if (p->pc < percent_limit) break; if (opt_cputime) { cumul += p->self; } else { if (p->is_max || cluster_size == 1) cumul += p->self; } if (opt_hpmprof) { fprintf(fp, fmt, ++j, p->pc, cumul, p->self, p->total, p->calls, p->mipsrate, p->mflops, p->divpc, p->is_max ? "*" : " "); } else { fprintf(fp, fmt, ++j, p->pc, cumul, p->self, p->total, p->calls, p->percall_ms_self, p->percall_ms_total, p->is_max ? "*" : " "); } print_routine_name(fp, p, len, cluster_size); if (opt_sizeinfo && p->sizeinfo > 0) { char s1[DRHOOK_STRBUF], s2[DRHOOK_STRBUF], s3[DRHOOK_STRBUF]; char s4[DRHOOK_STRBUF], s5[DRHOOK_STRBUF]; lld_commie(p->sizeinfo,s1); dbl_commie(p->sizespeed,s2); dbl_commie(p->sizeavg,s3); lld_commie(p->min_sizeinfo,s4); lld_commie(p->max_sizeinfo,s5); fprintf(fp,"\n%*s (%s; %s; %s; %s; %s)",len-20," ",s1,s2,s3,s4,s5); } fprintf(fp,"\n"); p++; } /* for (j=0; j<nprof; ) */ fclose(fp); finish_3: free_drhook(filename); free_drhook(maxval); free_drhook(clusize); } while (0); free_drhook(instr); free_drhook(flop); free_drhook(tot); free_drhook(prof); do_prof_off = 0; } else if (*print_option == 4) { /* Memory profiling */ int t, len; int nprof = 0; drhook_memprof_t *prof = NULL; drhook_memprof_t *p; long long int *tot; long long int *maxseen_tot; double totmaxmem_delta; if (!opt_memprof) return; /* no profiling info available */ if (tid > 1) return; /* just master thread allowed ; takes care of siblings, too */ if (numthreads<=0) return; if (do_prof_off) return; do_prof_off = 1; tot = calloc_drhook(numthreads, sizeof(*tot)); maxseen_tot = calloc_drhook(numthreads, sizeof(*maxseen_tot)); for (t=0; t<numthreads; t++) { for (j=0; j<hashsize; j++) { drhook_key_t *keyptr = &keydata[t][j]; while (keyptr) { if (keyptr->name && (keyptr->status == 0 || signal_handler_called)) { long long int self; self = keyptr->maxmem_selfdelta; if (self < 0) self = 0; tot[t] += self; maxseen_tot[t] = MAX(maxseen_tot[t], keyptr->mem_seenmax); nprof++; } keyptr = keyptr->next; } /* while (keyptr && keyptr->status == 0) */ } /* for (t=0; t<numthreads; t++) */ } /* for (j=0; j<hashsize; j++) */ totmaxmem_delta = tot[0]; for (t=1; t<numthreads; t++) { long long int tmp = tot[t]; totmaxmem_delta = MAX(totmaxmem_delta,tmp); } if (totmaxmem_delta <= 0) totmaxmem_delta = 1e-10; /* To avoid divide-by-zero */ p = prof = calloc_drhook(nprof + 1, sizeof(*prof)); /* Make sure there is at least one entry */ for (t=0; t<numthreads; t++) { for (j=0; j<hashsize; j++) { drhook_key_t *keyptr = &keydata[t][j]; while (keyptr) { if (keyptr->name && (keyptr->status == 0 || signal_handler_called)) { p->self = keyptr->maxmem_selfdelta; p->children = keyptr->mem_child; p->hwm = keyptr->mem_maxhwm; p->rss = keyptr->mem_maxrss; p->stk = keyptr->mem_maxstk; p->pag = keyptr->mem_maxpagdelta; p->leaked = keyptr->mem_curdelta; p->calls = keyptr->calls; p->alloc_count += keyptr->alloc_count; p->free_count += keyptr->free_count; p->name = keyptr->name; p->pc = (p->self/totmaxmem_delta) * 100.0; p->tid = t+1; p->index = p - prof; p->filename = keyptr->filename; p->callpath = keyptr->callpath; p->callpath_len = keyptr->callpath_len; p++; } keyptr = keyptr->next; } /* while (keyptr && keyptr->status == 0) */ } /* for (t=0; t<numthreads; t++) */ } /* for (j=0; j<hashsize; j++) */ do { int numroutines = 0; int cluster; long long int *maxval = calloc_drhook(nprof+1, sizeof(*maxval)); /* make sure at least 1 element */ int *clusize = calloc_drhook(nprof+1, sizeof(*clusize)); /* make sure at least 1 element */ char *prevname = NULL; const char *fmt1 = "%5d %9.2f %14lld %14lld %14lld %14lld %14lld %10lld %10llu %10llu%s%10llu %s"; const char *fmt = fmt1; char *filename = get_memmon_out(myproc); FILE *fp = NULL; if (!filename) break; if ((myproc == 1 && mon_out_procs == -1) || mon_out_procs == myproc) { fprintf(stderr,"Writing memory-profiling information of proc#%d into file '%s'\n",myproc,filename); } fp = fopen(filename,"w"); if (!fp) goto finish_4; /* alphanumerical sorting to find out clusters of the same routine but on different threads */ p = prof; qsort(p, nprof, sizeof(*p), memprof_name_comp); cluster = 0; maxval[cluster] = p->self; p->maxval = &maxval[cluster]; clusize[cluster] = 1; prevname = p->name; p++; for (j=1; j<nprof; j++) { if (!strequ(prevname,p->name)) { (p-1)->cluster = cluster; (p-1)->maxval = &maxval[cluster]; prevname = p->name; cluster++; } if (p->self > maxval[cluster]) maxval[cluster] = p->self; p->cluster = cluster; p->maxval = &maxval[cluster]; clusize[cluster]++; p++; } /* for (j=1; j<nprof; j++) */ numroutines = (nprof > 0) ? (cluster + 1) : 0; /* Active no. of routines */ totmaxmem_delta = 0; p = prof; for (j=0; j<nprof; j++) { int use_this = 0; cluster = p->cluster; if (clusize[cluster] > 1) { /* multiple threads <= numthreads indeed called this routine */ p->is_max = (p->self == *p->maxval); if (p->is_max) { /* first max found will be used for total time */ clusize[cluster] = -clusize[cluster]; /* ensures that max has been found for this cluster */ use_this = 1; } } else if (clusize[cluster] == 1) { use_this = 1; } if (use_this) totmaxmem_delta += p->self; p++; } if (totmaxmem_delta <= 0) totmaxmem_delta = 1e-10; /* To avoid divide-by-zero */ /* use re-calculated totmaxmem_delta to define percentages */ p = prof; for (j=0; j<nprof; j++) { p->pc = (p->self/totmaxmem_delta) * 100.0; p++; } /* sorting with respect to percentage value */ p = prof; qsort(p, nprof, sizeof(*p), memprof_pc_comp_desc); fprintf(fp, "Memory-profiling information for program='%s', proc#%d:\n",a_out, myproc); fprintf(fp,"\tNo. of instrumented routines called : %d\n", numroutines); fprintf(fp,"\tInstrumentation started : %s\n",start_stamp ? start_stamp : "N/A"); end_stamp = timestamp(); fprintf(fp,"\tInstrumentation ended : %s\n",end_stamp ? end_stamp : "N/A"); { long long int hwm = gethwm_()/1048576; long long int rss = getrss_()/1048576; long long int maxstack = getmaxstk_()/1048576; long long int vmpeak = getvmpeak_()/1048576; long long int pag = getpag_(); long long int maxseen = 0; long long int leaked = 0; p = prof; for (j=0; j<nprof; j++) { if (p->leaked > 0) leaked += p->leaked; p++; } for (t=0; t<numthreads; t++) { maxseen += maxseen_tot[t]; } maxseen /= 1048576; leaked /= 1048576; fprintf(fp, "\tMemory usage : %lld MB (max.seen), %lld MB (leaked), %lld MB (heap), %lld MB (max.rss), %lld MB (max.stack), %lld MB (vmpeak), %lld (paging)\n", maxseen,leaked,hwm,rss,maxstack,vmpeak,pag); fprintf(fp,"\tNo. of procs/threads: %d procs, %d threads\n",nproc,numthreads); } if (myproc == 1) { fprintf(stderr, "Memory-profiling information for program='%s', proc#%d:\n",a_out, myproc); fprintf(stderr,"\tNo. of instrumented routines called : %d\n", numroutines); fprintf(stderr,"\tInstrumentation started : %s\n",start_stamp ? start_stamp : "N/A"); fprintf(stderr,"\tInstrumentation ended : %s\n",end_stamp ? end_stamp : "N/A"); } /* if (myproc == 1) */ free_drhook(end_stamp); fprintf(fp,"\n"); len = fprintf(fp," # Memory-%% Self-alloc + Children Self-Leaked Heap Max.Stack Paging #Calls #Allocs #Frees "); /*"12345-1234567899-12345678901234-12345678901234-12345678901234-12345678901234-12345678901234-12345678901234-12345678901234-123456789012-123456789012"*/ fprintf(fp,"Routine@<thread-id>"); if (opt_clusterinfo) fprintf(fp," [Cluster:(id,size)]"); fprintf(fp,"\n"); fprintf(fp, " (self) (bytes) (bytes) (bytes) (bytes) (bytes) (delta)"); /*"12345-1234567899-12345678901234-12345678901234-12345678901234-12345678901234-12345678901234-12345678901234-12345678901234-123456789012-123456789012"*/ fprintf(fp,"\n"); p = prof; for (j=0; j<nprof; ) { int cluster_size = clusize[p->cluster]; if (p->pc < percent_limit) break; t = p->tid - 1; if (p->children > maxseen_tot[t]) p->children = maxseen_tot[t]; /* adjust */ fprintf(fp, fmt, ++j, p->pc, p->self, p->children, p->leaked, p->hwm, p->stk, p->pag, p->calls, p->alloc_count, (p->alloc_count - p->free_count != 0) ? "*" : " ", p->free_count, p->is_max ? "*" : " "); print_routine_name(fp, p, len, cluster_size); fprintf(fp,"\n"); p++; } /* for (j=0; j<nprof; ) */ fclose(fp); finish_4: free_drhook(filename); free_drhook(maxval); free_drhook(clusize); } while (0); free_drhook(tot); free_drhook(maxseen_tot); free_drhook(prof); do_prof_off = 0; } } } /*=== c_drhook_init_signals_ ===*/ void c_drhook_init_signals_(const int *enforce) { signal_drhook_init(*enforce); } /*=== c_drhook_raise_ ===*/ /* Just a convenience function for Fortran90 which may not have raise()-signal function CALL c_drhook_raise(10) ! Raise signal#10 */ void c_drhook_raise_(const int *sig) { fflush(NULL); raise(*sig); } /**** C-interface to Dr.Hook ****/ void Dr_Hook(const char *name, int option, double *handle, const char *filename, int sizeinfo, int name_len, int filename_len) { static int first_time = 1; static int value = 1; /* ON by default */ if (first_time) { /* Not thread safe */ extern void *cdrhookinit_(int *value); /* from ifsaux/support/cdrhookinit.F90 */ cdrhookinit_(&value); first_time = 0; } if (value == 0) return; /* Immediate return if OFF */ if (value != 0) { int tid = get_thread_id_(); if (option == 0) { c_drhook_start_(name, &tid, handle, filename, &sizeinfo, name_len > 0 ? name_len : strlen(name), filename_len > 0 ? filename_len : strlen(filename)); } else if (option == 1) { c_drhook_end_(name, &tid, handle, filename, &sizeinfo, name_len > 0 ? name_len : strlen(name), filename_len > 0 ? filename_len : strlen(filename)); } } } /**** Interface to HPM ****/ /*<<< experimental >>>*/ #ifdef HPM #ifdef RS6K /**** Interface to HPM (RS6K) ****/ #include <pmapi.h> static pthread_mutex_t hpm_lock = PTHREAD_MUTEX_INITIALIZER; static int *hpm_tid_init = NULL; static double cycles = 1300000000.0; /* 1.3GHz ; changed via pm_cycles() in init_hpm() */ #define MCYCLES (cycles * 1e-6) #define TEST_PM_ERROR(name, rc) \ if (rc != 0) { \ fprintf(stderr,"PM_ERROR(tid#%d, pthread_self()=%d): rc=%d at %s(), line=%d, file=%s\n",\ tid,pthread_self(),rc,name,__LINE__,__FILE__); \ pm_error((char *)name, rc); \ spin(tid); \ RAISE(SIGABRT); \ } static void init_hpm(int tid) { const char *name = "init_hpm"; int rc; if (!hpm_tid_init) { hpm_tid_init = calloc_drhook(numthreads, sizeof(*hpm_tid_init)); cycles = pm_cycles(); } if (!hpm_tid_init[tid-1]) { #ifdef PMAPI_POST_P4 pm_info2_t pminfo; #else pm_info_t pminfo; #endif pm_groups_info_t pmgroupsinfo; /*------------------------------------*/ /* initialize the performance monitor */ /*------------------------------------*/ #ifdef PMAPI_POST_P4 rc = pm_initialize(PM_VERIFIED | PM_UNVERIFIED | PM_CAVEAT | PM_GET_GROUPS, &pminfo, &pmgroupsinfo, PM_CURRENT); #else rc = pm_init(PM_VERIFIED | PM_UNVERIFIED | PM_CAVEAT | PM_GET_GROUPS, &pminfo, &pmgroupsinfo); #endif TEST_PM_ERROR((char *)name, rc); if (myproc <= 1) fprintf(stderr, ">>>pm_init() for ECMWF/OpenMP-tid#%d, pthread_self()=%d\n", tid,pthread_self()); } if (!hpm_tid_init[tid-1]) { #if defined(PMAPI_P7) char *env = getenv("HPM_GROUP"); hpm_grp = atoi(env); int group; fprintf(stderr,"hpm_group = %d\n",hpm_grp); if (hpm_grp == 150) group = 150; if (hpm_grp == 141) group = 141; /*-- counters -- case 150: strcpy(group_label, "pm_vsu23, VSU Execution"); strcpy(label[0], "four flops operation (fdiv,fsqrt) Scalar Instructions only (PM_VSU_FSQRT_FDIV)"); strcpy(label[1], "VSU0 Finished an instruction (PM_VSU_FIN)"); strcpy(label[2], "two flops operation (fmadd, fnmadd, fmsub, fnmsub) Scalar instructions only (PM_VSU_FMA)"); strcpy(label[3], "one flop (fadd, fmul, fsub, fcmp, fsel, fabs, fnabs, fres, fsqrte, fneg) operation finished (PM_VSU_1FLOP)"); strcpy(label[4], "Run instructions completed(PM_RUN_INST_CMPL)"); strcpy(label[5], "Run cycles (PM_RUN_CYC)"); strcpy(label[6], "Nothing"); strcpy(label[7], "Nothing"); */ /*-- counters -- case 141: strcpy(group_label, "pm_vsu14, VSU Execution"); strcpy(label[0], "one flop (fadd, fmul, fsub, fcmp, fsel, fabs, fnabs, fres, fsqrte, fneg) operation finished (PM_VSU_1FLOP)"); strcpy(label[1], "four flops operation (scalar fdiv, fsqrt; DP vector version of fmadd, fnmadd, fmsub, SP vector versions of single flop instructions) (PM_VSU_4FLOP)"); strcpy(label[2], "eight flops operation (DP vector versions of fdiv,fsqrt and SP vector versions of fmadd,fnmadd,fmsub,fnmsub) (PM_VSU_8FLOP)"); strcpy(label[3], "two flops operation (scalar fmadd, fnmadd, fmsub, fnmsub and DP vector versions of single flop instructions) (PM_VSU_2FLOP)"); strcpy(label[4], "Run instructions completed(PM_RUN_INST_CMPL)"); strcpy(label[5], "Run cycles (PM_RUN_CYC)"); strcpy(label[6], "Nothing"); strcpy(label[7], "Nothing"); */ #elif defined(PMAPI_P6) const int group = 186; /* pm_hpm1 */ /*-- counters -- case 186: strcpy(group_label, "HPM group"); strcpy(label[0], "FPU executed one flop instruction (PM_FPU_1FLOP)"); strcpy(label[1], "FPU executed multiply-add instruction (PM_FPU_FMA)"); strcpy(label[2], "FPU executed FSQRT or FDIV instruction (PM_FPU_SQRT_FDIV)"); strcpy(label[3], "Processor Cycles (PM_CYC [shared chip])"); strcpy(label[4], "Run instructions completed(PM_RUN_INST_CMPL)"); strcpy(label[5], "Run cycles (PM_RUN_CYC)"); strcpy(label[6], "Nothing"); strcpy(label[7], "Nothing"); */ #elif defined(PMAPI_P5_PLUS) /* IBM Power 5+ specific */ const int group = 150; /* pm_hpmcount2 */ /*-- counters -- (from John Hague, IBM/UK, 22-Aug-2006 : Thanx!!) case 150: strcpy(group_label, "pm_flop, Floating point operations"); strcpy(label[0], "FPU executed FDIV instruction (PM_FPU_FDIV)"); strcpy(label[1], "FPU executed multiply-add instruction (PM_FPU_FMA)"); strcpy(label[2], "FPU executed FSQRT instruction (PM_FPU_SQRT)"); strcpy(label[3], "FPU executed one flop instruction (PM_FPU_1FLOP)"); strcpy(label[4], "Run instructions completed(PM_RUN_INST_CMPL)"); strcpy(label[5], "Run cycles (PM_RUN_CYC)"); strcpy(label[6], "Nothing"); strcpy(label[7], "Nothing"); */ #else const int group = 60; /* pm_hpmcount2 */ /*-- counters -- case 60: strcpy(group_label, "pm_hpmcount2, Hpmcount group for computation intensity analysis"); strcpy(label[0], "FPU executed FDIV instruction (PM_FPU_FDIV)"); strcpy(label[1], "FPU executed multiply-add instruction (PM_FPU_FMA)"); strcpy(label[2], "FPU0 produced a result (PM_FPU0_FIN)"); strcpy(label[3], "FPU1 produced a result (PM_FPU1_FIN)"); strcpy(label[4], "Processor cycles (PM_CYC)"); strcpy(label[5], "FPU executed store instruction (PM_FPU_STF)"); strcpy(label[6], "Instructions completed (PM_INST_CMPL)"); strcpy(label[7], "LSU executed Floating Point load instruction (PM_LSU_LDF)"); */ #endif if (myproc <= 1) fprintf(stderr,"group = %d\n",group); pm_prog_t pmprog; pm_data_t pmdata; int i; /*---------------------*/ /* set a default group */ /*---------------------*/ for (i=0; i<MAX_COUNTERS; i++) { pmprog.events[i] = COUNT_NOTHING; } pmprog.events[0] = group; /*-------------------------------------------------------------*/ /* set the mode for user (not kernel) and thread (not process) */ /*-------------------------------------------------------------*/ pmprog.mode.w = 0; pmprog.mode.b.user = 1; pmprog.mode.b.process = 0; /* pmprog.mode.b.process = 1; */ /*------------------------------------------*/ /* for power-4 you have to use event groups */ /*------------------------------------------*/ pmprog.mode.b.is_group = 1; /*---------------------------------------------------*/ /* set the mode to not to start counting immediately */ /*---------------------------------------------------*/ /* pmprog.mode.b.count = 1; */ pmprog.mode.b.count = 0; /*-----------------------------------------*/ /* initialize the group and start counting */ /*-----------------------------------------*/ hpm_tid_init[tid-1] = pthread_self(); /* Always > 0 */ rc = pm_set_program_mythread(&pmprog); TEST_PM_ERROR((char *)name, rc); rc = pm_start_mythread(); TEST_PM_ERROR((char *)name, rc); } } static void stop_only_hpm(int tid, drhook_key_t *pstop) { const char *name = "stop_only_hpm"; pm_data_t pmdata; int i, rc; /* if (numthreads > 1) pthread_mutex_lock(&hpm_lock); */ if (!hpm_tid_init || !hpm_tid_init[tid-1]) init_hpm(tid); /* rc = pm_stop_mythread(); TEST_PM_ERROR((char *)name, rc); */ if (pstop && !pstop->counter_stopped) { rc = pm_get_data_mythread(&pmdata); TEST_PM_ERROR((char *)name, rc); if (pstop && pstop->counter_in && !pstop->counter_stopped) { for (i=0; i<MAX_COUNTERS; i++) { pstop->counter_sum[i] += (pmdata.accu[i] - pstop->counter_in[i]); } pstop->counter_stopped = 1; } } /* rc = pm_start_mythread(); TEST_PM_ERROR((char *)name, rc); */ /* if (numthreads > 1) pthread_mutex_unlock(&hpm_lock); */ } static void stopstart_hpm(int tid, drhook_key_t *pstop, drhook_key_t *pstart) { const char *name = "stopstart_hpm"; pm_data_t pmdata; int i, rc; /* if (numthreads > 1) pthread_mutex_lock(&hpm_lock); */ if (!hpm_tid_init || !hpm_tid_init[tid-1]) init_hpm(tid); /* rc = pm_stop_mythread(); TEST_PM_ERROR((char *)name, rc); */ rc = pm_get_data_mythread(&pmdata); TEST_PM_ERROR((char *)name, rc); if (pstop && pstop->counter_in && !pstop->counter_stopped) { for (i=0; i<MAX_COUNTERS; i++) { pstop->counter_sum[i] += (pmdata.accu[i] - pstop->counter_in[i]); } pstop->counter_stopped = 1; } if (pstart) { if (!pstart->counter_in ) pstart->counter_in = calloc_drhook(MAX_COUNTERS, sizeof(*pstart->counter_in )); if (!pstart->counter_sum) pstart->counter_sum = calloc_drhook(MAX_COUNTERS, sizeof(*pstart->counter_sum)); for (i=0; i<MAX_COUNTERS; i++) { pstart->counter_in[i] = pmdata.accu[i]; } pstart->counter_stopped = 0; } /* rc = pm_start_mythread(); TEST_PM_ERROR((char *)name, rc); */ /* if (numthreads > 1) pthread_mutex_unlock(&hpm_lock); */ } #else /**** Interface to HPM (CRAY SV2, XD1 and XT3) ****/ static int *hpm_tid_init = NULL; static double cycles = 0; #define MCYCLES (cycles * 1e-6) #define TEST_PM_ERROR(name, rc) \ if (rc != 0) { \ fprintf(stderr,"PM_ERROR(tid#%d, pthread_self()=%d): rc=%d at %s(), line=%d, file=%s\n",\ tid,pthread_self(),rc,name,__LINE__,__FILE__); \ pm_error((char *)name, rc); \ spin(tid); \ RAISE(SIGABRT); \ } static void init_hpm(int tid) { const char *name = "init_hpm"; int rc; cycles = irtc_rate_(); } static void stop_only_hpm(int tid, drhook_key_t *pstop) { const char *name = "stop_only_hpm"; int i, rc; if (!hpm_tid_init || !hpm_tid_init[tid-1]) init_hpm(tid); if (pstop && !pstop->counter_stopped) { if (pstop && pstop->counter_in && !pstop->counter_stopped) { #if defined(DT_FLOP) pstop->counter_sum[0] += ((long long int) flop_() - pstop->counter_in[0]); #if defined(SV2) pstop->counter_sum[ENTRY_4] += (_rtc() - pstop->counter_in[ENTRY_4]); #else pstop->counter_sum[ENTRY_4] += (irtc_() - pstop->counter_in[ENTRY_4]); #endif #endif pstop->counter_stopped = 1; } } } static void stopstart_hpm(int tid, drhook_key_t *pstop, drhook_key_t *pstart) { const char *name = "stopstart_hpm"; int i, rc; if (!hpm_tid_init || !hpm_tid_init[tid-1]) init_hpm(tid); if (pstop && pstop->counter_in && !pstop->counter_stopped) { #if defined(DT_FLOP) pstop->counter_sum[0] += ((long long int) flop_() - pstop->counter_in[0]); #if defined(SV2) pstop->counter_sum[ENTRY_4] += (_rtc() - pstop->counter_in[ENTRY_4]); #else pstop->counter_sum[ENTRY_4] += (irtc_() - pstop->counter_in[ENTRY_4]); #endif #endif pstop->counter_stopped = 1; } if (pstart) { if (!pstart->counter_in ) pstart->counter_in = calloc_drhook(MAX_COUNTERS, sizeof(*pstart->counter_in )); if (!pstart->counter_sum) pstart->counter_sum = calloc_drhook(MAX_COUNTERS, sizeof(*pstart->counter_sum)); #if defined(DT_FLOP) pstart->counter_in[0] = (long long int) flop_(); #if defined(SV2) pstart->counter_in[ENTRY_4] = _rtc(); #else pstart->counter_in[ENTRY_4] = irtc_(); #endif #endif pstart->counter_stopped = 0; } } #endif /*Interface to RS6K and SV2, XD1, XT3 */ static double mflops_hpm(const drhook_key_t *keyptr) { double mflops = 0; if (keyptr && keyptr->counter_sum && keyptr->counter_sum[ENTRY_4] > 0) { long long int sum = 0; #if defined(DT_FLOP) sum = keyptr->counter_sum[0]; #elif defined(PMAPI_P7) /* IBM Power 7 specific */ if(hpm_grp == 150) { sum = 2 * keyptr->counter_sum[2] + keyptr->counter_sum[3]; } if(hpm_grp == 141) { sum = 2 * keyptr->counter_sum[0] + 4 * keyptr->counter_sum[1] + 2 * keyptr->counter_sum[3]; } #elif defined(PMAPI_P6) /* IBM Power 6 specific */ sum = keyptr->counter_sum[0] + 2 * keyptr->counter_sum[1]; #elif defined(PMAPI_P5_PLUS) /* IBM Power 5+ specific */ sum = 2 * keyptr->counter_sum[1] + keyptr->counter_sum[3]; #else sum = keyptr->counter_sum[1] + keyptr->counter_sum[2] + keyptr->counter_sum[3] - keyptr->counter_sum[5]; #endif if (sum > 0) mflops = (sum * MCYCLES)/keyptr->counter_sum[ENTRY_4]; } return mflops; } static double mips_hpm(const drhook_key_t *keyptr) { double mipsrate = 0; #if defined(DT_FLOP) mipsrate = 0; #else if (keyptr && keyptr->counter_sum && keyptr->counter_sum[ENTRY_4] > 0) { mipsrate = (keyptr->counter_sum[ENTRY_6] * MCYCLES)/keyptr->counter_sum[ENTRY_4]; } #endif return mipsrate; } static double divpc_hpm(const drhook_key_t *keyptr) { double divpc = 0; #if defined(DT_FLOP) divpc = 0; #else if (keyptr && keyptr->counter_sum) { long long int sum = 0; #if defined(PMAPI_P7) /* IBM Power 7 specific */ if(hpm_grp == 150) { sum = 2 * keyptr->counter_sum[2] + keyptr->counter_sum[3]; if (sum > 0) divpc = (keyptr->counter_sum[0]*100.0)/sum; } if(hpm_grp == 141) { sum = 2 * keyptr->counter_sum[0] + 4 * keyptr->counter_sum[1] + 2 * keyptr->counter_sum[3]; if (sum > 0) divpc = (keyptr->counter_sum[1]*100.0)/sum; } #elif defined(PMAPI_P6) /* IBM Power 6 specific */ sum = keyptr->counter_sum[0] + 2 * keyptr->counter_sum[1]; if (sum > 0) divpc = (keyptr->counter_sum[2]*100.0)/sum; #elif defined(PMAPI_P5_PLUS) /* IBM Power 5+ specific */ sum = 2 * keyptr->counter_sum[1] + keyptr->counter_sum[3]; if (sum > 0) divpc = (keyptr->counter_sum[0]*100.0)/sum; #else sum = keyptr->counter_sum[1] + keyptr->counter_sum[2] + keyptr->counter_sum[3] - keyptr->counter_sum[5]; if (sum > 0) divpc = (keyptr->counter_sum[0]*100.0)/sum; #endif } #endif return divpc; } static double mflop_count(const drhook_key_t *keyptr) { double sum = 0; if (keyptr && keyptr->counter_sum && keyptr->counter_sum[ENTRY_4] > 0) { #if defined(DT_FLOP) sum = (keyptr->counter_sum[0]) * 1e-6; #elif defined(PMAPI_P7) /* IBM Power 7 specific */ if(hpm_grp == 150) { sum = (2 * keyptr->counter_sum[2] + keyptr->counter_sum[3]) * 1e-6; } if(hpm_grp == 141) { sum = (2 * keyptr->counter_sum[0] + 4 * keyptr->counter_sum[1] + 2 * keyptr->counter_sum[3]) * 1e-6; } #elif defined(PMAPI_P6) /* IBM Power 6 specific */ sum = (keyptr->counter_sum[0] + 2 * keyptr->counter_sum[1]) * 1e-6; #elif defined(PMAPI_P5_PLUS) /* IBM Power 5+ specific */ sum = (2 * keyptr->counter_sum[1] + keyptr->counter_sum[3]) * 1e-6; #else sum = (keyptr->counter_sum[1] + keyptr->counter_sum[2] + keyptr->counter_sum[3] - keyptr->counter_sum[5]) * 1e-6; #endif if (sum < 0) sum = 0; } return sum; } static double mip_count(const drhook_key_t *keyptr) { double sum = 0; #if defined(DT_FLOP) sum = 0; #else if (keyptr && keyptr->counter_sum && keyptr->counter_sum[ENTRY_4] > 0) { sum = keyptr->counter_sum[ENTRY_6] * 1e-6; } #endif return sum; } #endif /* HPM */ /* this is result of moving some code from libodb.a (odb/aux/util_ccode.c) for use by libifsaux.a directly ; simplifies linking sequences. */ #include <stdio.h> #include <string.h> /* #include <malloc.h> */ #include <stdlib.h> #include <signal.h> #define FORTRAN_CALL #if defined(CRAY) && !defined(SV2) #define util_cputime_ UTIL_CPUTIME #define util_walltime_ UTIL_WALLTIME #endif /* Portable CPU-timer (User + Sys) ; also WALL CLOCK-timer */ #include <unistd.h> #include <sys/types.h> #include <sys/times.h> #undef MIN #undef MAX #include <sys/param.h> #include <sys/time.h> #if !defined(VPP) FORTRAN_CALL double util_walltime_() { static double time_init = -1; double time_in_secs; #if !defined(CRAYXT) struct timeval tbuf; if (gettimeofday(&tbuf,NULL) == -1) perror("UTIL_WALLTIME"); if (time_init == -1) time_init = (double) tbuf.tv_sec + (tbuf.tv_usec / 1000000.0); time_in_secs = (double) tbuf.tv_sec + (tbuf.tv_usec / 1000000.0) - time_init; #else if (time_init == -1) time_init = dclock(); time_in_secs = dclock() - time_init; #endif return time_in_secs; } #if defined(CRAYXT) /* Cray XT3/XT4 with catamount microkernel */ FORTRAN_CALL double util_cputime_() { return util_walltime_(); /* In absence of anything better */ } #else extern clock_t times (struct tms *buffer); FORTRAN_CALL double util_cputime_() { struct tms tbuf; static int first_time = 1; static double clock_ticks = 0; (void) times(&tbuf); if (first_time) { clock_ticks = (double) sysconf(_SC_CLK_TCK); first_time = 0; } return (tbuf.tms_utime + tbuf.tms_stime + tbuf.tms_cutime + tbuf.tms_cstime) / clock_ticks; } #endif #else /* VPP */ FORTRAN_CALL double util_walltime_() { double w, time_in_secs; static double wallref = 0; extern FORTRAN_CALL gettod_(double *); if (wallref == 0) gettod_(&wallref); gettod_(&w); time_in_secs = (w - wallref) * 0.000001; return time_in_secs; } #endif #ifdef VPP #include <sys/types.h> #include <sys/param.h> #include <sys/signal.h> #include <sys/fault.h> #include <sys/syscall.h> #include <sys/procfs.h> #include <sys/proc.h> #include <fcntl.h> static int fujitsu_getrusage(int who, struct rusage *rusage) { int rc = -1; if (rusage) rusage->ru_maxrss = 0; if (who == RUSAGE_SELF && rusage) { static int maxrss = 0; static int oldpid = -1; static char procfile[20] = ""; static char *pf = NULL; /* static prpsinfo_t ps; */ static proc_t proc; int pid = getpid(); static int fildes = -1; unsigned int size; if (oldpid != pid) { oldpid = pid; maxrss = 0; pf = NULL; } if (!pf) { sprintf(procfile,"/proc/%d",pid); pf = procfile; fildes = open(procfile, O_RDONLY); } if (fildes == -1) return rc; /* if (ioctl(fildes, PIOCPSINFO, &ps) == -1) { perror("ioctl@fujitsu_getrusage(PIOCPSINFO)"); return rc; } */ if (ioctl(fildes, PIOCGETPR, &proc) == -1) { perror("ioctl@fujitsu_getrusage(PIOCGETPR)"); return rc; } size = /* ps.pr_usevpmem + */ proc.p_brksize + proc.p_stksize; if (size > maxrss) maxrss = size; rusage->ru_maxrss = maxrss; /* close(fildes); */ rc = 0; } return rc; } #endif /* VPP */ FORTRAN_CALL int util_ihpstat_(int *option) { int ret_value = 0; #if defined(SGI) || defined(VPP) if (*option == 1) { struct rusage rusage; #ifdef SGI int pagesize = 1024; getrusage(0, &rusage); #endif #ifdef VPP int pagesize = 1; /* getpagesize() */ fujitsu_getrusage(0, &rusage); #endif #if defined(SV2) int pagesize = getpagesize(); getrusage(0, &rusage); #endif #if defined(XT3) int pagesize = getpagesize(); getrusage(0, &rusage); #endif #if defined(XD1) int pagesize = getpagesize(); getrusage(0, &rusage); #endif ret_value = (rusage.ru_maxrss * pagesize + 7) / 8; /* In 8 byte words */ } #endif /* SGI or VPP */ return ret_value; } #ifndef __timer_t_defined static void set_timed_kill() { // Definition of timer_t, timer_create, timer_set // is a POSIX extention, not available on e.g. Darwin } #else static void set_timed_kill() { #if !defined MACOSX if (drhook_timed_kill) { const char delim[] = ", \t/"; char *p, *s = strdup_drhook(drhook_timed_kill); p = strtok(s,delim); while (p) { int target_myproc, target_omptid, target_sig; double start_time; int nelems = sscanf(p,"%d:%d:%d:%lf", &target_myproc, &target_omptid, &target_sig, &start_time); int ntids = 1; coml_get_max_threads_(&ntids); if (nelems == 4 && (target_myproc == myproc || target_myproc == -1) && (target_omptid == -1 || (target_omptid >= 1 && target_omptid <= ntids)) && (target_sig >= 1 && target_sig <= NSIG) && start_time > 0) { #if 1 { extern void run_fortran_omp_parallel_ipfipipipdpstr_(const int *, void (*func)(const int *, const int *, const int *, const double *, const char *, int len), const int *, const int *, const int *, const double *, const char *, int len); run_fortran_omp_parallel_ipfipipipdpstr_(&ntids,set_killer_timer, &ntids,&target_omptid,&target_sig,&start_time,p,strlen(p)); } #else #pragma omp parallel num_threads(ntids) { set_killer_timer(&ntids,&target_omptid,&target_sig,&start_time,p,strlen(p)); } #endif } p = strtok(NULL,delim); } free_drhook(s); } #endif } #endif
GB_binop__rdiv_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__rdiv_uint32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__rdiv_uint32) // A.*B function (eWiseMult): GB (_AemultB_03__rdiv_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_uint32) // A*D function (colscale): GB (_AxD__rdiv_uint32) // D*A function (rowscale): GB (_DxB__rdiv_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__rdiv_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__rdiv_uint32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_uint32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_uint32) // C=scalar+B GB (_bind1st__rdiv_uint32) // C=scalar+B' GB (_bind1st_tran__rdiv_uint32) // C=A+scalar GB (_bind2nd__rdiv_uint32) // C=A'+scalar GB (_bind2nd_tran__rdiv_uint32) // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = GB_IDIV_UNSIGNED (bij, aij, 32) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_IDIV_UNSIGNED (y, x, 32) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_RDIV || GxB_NO_UINT32 || GxB_NO_RDIV_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__rdiv_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__rdiv_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__rdiv_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__rdiv_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__rdiv_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = Bx [p] ; Cx [p] = GB_IDIV_UNSIGNED (bij, x, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rdiv_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = Ax [p] ; Cx [p] = GB_IDIV_UNSIGNED (y, aij, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_UNSIGNED (aij, x, 32) ; \ } GrB_Info GB (_bind1st_tran__rdiv_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_UNSIGNED (y, aij, 32) ; \ } GrB_Info GB (_bind2nd_tran__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mattran.c
#include "matrix.h" /** \brief Computes the transpose of a matrix * * \param[in] A Input matrix * \param[in] result Matrix to store the result * \return \f$ \mathbf{A}^T \f$ * */ MATRIX mat_tran(MATRIX A, MATRIX result) { int i, j, m, n; m = MatCol(A); n = MatRow(A); if(result==NULL) if((result = mat_creat(m,n, UNDEFINED))==NULL) return mat_error(MAT_MALLOC); #pragma omp parallel for private(j) for(i=0; i<m; ++i) { for (j=0; j<n; ++j) { result[i][j] = A[j][i]; } } return result; }
8990.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4096x4096. */ #include "convolution-2d.h" /* Array initialization. */ static void init_array (int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { // printf("Initializing Array\n"); int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { A[i][j] = ((DATA_TYPE) (i + j) / nj); } } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nj, DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { fprintf(stderr, DATA_PRINTF_MODIFIER, B[i][j]); if ((i * NJ + j) % 20 == 0) fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_conv2d(int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; #pragma scop for (i = 1; i < _PB_NI - 1; ++i) { #pragma omp target teams distribute schedule(dynamic, 1) for (j = 1; j < _PB_NJ - 1; ++j) { B[i][j] = 0.2 * A[i-1][j-1] + 0.5 * A[i-1][j] + -0.8 * A[i-1][j+1] + -0.3 * A[ i ][j-1] + 0.6 * A[ i ][j] + -0.9 * A[ i ][j+1] + 0.4 * A[i+1][j-1] + 0.7 * A[i+1][j] + 0.1 * A[i+1][j+1]; } } #pragma endscop // printf("Kernal computation complete !!\n"); } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NI, NJ, ni, nj); /* Initialize array(s). */ init_array (ni, nj, POLYBENCH_ARRAY(A)); /* Start timer. */ //polybench_start_instruments; polybench_timer_start(); /* Run kernel. */ kernel_conv2d (ni, nj, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B)); /* Stop and print timer. */ polybench_timer_stop(); polybench_timer_print(); //polybench_stop_instruments; //polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nj, POLYBENCH_ARRAY(B))); /* Be clean. */ POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); return 0; }
bli_dotv_bgq_int.c
/* BLIS An object-based framework for developing high-performance BLAS-like libraries. Copyright (C) 2014, The University of Texas at Austin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of The University of Texas at Austin nor the names of its contributors may be used to endorse or promote products derived derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "blis.h" void bli_ddotv_bgq_int ( conj_t conjx, conj_t conjy, dim_t n, double* restrict x, inc_t incx, double* restrict y, inc_t incy, double* restrict rho, cntx_t* cntx ) { bool_t use_ref = FALSE; // If the vector lengths are zero, set rho to zero and return. if ( bli_zero_dim1( n ) ) { PASTEMAC(d,set0s)( rho ); return; } // If there is anything that would interfere with our use of aligned // vector loads/stores, call the reference implementation. if ( incx != 1 || incy != 1 || bli_is_unaligned_to( x, 32 ) || bli_is_unaligned_to( y, 32 ) ) use_ref = TRUE; // Call the reference implementation if needed. if ( use_ref ) { BLIS_DDOTV_KERNEL_REF( conjx, conjy, n, x, incx, y, incy, rho, cntx ); return; } dim_t n_run = n / 4; dim_t n_left = n % 4; double rhos = 0.0; #pragma omp parallel reduction(+:rhos) { dim_t n_threads; dim_t t_id = omp_get_thread_num(); n_threads = omp_get_num_threads(); vector4double rhov = vec_splats( 0.0 ); vector4double xv, yv; for ( dim_t i = t_id; i < n_run; i += n_threads ) { xv = vec_lda( 0 * sizeof(double), &x[i*4] ); yv = vec_lda( 0 * sizeof(double), &y[i*4] ); rhov = vec_madd( xv, yv, rhov ); } rhos += vec_extract( rhov, 0 ); rhos += vec_extract( rhov, 1 ); rhos += vec_extract( rhov, 2 ); rhos += vec_extract( rhov, 3 ); } for ( dim_t i = 0; i < n_left; i++ ) { rhos += x[4*n_run + i] * y[4*n_run + i]; } *rho = rhos; }
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 24; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
prox_lib.h
/*! * Modifications Copyright 2017-2018 H2O.ai, Inc. */ #ifndef PROX_LIB_H_ #define PROX_LIB_H_ #include <algorithm> #include <cmath> #include <cstdio> #include <limits> #include <vector> #ifdef __CUDACC__ #include <thrust/device_vector.h> #include <thrust/functional.h> #include <thrust/inner_product.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/reduce.h> #include <thrust/execution_policy.h> #define __DEVICE__ __device__ #else #define __DEVICE__ #endif #include "interface_defs.h" // List of functions supported by the proximal operator library. enum Function { kAbs, // f(x) = |x| kExp, // f(x) = e^x kHuber, // f(x) = huber(x) kIdentity, // f(x) = x kIndBox01, // f(x) = I(0 <= x <= 1) kIndEq0, // f(x) = I(x = 0) kIndGe0, // f(x) = I(x >= 0) kIndLe0, // f(x) = I(x <= 0) kLogistic, // f(x) = log(1 + e^x) kMaxNeg0, // f(x) = max(0, -x) kMaxPos0, // f(x) = max(0, x) kNegEntr, // f(x) = x log(x) kNegLog, // f(x) = -log(x) kRecipr, // f(x) = 1/x kSquare, // f(x) = (1/2) x^2 kZero }; // f(x) = 0 // Object associated with the generic function c * f(a * x - b) + d * x + e * x * x. // Parameters a and c default to 1, while b, d and e default to 0. template <typename T> struct FunctionObj { Function h; T a, b, c, d, e; FunctionObj(Function h, T a, T b, T c, T d, T e) : h(h), a(a), b(b), c(c), d(d), e(e) { CheckConsts(); } FunctionObj(Function h, T a, T b, T c, T d) : h(h), a(a), b(b), c(c), d(d), e(0) { CheckConsts(); } FunctionObj(Function h, T a, T b, T c) : h(h), a(a), b(b), c(c), d(0), e(0) { CheckConsts(); } FunctionObj(Function h, T a, T b) : h(h), a(a), b(b), c(1), d(0), e(0) { } FunctionObj(Function h, T a) : h(h), a(a), b(0), c(1), d(0), e(0) { } explicit FunctionObj(Function h) : h(h), a(1), b(0), c(1), d(0), e(0) { } FunctionObj() : h(kZero), a(1), b(0), c(1), d(0), e(0) { } void CheckConsts() { if (c < static_cast<T>(0)) Printf("WARNING c < 0. Function not convex. Using c = 0"); if (e < static_cast<T>(0)) Printf("WARNING e < 0. Function not convex. Using e = 0"); c = std::max(c, static_cast<T>(0)); e = std::max(e, static_cast<T>(0)); } }; // Local Functions. namespace { // Evaluate abs(x) __DEVICE__ inline double Abs(double x) { return fabs(x); } __DEVICE__ inline float Abs(float x) { return fabsf(x); } // Evaluate acos(x) __DEVICE__ inline double Acos(double x) { return acos(x); } __DEVICE__ inline float Acos(float x) { return acosf(x); } // Evaluate cos(x) __DEVICE__ inline double Cos(double x) { return cos(x); } __DEVICE__ inline float Cos(float x) { return cosf(x); } // Evaluate e^x __DEVICE__ inline double Exp(double x) { return exp(x); } __DEVICE__ inline float Exp(float x) { return expf(x); } // Evaluate log(x) __DEVICE__ inline double Log(double x) { return log(x); } __DEVICE__ inline float Log(float x) { return logf(x); } // Evaluate max(x, y) __DEVICE__ inline double Max(double x, double y) { return fmax(x, y); } __DEVICE__ inline float Max(float x, float y) { return fmaxf(x, y); } // Evaluate max(x, y) __DEVICE__ inline double Min(double x, double y) { return fmin(x, y); } __DEVICE__ inline float Min(float x, float y) { return fminf(x, y); } // Evaluate x^y __DEVICE__ inline double Pow(double x, double y) { return pow(x, y); } __DEVICE__ inline float Pow(float x, float y) { return powf(x, y); } // Evaluate sqrt(x) __DEVICE__ inline double Sqrt(double x) { return sqrt(x); } __DEVICE__ inline float Sqrt(float x) { return sqrtf(x); } // Numeric Epsilon. template <typename T> __DEVICE__ inline T Epsilon(); template <> __DEVICE__ inline double Epsilon<double>() { return 4e-16; } template <> __DEVICE__ inline float Epsilon<float>() { return 1e-7f; } // Evaluate tol template <typename T> __DEVICE__ inline T Tol(); template <> __DEVICE__ inline double Tol() { return 1e-10; } template <> __DEVICE__ inline float Tol() { return 1e-5f; } // Evalution of max(0, x). template <typename T> __DEVICE__ inline T MaxPos(T x) { return Max(static_cast<T>(0), x); } // Evalution of max(0, -x). template <typename T> __DEVICE__ inline T MaxNeg(T x) { return Max(static_cast<T>(0), -x); } // Evalution of sign(x) template <typename T> __DEVICE__ inline T Sign(T x) { return x >= 0 ? 1 : -1; } // LambertW(Exp(x)) // Evaluate the principal branch of the Lambert W function. // ref: http://keithbriggs.info/software/LambertW.c template <typename T> __DEVICE__ inline T LambertWExp(T x) { T w; if (x > static_cast<T>(100)) { // Approximation for x in [100, 700]. T log_x = Log(x); return static_cast<T>(-0.36962844) + x - static_cast<T>(0.97284858) * log_x + static_cast<T>(1.3437973) / log_x; } else if (x < static_cast<T>(0)) { T p = Sqrt(static_cast<T>(2.0) * (Exp(x + static_cast<T>(1)) + static_cast<T>(1))); w = static_cast<T>(-1.0) + p * (static_cast<T>(1.0) + p * (static_cast<T>(-1.0 / 3.0) + p * static_cast<T>(11.0 / 72.0))); } else { w = x; } if (x > static_cast<T>(1.098612288668110)) { w -= Log(w); } for (unsigned int i = 0u; i < 10u; i++) { T e = Exp(w); T t = w * e - Exp(x); T p = w + static_cast<T>(1.); t /= e * p - static_cast<T>(0.5) * (p + static_cast<T>(1.0)) * t / p; w -= t; if (Abs(t) < Epsilon<T>() * (static_cast<T>(1) + Abs(w))) break; } return w; } // Find the root of a cubic x^3 + px^2 + qx + r = 0 with a single positive root. // ref: http://math.stackexchange.com/questions/60376 template <typename T> __DEVICE__ inline T CubicSolve(T p, T q, T r) { T s = p / 3, s2 = s * s, s3 = s2 * s; T a = -s2 + q / 3; T b = s3 - s * q / 2 + r / 2; T a3 = a * a * a; T b2 = b * b; if (a3 + b2 >= 0) { T A = Pow(Sqrt(a3 + b2) - b, static_cast<T>(1) / 3); return -s - a / A + A; } else { T A = Sqrt(-a3); T B = Acos(-b / A); T C = Pow(A, static_cast<T>(1) / 3); return -s + (C - a / C) * Cos(B / 3); } } } // namespace // Proximal operator definitions. // // Each of the following functions corresponds to one of the Function enums. // All functions accept one argument x and five parameters (a, b, c, d and rho) // and returns the evaluation of // // x -> Prox{c * f(a * x - b) + d * x + e * x ^ 2}, // // where Prox{.} is the proximal operator with penalty parameter rho. template <typename T> __DEVICE__ inline T ProxAbs(T v, T rho) { return MaxPos(v - 1 / rho) - MaxNeg(v + 1 / rho); } template <typename T> __DEVICE__ inline T ProxNegEntr(T v, T rho) { // Use double precision. return static_cast<T>( LambertWExp<double>( static_cast<double>((rho * v - 1) + Log(rho)))) / rho; } template <typename T> __DEVICE__ inline T ProxExp(T v, T rho) { return v - static_cast<T>( LambertWExp<double>(static_cast<double>(v - Log(rho)))); } template <typename T> __DEVICE__ inline T ProxHuber(T v, T rho) { return Abs(v) < 1 + 1 / rho ? v * rho / (1 + rho) : v - Sign(v) / rho; } template <typename T> __DEVICE__ inline T ProxIdentity(T v, T rho) { return v - 1 / rho; } template <typename T> __DEVICE__ inline T ProxIndBox01(T v, T rho) { return v <= 0 ? 0 : v >= 1 ? 1 : v; } template <typename T> __DEVICE__ inline T ProxIndEq0(T v, T rho) { return 0; } template <typename T> __DEVICE__ inline T ProxIndGe0(T v, T rho) { return v <= 0 ? 0 : v; } template <typename T> __DEVICE__ inline T ProxIndLe0(T v, T rho) { return v >= 0 ? 0 : v; } template <typename T> __DEVICE__ inline T ProxLogistic(T v, T rho) { // Initial guess based on piecewise approximation. T x; if (v < static_cast<T>(-2.5)) x = v; else if (v > static_cast<T>(2.5) + 1 / rho) x = v - 1 / rho; else x = (rho * v - static_cast<T>(0.5)) / (static_cast<T>(0.2) + rho); // Newton iteration. T l = v - 1 / rho, u = v; for (unsigned int i = 0; i < 5; ++i) { T inv_ex = 1 / (1 + Exp(-x)); T f = inv_ex + rho * (x - v); T g = inv_ex * (1 - inv_ex) + rho; if (f < 0) l = x; else u = x; x = x - f / g; x = Min(x, u); x = Max(x, l); } // Guarded method if not converged. for (unsigned int i = 0; u - l > Tol<T>() && i < 100; ++i) { T g_rho = 1 / (rho * (1 + Exp(-x))) + (x - v); if (g_rho > 0) { l = Max(l, x - g_rho); u = x; } else { u = Min(u, x - g_rho); l = x; } x = (u + l) / 2; } return x; } template <typename T> __DEVICE__ inline T ProxMaxNeg0(T v, T rho) { T z = v >= 0 ? v : 0; return v + 1 / rho <= 0 ? v + 1 / rho : z; } template <typename T> __DEVICE__ inline T ProxMaxPos0(T v, T rho) { T z = v <= 0 ? v : 0; return v >= 1 / rho ? v - 1 / rho : z; } template <typename T> __DEVICE__ inline T ProxNegLog(T v, T rho) { return (v + Sqrt(v * v + 4 / rho)) / 2; } template <typename T> __DEVICE__ inline T ProxRecipr(T v, T rho) { v = Max(v, static_cast<T>(0)); return CubicSolve(-v, static_cast<T>(0), -1 / rho); } template <typename T> __DEVICE__ inline T ProxSquare(T v, T rho) { return rho * v / (1 + rho); } template <typename T> __DEVICE__ inline T ProxZero(T v, T rho) { return v; } #define SMALL 1E-30 // ok for float or double for this purpose // Evaluates the proximal operator of f. template <typename T> __DEVICE__ inline T ProxEval(const FunctionObj<T> &f_obj, T v, T rho) { const T a = f_obj.a, b = f_obj.b, c = f_obj.c, d = f_obj.d, e = f_obj.e; v = a * (v * rho - d) / (SMALL + e + rho) - b; rho = (e + rho) / (SMALL + c * a * a); // Assumes c>=0 , as original paper assumes. This is so weight can be 0. switch (f_obj.h) { case kAbs: v = ProxAbs(v, rho); break; case kNegEntr: v = ProxNegEntr(v, rho); break; case kExp: v = ProxExp(v, rho); break; case kHuber: v = ProxHuber(v, rho); break; case kIdentity: v = ProxIdentity(v, rho); break; case kIndBox01: v = ProxIndBox01(v, rho); break; case kIndEq0: v = ProxIndEq0(v, rho); break; case kIndGe0: v = ProxIndGe0(v, rho); break; case kIndLe0: v = ProxIndLe0(v, rho); break; case kLogistic: v = ProxLogistic(v, rho); break; case kMaxNeg0: v = ProxMaxNeg0(v, rho); break; case kMaxPos0: v = ProxMaxPos0(v, rho); break; case kNegLog: v = ProxNegLog(v, rho); break; case kRecipr: v = ProxRecipr(v, rho); break; case kSquare: v = ProxSquare(v, rho); break; case kZero: default: v = ProxZero(v, rho); break; } return (v + b) / (SMALL+a); // TODO: assumes a>=0, which is normal but not required by paper. } // Function definitions. // // Each of the following functions corresponds to one of the Function enums. // All functions accept one argument x and four parameters (a, b, c, and d) // and returns the evaluation of // // x -> c * f(a * x - b) + d * x. template <typename T> __DEVICE__ inline T FuncAbs(T x) { return Abs(x); } template <typename T> __DEVICE__ inline T FuncNegEntr(T x) { return x <= 0 ? 0 : x * Log(x); } template <typename T> __DEVICE__ inline T FuncExp(T x) { return Exp(x); } template <typename T> __DEVICE__ inline T FuncHuber(T x) { T xabs = Abs(x); T xabs2 = xabs * xabs; return xabs < static_cast<T>(1) ? xabs2 / 2 : xabs - static_cast<T>(0.5); } template <typename T> __DEVICE__ inline T FuncIdentity(T x) { return x; } template <typename T> __DEVICE__ inline T FuncIndBox01(T x) { return 0; } template <typename T> __DEVICE__ inline T FuncIndEq0(T x) { return 0; } template <typename T> __DEVICE__ inline T FuncIndGe0(T x) { return 0; } template <typename T> __DEVICE__ inline T FuncIndLe0(T x) { return 0; } template <typename T> __DEVICE__ inline T FuncLogistic(T x) { return Log(1 + Exp(x)); } template <typename T> __DEVICE__ inline T FuncMaxNeg0(T x) { return MaxNeg(x); } template <typename T> __DEVICE__ inline T FuncMaxPos0(T x) { return MaxPos(x); } template <typename T> __DEVICE__ inline T FuncNegLog(T x) { x = Max(static_cast<T>(0), x); return -Log(x); } template <typename T> __DEVICE__ inline T FuncRecpr(T x) { x = Max(static_cast<T>(0), x); return 1 / x; } template <typename T> __DEVICE__ inline T FuncSquare(T x) { return x * x / 2; } template <typename T> __DEVICE__ inline T FuncZero(T x) { return 0; } // Evaluates the function f. template <typename T> __DEVICE__ inline T FuncEval(const FunctionObj<T> &f_obj, T x) { T dx = f_obj.d * x; T ex = f_obj.e * x * x / 2; x = f_obj.a * x - f_obj.b; switch (f_obj.h) { case kAbs: x = FuncAbs(x); break; case kNegEntr: x = FuncNegEntr(x); break; case kExp: x = FuncExp(x); break; case kHuber: x = FuncHuber(x); break; case kIdentity: x = FuncIdentity(x); break; case kIndBox01: x = FuncIndBox01(x); break; case kIndEq0: x = FuncIndEq0(x); break; case kIndGe0: x = FuncIndGe0(x); break; case kIndLe0: x = FuncIndLe0(x); break; case kLogistic: x = FuncLogistic(x); break; case kMaxNeg0: x = FuncMaxNeg0(x); break; case kMaxPos0: x = FuncMaxPos0(x); break; case kNegLog: x = FuncNegLog(x); break; case kRecipr: x = FuncRecpr(x); break; case kSquare: x = FuncSquare(x); break; case kZero: default: x = FuncZero(x); break; } return f_obj.c * x + dx + ex; } // Projection onto subgradient definitions // // Each of the following functions corresponds to one of the Function enums. // All functions accept one argument x and five parameters (a, b, c, d, and e) // and returns the evaluation of // // x -> ProjSubgrad{c * f(a * x - b) + d * x + (1/2) e * x ^ 2}, // // where ProjSubgrad{.} is the projection onto the subgradient of the function. template <typename T> __DEVICE__ inline T ProjSubgradAbs(T v, T x) { if (x < static_cast<T>(0.)) return static_cast<T>(-1.); else if (x > static_cast<T>(0.)) return static_cast<T>(1.); else return Max(static_cast<T>(-1.), Min(static_cast<T>(1.), v)); } template <typename T> __DEVICE__ inline T ProjSubgradNegEntr(T v, T x) { return -Log(x) - static_cast<T>(1.); } template <typename T> __DEVICE__ inline T ProjSubgradExp(T v, T x) { return Exp(x); } template <typename T> __DEVICE__ inline T ProjSubgradHuber(T v, T x) { return Max(static_cast<T>(-1.), Min(static_cast<T>(1.), x)); } template <typename T> __DEVICE__ inline T ProjSubgradIdentity(T v, T x) { return static_cast<T>(1.); } template <typename T> __DEVICE__ inline T ProjSubgradIndBox01(T v, T x) { if (x <= static_cast<T>(0.)) return Min(static_cast<T>(0.), v); else if (x >= static_cast<T>(1.)) return Max(static_cast<T>(0.), v); else return static_cast<T>(0.); } template <typename T> __DEVICE__ inline T ProjSubgradIndEq0(T v, T x) { return v; } template <typename T> __DEVICE__ inline T ProjSubgradIndGe0(T v, T x) { if (x <= static_cast<T>(0.)) return Min(static_cast<T>(0.), v); else return static_cast<T>(0.); } template <typename T> __DEVICE__ inline T ProjSubgradIndLe0(T v, T x) { if (x >= static_cast<T>(0.)) return Max(static_cast<T>(0.), v); else return static_cast<T>(0.); } template <typename T> __DEVICE__ inline T ProjSubgradLogistic(T v, T x) { return Exp(x) / (static_cast<T>(1.) + Exp(x)); } template <typename T> __DEVICE__ inline T ProjSubgradMaxNeg0(T v, T x) { if (x < static_cast<T>(0.)) return static_cast<T>(-1.); else if (x > static_cast<T>(0.)) return static_cast<T>(0.); else return Min(static_cast<T>(0.), Max(static_cast<T>(-1.), v)); } template <typename T> __DEVICE__ inline T ProjSubgradMaxPos0(T v, T x) { if (x < static_cast<T>(0.)) return static_cast<T>(0.); else if (x > static_cast<T>(0.)) return static_cast<T>(1.); else return Min(static_cast<T>(1.), Max(static_cast<T>(0.), v)); } template <typename T> __DEVICE__ inline T ProjSubgradNegLog(T v, T x) { return static_cast<T>(-1.) / x; } template <typename T> __DEVICE__ inline T ProjSubgradRecipr(T v, T x) { return static_cast<T>(1.) / (x * x); } template <typename T> __DEVICE__ inline T ProjSubgradSquare(T v, T x) { return x; } template <typename T> __DEVICE__ inline T ProjSubgradZero(T v, T x) { return static_cast<T>(0.); } // Evaluates the projection of v onto the subgradient of f at x. template <typename T> __DEVICE__ inline T ProjSubgradEval(const FunctionObj<T> &f_obj, T v, T x) { const T a = f_obj.a, b = f_obj.b, c = f_obj.c, d = f_obj.d, e = f_obj.e; if (a == static_cast<T>(0.) || c == static_cast<T>(0.)) return d + e * x; v = static_cast<T>(1.) / (a * c) * (v - d - e * x); T axb = a * x - b; switch (f_obj.h) { case kAbs: v = ProjSubgradAbs(v, axb); break; case kNegEntr: v = ProjSubgradNegEntr(v, axb); break; case kExp: v = ProjSubgradExp(v, axb); break; case kHuber: v = ProjSubgradHuber(v, axb); break; case kIdentity: v = ProjSubgradIdentity(v, axb); break; case kIndBox01: v = ProjSubgradIndBox01(v, axb); break; case kIndEq0: v = ProjSubgradIndEq0(v, axb); break; case kIndGe0: v = ProjSubgradIndGe0(v, axb); break; case kIndLe0: v = ProjSubgradIndLe0(v, axb); break; case kLogistic: v = ProjSubgradLogistic(v, axb); break; case kMaxNeg0: v = ProjSubgradMaxNeg0(v, axb); break; case kMaxPos0: v = ProjSubgradMaxPos0(v, axb); break; case kNegLog: v = ProjSubgradNegLog(v, axb); break; case kRecipr: v = ProjSubgradRecipr(v, axb); break; case kSquare: v = ProjSubgradSquare(v, axb); break; case kZero: default: v = ProjSubgradZero(v, axb); break; } return a * c * v + d + e * x; } // Evaluates the proximal operator Prox{f_obj[i]}(x_in[i]) -> x_out[i]. // // @param f_obj Vector of function objects. // @param rho Penalty parameter. // @param x_in Array to which proximal operator will be applied. // @param x_out Array to which result will be written. template <typename T> void ProxEval(const std::vector<FunctionObj<T> > &f_obj, T rho, const T *x_in, T *x_out) { #ifdef _OPENMP #pragma omp parallel for #endif for (unsigned int i = 0; i < f_obj.size(); ++i) x_out[i] = ProxEval(f_obj[i], x_in[i], rho); } // Returns evalution of Sum_i Func{f_obj[i]}(x_in[i]). // // @param f_obj Vector of function objects. // @param x_in Array to which function will be applied. // @param x_out Array to which result will be written. // @returns Evaluation of sum of functions. template <typename T> T FuncEval(const std::vector<FunctionObj<T> > &f_obj, const T* x_in) { T sum = 0; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for (unsigned int i = 0; i < f_obj.size(); ++i) sum += FuncEval(f_obj[i], x_in[i]); return sum; } // Projection onto the subgradient at x_in // ProjSubgrad{f_obj[i]}(x_in[i], v_in[i]) -> x_out[i]. // // @param f_obj Vector of function objects. // @param x_in Array of points at which subgradient should be evaluated. // @param v_in Array of points that should be projected onto the subgradient. // @param v_out Array to which result will be written. template <typename T> void ProjSubgradEval(const std::vector<FunctionObj<T> > &f_obj, const T *x_in, const T *v_in, T *v_out) { #ifdef _OPENMP #pragma omp parallel for #endif for (unsigned int i = 0; i < f_obj.size(); ++i) v_out[i] = ProjSubgradEval(f_obj[i], v_in[i], x_in[i]); } #ifdef __CUDACC__ template <typename T> struct ProxEvalF : thrust::binary_function<FunctionObj<T>, T, T> { T rho; __device__ ProxEvalF(T rho) : rho(rho) { } __device__ T operator()(const FunctionObj<T> &f_obj, T x) { return ProxEval(f_obj, x, rho); } }; template <typename T> void ProxEval(const thrust::device_vector<FunctionObj<T> > &f_obj, T rho, const T *x_in, T *x_out) { thrust::transform(thrust::device, f_obj.cbegin(), f_obj.cend(), thrust::device_pointer_cast(x_in), thrust::device_pointer_cast(x_out), ProxEvalF<T>(rho)); } template <typename T> struct FuncEvalF : thrust::binary_function<FunctionObj<T>, T, T> { __device__ T operator()(const FunctionObj<T> &f_obj, T x) { return FuncEval(f_obj, x); } }; template <typename T> T FuncEval(const thrust::device_vector<FunctionObj<T> > &f_obj, const T *x_in) { return thrust::inner_product(f_obj.cbegin(), f_obj.cend(), thrust::device_pointer_cast(x_in), static_cast<T>(0), thrust::plus<T>(), FuncEvalF<T>()); } template <typename T> struct ProjSubgradF { __device__ T operator()(const FunctionObj<T> &f_obj, const thrust::tuple<T, T>& vx) { return ProjSubgradEval(f_obj, thrust::get<0>(vx), thrust::get<1>(vx)); } }; template <typename T> void ProjSubgradEval(const thrust::device_vector<FunctionObj<T> > &f_obj, const T *v_in, const T *x_in, T *v_out) { thrust::transform(thrust::device, f_obj.cbegin(), f_obj.cend(), thrust::make_zip_iterator(thrust::make_tuple( thrust::device_pointer_cast(v_in), thrust::device_pointer_cast(x_in))), thrust::device_pointer_cast(v_out), ProjSubgradF<T>()); } #endif // __CUDACC__ #endif // PROX_LIB_H_
atomic_write_codegen.c
// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -target-cpu core2 -fopenmp -x c -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-apple-darwin10 -target-cpu core2 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-apple-darwin10 -target-cpu core2 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -target-cpu core2 -fopenmp-simd -x c -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s // RUN: %clang_cc1 -fopenmp-simd -x c -triple x86_64-apple-darwin10 -target-cpu core2 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp-simd -x c -triple x86_64-apple-darwin10 -target-cpu core2 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s // SIMD-ONLY0-NOT: {{__kmpc|__tgt}} // expected-no-diagnostics // REQUIRES: x86-registered-target #ifndef HEADER #define HEADER _Bool bv, bx; char cv, cx; unsigned char ucv, ucx; short sv, sx; unsigned short usv, usx; int iv, ix; unsigned int uiv, uix; long lv, lx; unsigned long ulv, ulx; long long llv, llx; unsigned long long ullv, ullx; float fv, fx; double dv, dx; long double ldv, ldx; _Complex int civ, cix; _Complex float cfv, cfx; _Complex double cdv, cdx; typedef int int4 __attribute__((__vector_size__(16))); int4 int4x; struct BitFields { int : 32; int a : 31; } bfx; struct BitFields_packed { int : 32; int a : 31; } __attribute__ ((__packed__)) bfx_packed; struct BitFields2 { int : 31; int a : 1; } bfx2; struct BitFields2_packed { int : 31; int a : 1; } __attribute__ ((__packed__)) bfx2_packed; struct BitFields3 { int : 11; int a : 14; } bfx3; struct BitFields3_packed { int : 11; int a : 14; } __attribute__ ((__packed__)) bfx3_packed; struct BitFields4 { short : 16; int a: 1; long b : 7; } bfx4; struct BitFields4_packed { short : 16; int a: 1; long b : 7; } __attribute__ ((__packed__)) bfx4_packed; typedef float float2 __attribute__((ext_vector_type(2))); float2 float2x; // Register "0" is currently an invalid register for global register variables. // Use "esp" instead of "0". // register int rix __asm__("0"); register int rix __asm__("esp"); int main() { // CHECK: store atomic i32 1, i32* getelementptr inbounds ({ i32, i32 }, { i32, i32 }* @civ, i32 0, i32 1) monotonic, align 4 #pragma omp atomic write __imag(civ) = 1; // CHECK: load i8, i8* // CHECK: store atomic i8 {{.*}} monotonic, align 1 #pragma omp atomic write bx = bv; // CHECK: load i8, i8* // CHECK: store atomic i8 {{.*}} release, align 1 #pragma omp atomic write release cx = cv; // CHECK: load i8, i8* // CHECK: store atomic i8 {{.*}} monotonic, align 1 #pragma omp atomic write ucx = ucv; // CHECK: load i16, i16* // CHECK: store atomic i16 {{.*}} monotonic, align 2 #pragma omp atomic write sx = sv; // CHECK: load i16, i16* // CHECK: store atomic i16 {{.*}} monotonic, align 2 #pragma omp atomic write usx = usv; // CHECK: load i32, i32* // CHECK: store atomic i32 {{.*}} monotonic, align 4 #pragma omp atomic write ix = iv; // CHECK: load i32, i32* // CHECK: store atomic i32 {{.*}} monotonic, align 4 #pragma omp atomic write uix = uiv; // CHECK: load i64, i64* // CHECK: store atomic i64 {{.*}} monotonic, align 8 #pragma omp atomic write lx = lv; // CHECK: load i64, i64* // CHECK: store atomic i64 {{.*}} monotonic, align 8 #pragma omp atomic write ulx = ulv; // CHECK: load i64, i64* // CHECK: store atomic i64 {{.*}} monotonic, align 8 #pragma omp atomic write llx = llv; // CHECK: load i64, i64* // CHECK: store atomic i64 {{.*}} monotonic, align 8 #pragma omp atomic write ullx = ullv; // CHECK: load float, float* // CHECK: bitcast float {{.*}} to i32 // CHECK: store atomic i32 {{.*}}, i32* bitcast (float* {{.*}} monotonic, align 4 #pragma omp atomic write fx = fv; // CHECK: load double, double* // CHECK: bitcast double {{.*}} to i64 // CHECK: store atomic i64 {{.*}}, i64* bitcast (double* {{.*}} monotonic, align 8 #pragma omp atomic write dx = dv; // CHECK: [[LD:%.+]] = load x86_fp80, x86_fp80* // CHECK: [[BITCAST:%.+]] = bitcast x86_fp80* [[LDTEMP:%.*]] to i8* // CHECK: call void @llvm.memset.p0i8.i64(i8* align 16 [[BITCAST]], i8 0, i64 16, i1 false) // CHECK: store x86_fp80 [[LD]], x86_fp80* [[LDTEMP]] // CHECK: [[BITCAST:%.+]] = bitcast x86_fp80* [[LDTEMP:%.*]] to i128* // CHECK: [[LD:%.+]] = load i128, i128* [[BITCAST]] // CHECK: store atomic i128 [[LD]], i128* bitcast (x86_fp80* {{.*}} monotonic, align 16 #pragma omp atomic write ldx = ldv; // CHECK: [[REAL_VAL:%.+]] = load i32, i32* getelementptr inbounds ({ i32, i32 }, { i32, i32 }* @{{.*}}, i32 0, i32 0) // CHECK: [[IMG_VAL:%.+]] = load i32, i32* getelementptr inbounds ({ i32, i32 }, { i32, i32 }* @{{.*}}, i32 0, i32 1) // CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds { i32, i32 }, { i32, i32 }* [[TEMP:%.+]], i32 0, i32 0 // CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds { i32, i32 }, { i32, i32 }* [[TEMP]], i32 0, i32 1 // CHECK: store i32 [[REAL_VAL]], i32* [[TEMP_REAL_REF]] // CHECK: store i32 [[IMG_VAL]], i32* [[TEMP_IMG_REF]] // CHECK: [[BITCAST:%.+]] = bitcast { i32, i32 }* [[TEMP]] to i8* // CHECK: call void @__atomic_store(i64 8, i8* bitcast ({ i32, i32 }* @{{.*}} to i8*), i8* [[BITCAST]], i32 0) #pragma omp atomic write cix = civ; // CHECK: [[REAL_VAL:%.+]] = load float, float* getelementptr inbounds ({ float, float }, { float, float }* @{{.*}}, i32 0, i32 0) // CHECK: [[IMG_VAL:%.+]] = load float, float* getelementptr inbounds ({ float, float }, { float, float }* @{{.*}}, i32 0, i32 1) // CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds { float, float }, { float, float }* [[TEMP:%.+]], i32 0, i32 0 // CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds { float, float }, { float, float }* [[TEMP]], i32 0, i32 1 // CHECK: store float [[REAL_VAL]], float* [[TEMP_REAL_REF]] // CHECK: store float [[IMG_VAL]], float* [[TEMP_IMG_REF]] // CHECK: [[BITCAST:%.+]] = bitcast { float, float }* [[TEMP]] to i8* // CHECK: call void @__atomic_store(i64 8, i8* bitcast ({ float, float }* @{{.*}} to i8*), i8* [[BITCAST]], i32 0) #pragma omp atomic write cfx = cfv; // CHECK: [[REAL_VAL:%.+]] = load double, double* getelementptr inbounds ({ double, double }, { double, double }* @{{.*}}, i32 0, i32 0) // CHECK: [[IMG_VAL:%.+]] = load double, double* getelementptr inbounds ({ double, double }, { double, double }* @{{.*}}, i32 0, i32 1) // CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds { double, double }, { double, double }* [[TEMP:%.+]], i32 0, i32 0 // CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds { double, double }, { double, double }* [[TEMP]], i32 0, i32 1 // CHECK: store double [[REAL_VAL]], double* [[TEMP_REAL_REF]] // CHECK: store double [[IMG_VAL]], double* [[TEMP_IMG_REF]] // CHECK: [[BITCAST:%.+]] = bitcast { double, double }* [[TEMP]] to i8* // CHECK: call void @__atomic_store(i64 16, i8* bitcast ({ double, double }* @{{.*}} to i8*), i8* [[BITCAST]], i32 5) // CHECK: call{{.*}} @__kmpc_flush( #pragma omp atomic seq_cst write cdx = cdv; // CHECK: load i8, i8* // CHECK: store atomic i64 {{.*}} monotonic, align 8 #pragma omp atomic write ulx = bv; // CHECK: load i8, i8* // CHECK: store atomic i8 {{.*}} monotonic, align 1 #pragma omp atomic write bx = cv; // CHECK: load i8, i8* // CHECK: store atomic i8 {{.*}} seq_cst, align 1 // CHECK: call{{.*}} @__kmpc_flush( #pragma omp atomic write, seq_cst cx = ucv; // CHECK: load i16, i16* // CHECK: store atomic i64 {{.*}} monotonic, align 8 #pragma omp atomic write ulx = sv; // CHECK: load i16, i16* // CHECK: store atomic i64 {{.*}} monotonic, align 8 #pragma omp atomic write lx = usv; // CHECK: load i32, i32* // CHECK: store atomic i32 {{.*}} seq_cst, align 4 // CHECK: call{{.*}} @__kmpc_flush( #pragma omp atomic seq_cst, write uix = iv; // CHECK: load i32, i32* // CHECK: store atomic i32 {{.*}} monotonic, align 4 #pragma omp atomic write ix = uiv; // CHECK: load i64, i64* // CHECK: [[VAL:%.+]] = trunc i64 %{{.*}} to i32 // CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds { i32, i32 }, { i32, i32 }* [[TEMP:%.+]], i32 0, i32 0 // CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds { i32, i32 }, { i32, i32 }* [[TEMP]], i32 0, i32 1 // CHECK: store i32 [[VAL]], i32* [[TEMP_REAL_REF]] // CHECK: store i32 0, i32* [[TEMP_IMG_REF]] // CHECK: [[BITCAST:%.+]] = bitcast { i32, i32 }* [[TEMP]] to i8* // CHECK: call void @__atomic_store(i64 8, i8* bitcast ({ i32, i32 }* @{{.+}} to i8*), i8* [[BITCAST]], i32 0) #pragma omp atomic write cix = lv; // CHECK: load i64, i64* // CHECK: store atomic i32 %{{.+}}, i32* bitcast (float* {{.*}} monotonic, align 4 #pragma omp atomic write fx = ulv; // CHECK: load i64, i64* // CHECK: store atomic i64 %{{.+}}, i64* bitcast (double* {{.*}} monotonic, align 8 #pragma omp atomic write dx = llv; // CHECK: load i64, i64* // CHECK: [[VAL:%.+]] = uitofp i64 %{{.+}} to x86_fp80 // CHECK: [[BITCAST:%.+]] = bitcast x86_fp80* [[TEMP:%.+]] to i8* // CHECK: call void @llvm.memset.p0i8.i64(i8* align 16 [[BITCAST]], i8 0, i64 16, i1 false) // CHECK: store x86_fp80 [[VAL]], x86_fp80* [[TEMP]] // CHECK: [[BITCAST:%.+]] = bitcast x86_fp80* [[TEMP]] to i128* // CHECK: [[VAL:%.+]] = load i128, i128* [[BITCAST]] // CHECK: store atomic i128 [[VAL]], i128* bitcast (x86_fp80* {{.*}} monotonic, align 16 #pragma omp atomic write ldx = ullv; // CHECK: load float, float* // CHECK: [[VAL:%.+]] = fptosi float %{{.*}} to i32 // CHECK: [[TEMP_REAL_REF:%.+]] = getelementptr inbounds { i32, i32 }, { i32, i32 }* [[TEMP:%.+]], i32 0, i32 0 // CHECK: [[TEMP_IMG_REF:%.+]] = getelementptr inbounds { i32, i32 }, { i32, i32 }* [[TEMP]], i32 0, i32 1 // CHECK: store i32 [[VAL]], i32* [[TEMP_REAL_REF]] // CHECK: store i32 0, i32* [[TEMP_IMG_REF]] // CHECK: [[BITCAST:%.+]] = bitcast { i32, i32 }* [[TEMP]] to i8* // CHECK: call void @__atomic_store(i64 8, i8* bitcast ({ i32, i32 }* @{{.+}} to i8*), i8* [[BITCAST]], i32 0) #pragma omp atomic write cix = fv; // CHECK: load double, double* // CHECK: store atomic i16 {{.*}} monotonic, align 2 #pragma omp atomic write sx = dv; // CHECK: load x86_fp80, x86_fp80* // CHECK: store atomic i8 {{.*}} monotonic, align 1 #pragma omp atomic write bx = ldv; // CHECK: load i32, i32* getelementptr inbounds ({ i32, i32 }, { i32, i32 }* @{{.+}}, i32 0, i32 0) // CHECK: load i32, i32* getelementptr inbounds ({ i32, i32 }, { i32, i32 }* @{{.+}}, i32 0, i32 1) // CHECK: icmp ne i32 %{{.+}}, 0 // CHECK: icmp ne i32 %{{.+}}, 0 // CHECK: or i1 // CHECK: store atomic i8 {{.*}} monotonic, align 1 #pragma omp atomic write bx = civ; // CHECK: load float, float* getelementptr inbounds ({ float, float }, { float, float }* @{{.*}}, i32 0, i32 0) // CHECK: store atomic i16 {{.*}} monotonic, align 2 #pragma omp atomic write usx = cfv; // CHECK: load double, double* getelementptr inbounds ({ double, double }, { double, double }* @{{.+}}, i32 0, i32 0) // CHECK: store atomic i64 {{.*}} monotonic, align 8 #pragma omp atomic write llx = cdv; // CHECK-DAG: [[IDX:%.+]] = load i16, i16* @{{.+}} // CHECK-DAG: load i8, i8* // CHECK-DAG: [[VEC_ITEM_VAL:%.+]] = zext i1 %{{.+}} to i32 // CHECK: [[I128VAL:%.+]] = load atomic i128, i128* bitcast (<4 x i32>* [[DEST:@.+]] to i128*) monotonic, align 16 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_I128:%.+]] = phi i128 [ [[I128VAL]], %{{.+}} ], [ [[FAILED_I128_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[BITCAST:%.+]] = bitcast <4 x i32>* [[LDTEMP:%.+]] to i128* // CHECK: store i128 [[OLD_I128]], i128* [[BITCAST]], // CHECK: [[VEC_VAL:%.+]] = load <4 x i32>, <4 x i32>* [[LDTEMP]] // CHECK: [[NEW_VEC_VAL:%.+]] = insertelement <4 x i32> [[VEC_VAL]], i32 [[VEC_ITEM_VAL]], i16 [[IDX]] // CHECK: store <4 x i32> [[NEW_VEC_VAL]], <4 x i32>* [[LDTEMP]] // CHECK: [[NEW_I128:%.+]] = load i128, i128* [[BITCAST]] // CHECK: [[RES:%.+]] = cmpxchg i128* bitcast (<4 x i32>* [[DEST]] to i128*), i128 [[OLD_I128]], i128 [[NEW_I128]] monotonic monotonic, align 16 // CHECK: [[FAILED_I128_OLD_VAL:%.+]] = extractvalue { i128, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i128, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write int4x[sv] = bv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32 // CHECK: [[PREV_VALUE:%.+]] = load atomic i32, i32* bitcast (i8* getelementptr (i8, i8* bitcast (%struct.BitFields* @{{.+}} to i8*), i64 4) to i32*) monotonic, align 4 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_BF_VALUE:%.+]] = phi i32 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[BF_VALUE:%.+]] = and i32 [[NEW_VAL]], 2147483647 // CHECK: [[BF_CLEAR:%.+]] = and i32 %{{.+}}, -2147483648 // CHECK: or i32 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i32 %{{.+}}, i32* [[LDTEMP:%.+]] // CHECK: [[NEW_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP]] // CHECK: [[RES:%.+]] = cmpxchg i32* bitcast (i8* getelementptr (i8, i8* bitcast (%struct.BitFields* @{{.+}} to i8*), i64 4) to i32*), i32 [[OLD_BF_VALUE]], i32 [[NEW_BF_VALUE]] monotonic monotonic, align 4 // CHECK: [[FAILED_OLD_VAL]] = extractvalue { i32, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i32, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write bfx.a = ldv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32 // CHECK: [[BITCAST:%.+]] = bitcast i32* [[LDTEMP:%.+]] to i8* // CHECK: call void @__atomic_load(i64 4, i8* getelementptr (i8, i8* bitcast (%struct.BitFields_packed* @{{.+}} to i8*), i64 4), i8* [[BITCAST]], i32 0) // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP]], // CHECK: store i32 [[OLD_BF_VALUE]], i32* [[LDTEMP1:%.+]], // CHECK: [[OLD_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP1]], // CHECK: [[BF_VALUE:%.+]] = and i32 [[NEW_VAL]], 2147483647 // CHECK: [[BF_CLEAR:%.+]] = and i32 [[OLD_BF_VALUE]], -2147483648 // CHECK: or i32 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i32 %{{.+}}, i32* [[LDTEMP1]] // CHECK: [[BITCAST_TEMP_OLD_BF_ADDR:%.+]] = bitcast i32* [[LDTEMP]] to i8* // CHECK: [[BITCAST_TEMP_NEW_BF_ADDR:%.+]] = bitcast i32* [[LDTEMP1]] to i8* // CHECK: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i64 4, i8* getelementptr (i8, i8* bitcast (%struct.BitFields_packed* @{{.+}} to i8*), i64 4), i8* [[BITCAST_TEMP_OLD_BF_ADDR]], i8* [[BITCAST_TEMP_NEW_BF_ADDR]], i32 0, i32 0) // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write bfx_packed.a = ldv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32 // CHECK: [[PREV_VALUE:%.+]] = load atomic i32, i32* getelementptr inbounds (%struct.BitFields2, %struct.BitFields2* @{{.+}}, i32 0, i32 0) monotonic, align 4 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_BF_VALUE:%.+]] = phi i32 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[BF_AND:%.+]] = and i32 [[NEW_VAL]], 1 // CHECK: [[BF_VALUE:%.+]] = shl i32 [[BF_AND]], 31 // CHECK: [[BF_CLEAR:%.+]] = and i32 %{{.+}}, 2147483647 // CHECK: or i32 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i32 %{{.+}}, i32* [[LDTEMP:%.+]] // CHECK: [[NEW_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP]] // CHECK: [[RES:%.+]] = cmpxchg i32* getelementptr inbounds (%struct.BitFields2, %struct.BitFields2* @{{.+}}, i32 0, i32 0), i32 [[OLD_BF_VALUE]], i32 [[NEW_BF_VALUE]] monotonic monotonic, align 4 // CHECK: [[FAILED_OLD_VAL]] = extractvalue { i32, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i32, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write bfx2.a = ldv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32 // CHECK: [[PREV_VALUE:%.+]] = load atomic i8, i8* getelementptr (i8, i8* bitcast (%struct.BitFields2_packed* @{{.+}} to i8*), i64 3) monotonic, align 1 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_BF_VALUE:%.+]] = phi i8 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[TRUNC:%.+]] = trunc i32 [[NEW_VAL]] to i8 // CHECK: [[BF_AND:%.+]] = and i8 [[TRUNC]], 1 // CHECK: [[BF_VALUE:%.+]] = shl i8 [[BF_AND]], 7 // CHECK: [[BF_CLEAR:%.+]] = and i8 %{{.+}}, 127 // CHECK: or i8 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i8 %{{.+}}, i8* [[LDTEMP:%.+]] // CHECK: [[NEW_BF_VALUE:%.+]] = load i8, i8* [[LDTEMP]] // CHECK: [[RES:%.+]] = cmpxchg i8* getelementptr (i8, i8* bitcast (%struct.BitFields2_packed* @{{.+}} to i8*), i64 3), i8 [[OLD_BF_VALUE]], i8 [[NEW_BF_VALUE]] monotonic monotonic, align 1 // CHECK: [[FAILED_OLD_VAL]] = extractvalue { i8, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i8, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write bfx2_packed.a = ldv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32 // CHECK: [[PREV_VALUE:%.+]] = load atomic i32, i32* getelementptr inbounds (%struct.BitFields3, %struct.BitFields3* @{{.+}}, i32 0, i32 0) monotonic, align 4 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_BF_VALUE:%.+]] = phi i32 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[BF_AND:%.+]] = and i32 [[NEW_VAL]], 16383 // CHECK: [[BF_VALUE:%.+]] = shl i32 [[BF_AND]], 11 // CHECK: [[BF_CLEAR:%.+]] = and i32 %{{.+}}, -33552385 // CHECK: or i32 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i32 %{{.+}}, i32* [[LDTEMP:%.+]] // CHECK: [[NEW_BF_VALUE:%.+]] = load i32, i32* [[LDTEMP]] // CHECK: [[RES:%.+]] = cmpxchg i32* getelementptr inbounds (%struct.BitFields3, %struct.BitFields3* @{{.+}}, i32 0, i32 0), i32 [[OLD_BF_VALUE]], i32 [[NEW_BF_VALUE]] monotonic monotonic, align 4 // CHECK: [[FAILED_OLD_VAL]] = extractvalue { i32, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i32, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write bfx3.a = ldv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32 // CHECK: [[LDTEMP:%.+]] = bitcast i32* %{{.+}} to i24* // CHECK: [[BITCAST:%.+]] = bitcast i24* %{{.+}} to i8* // CHECK: call void @__atomic_load(i64 3, i8* getelementptr (i8, i8* bitcast (%struct.BitFields3_packed* @{{.+}} to i8*), i64 1), i8* [[BITCAST]], i32 0) // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_VAL:%.+]] = load i24, i24* %{{.+}}, // CHECK: store i24 [[OLD_VAL]], i24* [[TEMP:%.+]], // CHECK: [[TRUNC:%.+]] = trunc i32 [[NEW_VAL]] to i24 // CHECK: [[BF_AND:%.+]] = and i24 [[TRUNC]], 16383 // CHECK: [[BF_VALUE:%.+]] = shl i24 [[BF_AND]], 3 // CHECK: [[BF_CLEAR:%.+]] = and i24 %{{.+}}, -131065 // CHECK: or i24 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i24 %{{.+}}, i24* [[TEMP]] // CHECK: [[BITCAST_TEMP_OLD_BF_ADDR:%.+]] = bitcast i24* [[LDTEMP]] to i8* // CHECK: [[BITCAST_TEMP_NEW_BF_ADDR:%.+]] = bitcast i24* [[TEMP]] to i8* // CHECK: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i64 3, i8* getelementptr (i8, i8* bitcast (%struct.BitFields3_packed* @{{.+}} to i8*), i64 1), i8* [[BITCAST_TEMP_OLD_BF_ADDR]], i8* [[BITCAST_TEMP_NEW_BF_ADDR]], i32 0, i32 0) // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write bfx3_packed.a = ldv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32 // CHECK: [[PREV_VALUE:%.+]] = load atomic i64, i64* bitcast (%struct.BitFields4* @{{.+}} to i64*) monotonic, align 8 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_BF_VALUE:%.+]] = phi i64 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[ZEXT:%.+]] = zext i32 [[NEW_VAL]] to i64 // CHECK: [[BF_AND:%.+]] = and i64 [[ZEXT]], 1 // CHECK: [[BF_VALUE:%.+]] = shl i64 [[BF_AND]], 16 // CHECK: [[BF_CLEAR:%.+]] = and i64 %{{.+}}, -65537 // CHECK: or i64 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i64 %{{.+}}, i64* [[LDTEMP:%.+]] // CHECK: [[NEW_BF_VALUE:%.+]] = load i64, i64* [[LDTEMP]] // CHECK: [[RES:%.+]] = cmpxchg i64* bitcast (%struct.BitFields4* @{{.+}} to i64*), i64 [[OLD_BF_VALUE]], i64 [[NEW_BF_VALUE]] monotonic monotonic, align 8 // CHECK: [[FAILED_OLD_VAL]] = extractvalue { i64, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i64, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write bfx4.a = ldv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i32 // CHECK: [[PREV_VALUE:%.+]] = load atomic i8, i8* getelementptr inbounds (%struct.BitFields4_packed, %struct.BitFields4_packed* @{{.+}}, i32 0, i32 0, i64 2) monotonic, align 1 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_BF_VALUE:%.+]] = phi i8 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[TRUNC:%.+]] = trunc i32 [[NEW_VAL]] to i8 // CHECK: [[BF_VALUE:%.+]] = and i8 [[TRUNC]], 1 // CHECK: [[BF_CLEAR:%.+]] = and i8 %{{.+}}, -2 // CHECK: or i8 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i8 %{{.+}}, i8* [[LDTEMP:%.+]] // CHECK: [[NEW_BF_VALUE:%.+]] = load i8, i8* [[LDTEMP]] // CHECK: [[RES:%.+]] = cmpxchg i8* getelementptr inbounds (%struct.BitFields4_packed, %struct.BitFields4_packed* @{{.+}}, i32 0, i32 0, i64 2), i8 [[OLD_BF_VALUE]], i8 [[NEW_BF_VALUE]] monotonic monotonic, align 1 // CHECK: [[FAILED_OLD_VAL]] = extractvalue { i8, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i8, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write bfx4_packed.a = ldv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i64 // CHECK: [[PREV_VALUE:%.+]] = load atomic i64, i64* bitcast (%struct.BitFields4* @{{.+}} to i64*) monotonic, align 8 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_BF_VALUE:%.+]] = phi i64 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[BF_AND:%.+]] = and i64 [[NEW_VAL]], 127 // CHECK: [[BF_VALUE:%.+]] = shl i64 [[BF_AND]], 17 // CHECK: [[BF_CLEAR:%.+]] = and i64 %{{.+}}, -16646145 // CHECK: or i64 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i64 %{{.+}}, i64* [[LDTEMP:%.+]] // CHECK: [[NEW_BF_VALUE:%.+]] = load i64, i64* [[LDTEMP]] // CHECK: [[RES:%.+]] = cmpxchg i64* bitcast (%struct.BitFields4* @{{.+}} to i64*), i64 [[OLD_BF_VALUE]], i64 [[NEW_BF_VALUE]] monotonic monotonic, align 8 // CHECK: [[FAILED_OLD_VAL]] = extractvalue { i64, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i64, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write bfx4.b = ldv; // CHECK: load x86_fp80, x86_fp80* @{{.+}} // CHECK: [[NEW_VAL:%.+]] = fptosi x86_fp80 %{{.+}} to i64 // CHECK: [[PREV_VALUE:%.+]] = load atomic i8, i8* getelementptr inbounds (%struct.BitFields4_packed, %struct.BitFields4_packed* @{{.+}}, i32 0, i32 0, i64 2) monotonic, align 1 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_BF_VALUE:%.+]] = phi i8 [ [[PREV_VALUE]], %[[EXIT]] ], [ [[FAILED_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[TRUNC:%.+]] = trunc i64 [[NEW_VAL]] to i8 // CHECK: [[BF_AND:%.+]] = and i8 [[TRUNC]], 127 // CHECK: [[BF_VALUE:%.+]] = shl i8 [[BF_AND]], 1 // CHECK: [[BF_CLEAR:%.+]] = and i8 %{{.+}}, 1 // CHECK: or i8 [[BF_CLEAR]], [[BF_VALUE]] // CHECK: store i8 %{{.+}}, i8* [[LDTEMP:%.+]] // CHECK: [[NEW_BF_VALUE:%.+]] = load i8, i8* [[LDTEMP]] // CHECK: [[RES:%.+]] = cmpxchg i8* getelementptr inbounds (%struct.BitFields4_packed, %struct.BitFields4_packed* @{{.+}}, i32 0, i32 0, i64 2), i8 [[OLD_BF_VALUE]], i8 [[NEW_BF_VALUE]] monotonic monotonic, align 1 // CHECK: [[FAILED_OLD_VAL]] = extractvalue { i8, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i8, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic relaxed write bfx4_packed.b = ldv; // CHECK: load i64, i64* // CHECK: [[VEC_ITEM_VAL:%.+]] = uitofp i64 %{{.+}} to float // CHECK: [[I64VAL:%.+]] = load atomic i64, i64* bitcast (<2 x float>* [[DEST:@.+]] to i64*) monotonic, align 8 // CHECK: br label %[[CONT:.+]] // CHECK: [[CONT]] // CHECK: [[OLD_I64:%.+]] = phi i64 [ [[I64VAL]], %{{.+}} ], [ [[FAILED_I64_OLD_VAL:%.+]], %[[CONT]] ] // CHECK: [[BITCAST:%.+]] = bitcast <2 x float>* [[LDTEMP:%.+]] to i64* // CHECK: store i64 [[OLD_I64]], i64* [[BITCAST]], // CHECK: [[VEC_VAL:%.+]] = load <2 x float>, <2 x float>* [[LDTEMP]] // CHECK: [[NEW_VEC_VAL:%.+]] = insertelement <2 x float> [[VEC_VAL]], float [[VEC_ITEM_VAL]], i64 0 // CHECK: store <2 x float> [[NEW_VEC_VAL]], <2 x float>* [[LDTEMP]] // CHECK: [[NEW_I64:%.+]] = load i64, i64* [[BITCAST]] // CHECK: [[RES:%.+]] = cmpxchg i64* bitcast (<2 x float>* [[DEST]] to i64*), i64 [[OLD_I64]], i64 [[NEW_I64]] monotonic monotonic, align 8 // CHECK: [[FAILED_I64_OLD_VAL:%.+]] = extractvalue { i64, i1 } [[RES]], 0 // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i64, i1 } [[RES]], 1 // CHECK: br i1 [[FAIL_SUCCESS]], label %[[EXIT:.+]], label %[[CONT]] // CHECK: [[EXIT]] #pragma omp atomic write relaxed float2x.x = ulv; // CHECK: call i32 @llvm.read_register.i32( // CHECK: sitofp i32 %{{.+}} to double // CHECK: bitcast double %{{.+}} to i64 // CHECK: store atomic i64 %{{.+}}, i64* bitcast (double* @{{.+}} to i64*) seq_cst, align 8 // CHECK: call{{.*}} @__kmpc_flush( #pragma omp atomic write seq_cst dv = rix; return 0; } #endif
reduction.c
#include <stdio.h> #include <stdlib.h> float sum(const float *a, const size_t n); int main(int argc, char* argv[]) { const size_t n = 1<<10; size_t i; float *a; a = malloc(n*sizeof(float)); for (i = 0; i < n; i++) { a[i] = (float)i; } printf("Sum: %f\n", sum(a, n)); free(a); } float sum(const float *a, const size_t n) { float total = 0.; size_t i; #pragma omp parallel for reduction(+:total) for (i = 0; i < n; i++) { total += a[i]; } return total; }
loop_order.c
#include <stdio.h> #include <omp.h> #define N 1024 #define THREADS 8 int main(void) { int errors = 0; int total_wait_errors = 0; int x[N]; int y[N]; int z[N]; int num_threads = -1; int rand_indexes[8]; for (int i = 0; i < N; i++) { x[i] = 1; y[i] = i + 1; z[i] = 2*(i + 1); } for (int i = 0; i < THREADS; i++) { rand_indexes[i] = rand()%(N + 1); } #pragma omp target parallel num_threads(THREADS) map(tofrom: x[0:N], num_threads, total_wait_errors) map(to: y[0:N], z[0:N]) { #pragma omp loop order(concurrent) for (int i = 0; i < N; i++) { x[i] += y[i]*z[i]; } if (x[rand_indexes[omp_get_thread_num()]] == 1) { #pragma omp atomic update total_wait_errors++; } if (omp_get_thread_num() == 0) { num_threads = omp_get_num_threads(); } } for (int i = 0; i < N; i++) { if(x[i] != 1 + (y[i]*z[i])) errors++; } if(errors || total_wait_errors){ printf("Fail!"); return 1; } printf("Success!"); return 0; }
GxB_Vector_Option_get.c
//------------------------------------------------------------------------------ // GxB_Vector_Option_get: get an option in a vector //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #include "GB.h" GrB_Info GxB_Vector_Option_get // gets the current option of a vector ( GrB_Vector v, // vector to query GxB_Option_Field field, // option to query ... // return value of the vector option ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GB_WHERE1 ("GxB_Vector_Option_get (v, field, &value)") ; GB_RETURN_IF_NULL_OR_FAULTY (v) ; ASSERT_VECTOR_OK (v, "v to get option", GB0) ; //-------------------------------------------------------------------------- // get the option //-------------------------------------------------------------------------- va_list ap ; switch (field) { case GxB_BITMAP_SWITCH : { va_start (ap, field) ; double *bitmap_switch = va_arg (ap, double *) ; va_end (ap) ; GB_RETURN_IF_NULL (bitmap_switch) ; (*bitmap_switch) = (double) v->bitmap_switch ; } break ; case GxB_SPARSITY_CONTROL : { va_start (ap, field) ; int *sparsity_control = va_arg (ap, int *) ; va_end (ap) ; GB_RETURN_IF_NULL (sparsity_control) ; (*sparsity_control) = v->sparsity_control ; } break ; case GxB_SPARSITY_STATUS : { va_start (ap, field) ; int *sparsity = va_arg (ap, int *) ; va_end (ap) ; GB_RETURN_IF_NULL (sparsity) ; (*sparsity) = GB_sparsity ((GrB_Matrix) v) ; } break ; case GxB_FORMAT : { // a GrB_Vector is always stored by-column va_start (ap, field) ; GxB_Format_Value *format = va_arg (ap, GxB_Format_Value *) ; va_end (ap) ; GB_RETURN_IF_NULL (format) ; (*format) = GxB_BY_COL ; } break ; case GxB_IS_HYPER : // historical; use GxB_SPARSITY_STATUS instead { // a GrB_Vector is never hypersparse va_start (ap, field) ; bool *v_is_hyper = va_arg (ap, bool *) ; va_end (ap) ; GB_RETURN_IF_NULL (v_is_hyper) ; (*v_is_hyper) = false ; } break ; default : return (GrB_INVALID_VALUE) ; } #pragma omp flush return (GrB_SUCCESS) ; }
omp_pause_resource.c
// RUN: %libomp-compile-and-run // Linking fails for icc 18/19 // UNSUPPORTED: icc-18, icc-19 #include <stdio.h> #include "omp_testsuite.h" int test_omp_pause_resource() { int fails, nthreads, my_dev; fails = 0; nthreads = 0; my_dev = omp_get_initial_device(); #pragma omp parallel #pragma omp single nthreads = omp_get_num_threads(); if (omp_pause_resource(omp_pause_soft, my_dev)) fails++; #pragma omp parallel shared(nthreads) #pragma omp single nthreads = omp_get_num_threads(); if (nthreads == 0) fails++; if (omp_pause_resource(omp_pause_hard, my_dev)) fails++; nthreads = 0; #pragma omp parallel shared(nthreads) #pragma omp single nthreads = omp_get_num_threads(); if (nthreads == 0) fails++; if (omp_pause_resource_all(omp_pause_soft)) fails++; nthreads = 0; #pragma omp parallel shared(nthreads) #pragma omp single nthreads = omp_get_num_threads(); if (nthreads == 0) fails++; return fails == 0; } int main() { int i; int num_failed = 0; for (i = 0; i < REPETITIONS; i++) { if (!test_omp_pause_resource()) { num_failed++; } } return num_failed; }
GB_select_phase1.c
//------------------------------------------------------------------------------ // GB_select_phase1: count entries in each vector for C=select(A,thunk) //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ //-------------------------------------------------------------------------- // get A and its slicing //-------------------------------------------------------------------------- const int64_t *restrict kfirst_Aslice = A_ek_slicing ; const int64_t *restrict klast_Aslice = A_ek_slicing + A_ntasks ; const int64_t *restrict pstart_Aslice = A_ek_slicing + A_ntasks * 2 ; const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ai = A->i ; int64_t avlen = A->vlen ; int64_t anvec = A->nvec ; #if defined ( GB_ENTRY_SELECTOR ) //========================================================================== // entry selector //========================================================================== ASSERT (GB_JUMBLED_OK (A)) ; // The count of live entries kth vector A(:,k) is reduced to the kth scalar // Cp(k). Each thread computes the reductions on roughly the same number // of entries, which means that a vector A(:,k) may be reduced by more than // one thread. The first vector A(:,kfirst) reduced by thread tid may be // partial, where the prior thread tid-1 (and other prior threads) may also // do some of the reductions for this same vector A(:,kfirst). The thread // tid reduces all vectors A(:,k) for k in the range kfirst+1 to klast-1. // The last vector A(:,klast) reduced by thread tid may also be partial. // Thread tid+1, and following threads, may also do some of the reduces for // A(:,klast). //-------------------------------------------------------------------------- // get A //-------------------------------------------------------------------------- const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ; size_t asize = A->type->size ; int64_t avdim = A->vdim ; ASSERT (GB_JUMBLED_OK (A)) ; //-------------------------------------------------------------------------- // reduce each slice //-------------------------------------------------------------------------- // each thread reduces its own part in parallel int tid ; #pragma omp parallel for num_threads(A_nthreads) schedule(dynamic,1) for (tid = 0 ; tid < A_ntasks ; tid++) { // if kfirst > klast then thread tid does no work at all int64_t kfirst = kfirst_Aslice [tid] ; int64_t klast = klast_Aslice [tid] ; Wfirst [tid] = 0 ; Wlast [tid] = 0 ; //---------------------------------------------------------------------- // reduce vectors kfirst to klast //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // find the part of A(:,k) to be reduced by this thread //------------------------------------------------------------------ int64_t j = GBH (Ah, k) ; int64_t pA, pA_end ; GB_get_pA (&pA, &pA_end, tid, k, kfirst, klast, pstart_Aslice, Ap, avlen) ; //------------------------------------------------------------------ // count entries in Ax [pA ... pA_end-1] //------------------------------------------------------------------ int64_t cjnz = 0 ; for ( ; pA < pA_end ; pA++) { ASSERT (Ai != NULL) ; int64_t i = Ai [pA] ; GB_TEST_VALUE_OF_ENTRY (keep, pA) ; if (keep) cjnz++ ; } if (k == kfirst) { Wfirst [tid] = cjnz ; } else if (k == klast) { Wlast [tid] = cjnz ; } else { Cp [k] = cjnz ; } } } //-------------------------------------------------------------------------- // reduce the first and last vector of each slice using a single thread //-------------------------------------------------------------------------- GB_ek_slice_merge1 (Cp, Wfirst, Wlast, A_ek_slicing, A_ntasks) ; #else //========================================================================== // positional selector (tril, triu, diag, offdiag, resize, row*) //========================================================================== ASSERT (!GB_JUMBLED (A)) ; //-------------------------------------------------------------------------- // tril, triu, diag, offdiag, resize: binary search in each vector //-------------------------------------------------------------------------- int64_t k ; #pragma omp parallel for num_threads(A_nthreads) schedule(guided) for (k = 0 ; k < anvec ; k++) { //---------------------------------------------------------------------- // get A(:,k) //---------------------------------------------------------------------- int64_t pA_start = GBP (Ap, k, avlen) ; int64_t pA_end = GBP (Ap, k+1, avlen) ; int64_t p = pA_start ; int64_t cjnz = 0 ; int64_t ajnz = pA_end - pA_start ; bool found = false ; if (ajnz > 0) { //------------------------------------------------------------------ // search for the entry A(i,k) //------------------------------------------------------------------ int64_t ifirst = GBI (Ai, pA_start, avlen) ; int64_t ilast = GBI (Ai, pA_end-1, avlen) ; #if defined ( GB_ROWINDEX_SELECTOR ) int64_t i = -ithunk ; #elif defined ( GB_ROWLE_SELECTOR ) || defined ( GB_ROWGT_SELECTOR ) int64_t i = ithunk ; #else // TRIL, TRIU, DIAG, OFFDIAG int64_t j = GBH (Ah, k) ; int64_t i = j-ithunk ; #endif if (i < ifirst) { // all entries in A(:,k) come after i ; } else if (i > ilast) { // all entries in A(:,k) come before i p = pA_end ; } else if (ajnz == avlen) { // A(:,k) is dense found = true ; p += i ; ASSERT (GBI (Ai, p, avlen) == i) ; } else { // binary search for A (i,k) int64_t pright = pA_end - 1 ; GB_SPLIT_BINARY_SEARCH (i, Ai, p, pright, found) ; } #if defined ( GB_TRIL_SELECTOR ) // keep p to pA_end-1 cjnz = pA_end - p ; #elif defined ( GB_ROWGT_SELECTOR ) // if found, keep p+1 to pA_end-1 // else keep p to pA_end-1 if (found) { p++ ; // now in both cases, keep p to pA_end-1 } // keep p to pA_end-1 cjnz = pA_end - p ; #elif defined ( GB_TRIU_SELECTOR ) \ || defined ( GB_ROWLE_SELECTOR ) // if found, keep pA_start to p // else keep pA_start to p-1 if (found) { p++ ; // now in both cases, keep pA_start to p-1 } // keep pA_start to p-1 cjnz = p - pA_start ; #elif defined ( GB_DIAG_SELECTOR ) // if found, keep p // else keep nothing cjnz = found ; if (!found) p = -1 ; // if (cjnz >= 0) keep p, else keep nothing #elif defined ( GB_OFFDIAG_SELECTOR ) || \ defined ( GB_ROWINDEX_SELECTOR ) // if found, keep pA_start to p-1 and p+1 to pA_end-1 // else keep pA_start to pA_end cjnz = ajnz - found ; if (!found) { p = pA_end ; // now just keep pA_start to p-1; p+1 to pA_end is // now empty } // in both cases, keep pA_start to p-1 and // p+1 to pA_end-1. If the entry is not found, then // p == pA_end, and all entries are kept. #endif } //---------------------------------------------------------------------- // log the result for the kth vector //---------------------------------------------------------------------- Zp [k] = p ; Cp [k] = cjnz ; } //-------------------------------------------------------------------------- // compute Wfirst and Wlast for each task //-------------------------------------------------------------------------- // Wfirst [0..A_ntasks-1] and Wlast [0..A_ntasks-1] are required for // constructing C_start_slice [0..A_ntasks-1] in GB_selector. for (int tid = 0 ; tid < A_ntasks ; tid++) { // if kfirst > klast then task tid does no work at all int64_t kfirst = kfirst_Aslice [tid] ; int64_t klast = klast_Aslice [tid] ; Wfirst [tid] = 0 ; Wlast [tid] = 0 ; if (kfirst <= klast) { int64_t pA_start = pstart_Aslice [tid] ; int64_t pA_end = GBP (Ap, kfirst+1, avlen) ; pA_end = GB_IMIN (pA_end, pstart_Aslice [tid+1]) ; if (pA_start < pA_end) { #if defined ( GB_TRIL_SELECTOR ) || \ defined ( GB_ROWGT_SELECTOR ) // keep Zp [kfirst] to pA_end-1 int64_t p = GB_IMAX (Zp [kfirst], pA_start) ; Wfirst [tid] = GB_IMAX (0, pA_end - p) ; #elif defined ( GB_TRIU_SELECTOR ) || \ defined ( GB_ROWLE_SELECTOR ) // keep pA_start to Zp [kfirst]-1 int64_t p = GB_IMIN (Zp [kfirst], pA_end) ; Wfirst [tid] = GB_IMAX (0, p - pA_start) ; #elif defined ( GB_DIAG_SELECTOR ) // task that owns the diagonal entry does this work int64_t p = Zp [kfirst] ; Wfirst [tid] = (pA_start <= p && p < pA_end) ? 1 : 0 ; #elif defined ( GB_OFFDIAG_SELECTOR ) || \ defined ( GB_ROWINDEX_SELECTOR ) // keep pA_start to Zp [kfirst]-1 int64_t p = GB_IMIN (Zp [kfirst], pA_end) ; Wfirst [tid] = GB_IMAX (0, p - pA_start) ; // keep Zp [kfirst]+1 to pA_end-1 p = GB_IMAX (Zp [kfirst]+1, pA_start) ; Wfirst [tid] += GB_IMAX (0, pA_end - p) ; #endif } } if (kfirst < klast) { int64_t pA_start = GBP (Ap, klast, avlen) ; int64_t pA_end = pstart_Aslice [tid+1] ; if (pA_start < pA_end) { #if defined ( GB_TRIL_SELECTOR ) || \ defined ( GB_ROWGT_SELECTOR ) // keep Zp [klast] to pA_end-1 int64_t p = GB_IMAX (Zp [klast], pA_start) ; Wlast [tid] = GB_IMAX (0, pA_end - p) ; #elif defined ( GB_TRIU_SELECTOR ) || \ defined ( GB_ROWLE_SELECTOR ) // keep pA_start to Zp [klast]-1 int64_t p = GB_IMIN (Zp [klast], pA_end) ; Wlast [tid] = GB_IMAX (0, p - pA_start) ; #elif defined ( GB_DIAG_SELECTOR ) // task that owns the diagonal entry does this work int64_t p = Zp [klast] ; Wlast [tid] = (pA_start <= p && p < pA_end) ? 1 : 0 ; #elif defined ( GB_OFFDIAG_SELECTOR ) || \ defined ( GB_ROWINDEX_SELECTOR ) // keep pA_start to Zp [klast]-1 int64_t p = GB_IMIN (Zp [klast], pA_end) ; Wlast [tid] = GB_IMAX (0, p - pA_start) ; // keep Zp [klast]+1 to pA_end-1 p = GB_IMAX (Zp [klast]+1, pA_start) ; Wlast [tid] += GB_IMAX (0, pA_end - p) ; #endif } } } #endif
Launcher.h
// SPDX-FileCopyrightText: 2020 CERN // SPDX-License-Identifier: Apache-2.0 /** * @file Launcher.h * @brief Backend-dependent abstraction for parallel function execution * @author Andrei Gheata (andrei.gheata@cern.ch) */ #ifndef COPCORE_LAUNCHER_H_ #define COPCORE_LAUNCHER_H_ #include <CopCore/Global.h> namespace copcore { #ifdef COPCORE_CUDA_COMPILER namespace kernel_launcher_impl { template <class Function, class... Args> __global__ void kernel_dispatch(int data_size, Function device_func_select, const Args... args) { // Initiate a grid-size loop to maximize reuse of threads and CPU compatibility, keeping adressing within warps // unit-stride for (auto id = blockIdx.x * blockDim.x + threadIdx.x; id < data_size; id += blockDim.x * gridDim.x) { device_func_select(id, args...); } } } // End namespace kernel_launcher_impl #endif template <BackendType backend> class LauncherBase { public: using LaunchGrid_t = launch_grid<backend>; using Stream_t = typename copcore::StreamType<backend>::value_type; protected: int fDeviceId{0}; ///< device id (GPU for CUDA, socket for CPU) // LaunchGrid_t fGrid{{0}, {0}}; ///< launch grid to be used if set by user Stream_t fStream{0}; ///< stream id for CUDA, not used for CPU) public: LauncherBase(Stream_t stream) : fStream{stream} {} // void SetDevice(int device) { fDeviceId = device; } int GetDevice() const { return fDeviceId; } void SetStream(Stream_t stream) { fStream = stream; } Stream_t GetStream() const { return fStream; } }; // end class LauncherBase /** @brief Launcher for generic backend */ template <BackendType backend> class Launcher : protected LauncherBase<backend> { public: using LaunchGrid_t = launch_grid<backend>; /** @brief Generic backend launch method. Implementation done in specializations */ template <class FunctionPtr, class... Args> int Run(FunctionPtr, int, LaunchGrid_t, const Args &...) const { // Not implemented backend launches will end-up here std::string backend_name(copcore::BackendName(backend)); COPCORE_EXCEPTION("Launcher::Launch: No implementation available for " + backend_name); return 1; } }; #ifdef COPCORE_CUDA_COMPILER /** @brief Specialization of Launcher for the CUDA backend */ template <> class Launcher<BackendType::CUDA> : public LauncherBase<BackendType::CUDA> { private: int fNumSMs; ///< number of streaming multi-processors public: Launcher(Stream_t stream = 0) : LauncherBase(stream) { cudaGetDevice(&fDeviceId); cudaDeviceGetAttribute(&fNumSMs, cudaDevAttrMultiProcessorCount, fDeviceId); } template <class DeviceFunctionPtr, class... Args> int Run(DeviceFunctionPtr func, int n_elements, LaunchGrid_t grid, const Args &... args) const { constexpr unsigned int warpsPerSM = 32; // we should target a reasonable occupancy constexpr unsigned int block_size = 256; // Compute the launch grid. if (!n_elements) return 0; // Adjust automatically the execution grid. Optimal occupancy: // nMaxThreads = fNumSMs * warpsPerSM * 32; grid_size = nmaxthreads / block_size // if n_elements < nMaxThreads we reduce the grid size to minimize null threads LaunchGrid_t exec_grid{grid}; if (grid[1].x == 0) { unsigned int grid_size = std::min(warpsPerSM * fNumSMs * 32 / block_size, (n_elements + block_size - 1) / block_size); exec_grid[0].x = grid_size; exec_grid[1].x = block_size; } //std::cout << "grid_size = " << exec_grid[0].x << " block_size = " << exec_grid[1].x << std::endl; // launch the kernel kernel_launcher_impl::kernel_dispatch<<<exec_grid[0], exec_grid[1], 0, fStream>>>(n_elements, func, args...); COPCORE_CUDA_CHECK(cudaGetLastError()); return 0; } void WaitStream() const { if (fStream) COPCORE_CUDA_CHECK(cudaStreamSynchronize(fStream)); else COPCORE_CUDA_CHECK(cudaDeviceSynchronize()); } static void WaitDevice() { COPCORE_CUDA_CHECK(cudaDeviceSynchronize()); } }; // End class Launcher<BackendType::CUDA> #endif /** @brief Specialization of Launcher for the CPU backend */ template <> class Launcher<BackendType::CPU> : public LauncherBase<BackendType::CPU> { public: Launcher(Stream_t stream = 0) : LauncherBase(stream) {} template <class HostFunctionPtr, class... Args> int Run(HostFunctionPtr func, int n_elements, LaunchGrid_t /*grid*/, const Args &... args) const { #pragma omp parallel for for (int i = 0; i < n_elements; ++i) { func(i, args...); } return 0; } void WaitStream() const {} static void WaitDevice() {} }; // End class Launcher<BackendType::CPU> } // End namespace copcore #endif // COPCORE_LAUNCHER_H_