source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
GB_unop__bnot_int64_int64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary 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_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__bnot_int64_int64
// op(A') function: GB_unop_tran__bnot_int64_int64
// C type: int64_t
// A type: int64_t
// cast: int64_t cij = aij
// unaryop: cij = ~(aij)
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_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) \
int64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int64_t z = aij ; \
Cx [pC] = ~(z) ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BNOT || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__bnot_int64_int64
(
int64_t *Cx, // Cx and Ax may be aliased
const int64_t *Ax,
const int8_t *GB_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)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (int64_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t aij = Ax [p] ;
int64_t z = aij ;
Cx [p] = ~(z) ;
}
#endif
}
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 ;
int64_t aij = Ax [p] ;
int64_t z = aij ;
Cx [p] = ~(z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__bnot_int64_int64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_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
|
jacobi2d-parallel-no.c | /**
* jacobi-2d-imper.c: This file is part of the PolyBench/C 3.2 test suite.
* Jacobi with array copying, no reduction.
*
* Contact: Louis-Noel Pouchet <pouchet@cse.ohio-state.edu>
* Web address: http://polybench.sourceforge.net
* License: /LICENSE.OSU.txt
*/
#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 20x1000. */
#include "jacobi-2d-imper.h"
/* Array initialization. */
static void init_array(int n,double A[500 + 0][500 + 0],double B[500 + 0][500 + 0])
{
//int i;
//int j;
{
int c2;
int c1;
if (n >= 1) {
#pragma omp parallel for private(c2)
for (c1 = 0; c1 <= n + -1; c1++) {
for (c2 = 0; c2 <= n + -1; c2++) {
A[c1][c2] = (((double )c1) * (c2 + 2) + 2) / n;
B[c1][c2] = (((double )c1) * (c2 + 3) + 3) / n;
}
}
}
}
}
/* 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 n,double A[500 + 0][500 + 0])
{
int i;
int j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
fprintf(stderr,"%0.2lf ",A[i][j]);
if ((i * n + 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_jacobi_2d_imper(int tsteps,int n,double A[500 + 0][500 + 0],double B[500 + 0][500 + 0])
{
//int t;
//int i;
//int j;
//#pragma scop
{
int c2;
int c1;
int c0;
for (c2 = 1; c2 <= 498; c2++) {
B[1][c2] = 0.2 * (A[1][c2] + A[1][c2 - 1] + A[1][1 + c2] + A[1 + 1][c2] + A[1 - 1][c2]);
}
for (c0 = 2; c0 <= 525; c0++) {
if (c0 <= 28) {
if ((2 * c0 + 1) % 3 == 0) {
for (c2 = ((2 * c0 + 1) * 3 < 0?-(-(2 * c0 + 1) / 3) : ((3 < 0?(-(2 * c0 + 1) + - 3 - 1) / - 3 : (2 * c0 + 1 + 3 - 1) / 3))); c2 <= (((2 * c0 + 1492) * 3 < 0?((3 < 0?-((-(2 * c0 + 1492) + 3 + 1) / 3) : -((-(2 * c0 + 1492) + 3 - 1) / 3))) : (2 * c0 + 1492) / 3)); c2++) {
B[1][(-2 * c0 + 3 * c2 + 2) / 3] = 0.2 * (A[1][(-2 * c0 + 3 * c2 + 2) / 3] + A[1][(-2 * c0 + 3 * c2 + 2) / 3 - 1] + A[1][1 + (-2 * c0 + 3 * c2 + 2) / 3] + A[1 + 1][(-2 * c0 + 3 * c2 + 2) / 3] + A[1 - 1][(-2 * c0 + 3 * c2 + 2) / 3]);
}
}
}
#pragma omp parallel for private(c2)
for (c1 = ((((2 * c0 + 2) * 3 < 0?-(-(2 * c0 + 2) / 3) : ((3 < 0?(-(2 * c0 + 2) + - 3 - 1) / - 3 : (2 * c0 + 2 + 3 - 1) / 3)))) > c0 + -9?(((2 * c0 + 2) * 3 < 0?-(-(2 * c0 + 2) / 3) : ((3 < 0?(-(2 * c0 + 2) + - 3 - 1) / - 3 : (2 * c0 + 2 + 3 - 1) / 3)))) : c0 + -9); c1 <= (((((2 * c0 + 498) * 3 < 0?((3 < 0?-((-(2 * c0 + 498) + 3 + 1) / 3) : -((-(2 * c0 + 498) + 3 - 1) / 3))) : (2 * c0 + 498) / 3)) < c0?(((2 * c0 + 498) * 3 < 0?((3 < 0?-((-(2 * c0 + 498) + 3 + 1) / 3) : -((-(2 * c0 + 498) + 3 - 1) / 3))) : (2 * c0 + 498) / 3)) : c0)); c1++) {
B[-2 * c0 + 3 * c1][1] = 0.2 * (A[-2 * c0 + 3 * c1][1] + A[-2 * c0 + 3 * c1][1 - 1] + A[-2 * c0 + 3 * c1][1 + 1] + A[1 + (-2 * c0 + 3 * c1)][1] + A[-2 * c0 + 3 * c1 - 1][1]);
for (c2 = 2 * c0 + -2 * c1 + 2; c2 <= 2 * c0 + -2 * c1 + 498; c2++) {
A[-2 * c0 + 3 * c1 + -1][-2 * c0 + 2 * c1 + c2 + -1] = B[-2 * c0 + 3 * c1 + -1][-2 * c0 + 2 * c1 + c2 + -1];
B[-2 * c0 + 3 * c1][-2 * c0 + 2 * c1 + c2] = 0.2 * (A[-2 * c0 + 3 * c1][-2 * c0 + 2 * c1 + c2] + A[-2 * c0 + 3 * c1][-2 * c0 + 2 * c1 + c2 - 1] + A[-2 * c0 + 3 * c1][1 + (-2 * c0 + 2 * c1 + c2)] + A[1 + (-2 * c0 + 3 * c1)][-2 * c0 + 2 * c1 + c2] + A[-2 * c0 + 3 * c1 - 1][-2 * c0 + 2 * c1 + c2]);
}
A[-2 * c0 + 3 * c1 + -1][498] = B[-2 * c0 + 3 * c1 + -1][498];
}
if (c0 >= 499) {
if ((2 * c0 + 1) % 3 == 0) {
for (c2 = ((2 * c0 + -992) * 3 < 0?-(-(2 * c0 + -992) / 3) : ((3 < 0?(-(2 * c0 + -992) + - 3 - 1) / - 3 : (2 * c0 + -992 + 3 - 1) / 3))); c2 <= (((2 * c0 + 499) * 3 < 0?((3 < 0?-((-(2 * c0 + 499) + 3 + 1) / 3) : -((-(2 * c0 + 499) + 3 - 1) / 3))) : (2 * c0 + 499) / 3)); c2++) {
A[498][(-2 * c0 + 3 * c2 + 995) / 3] = B[498][(-2 * c0 + 3 * c2 + 995) / 3];
}
}
}
}
for (c2 = 20; c2 <= 517; c2++) {
A[498][c2 + -19] = B[498][c2 + -19];
}
}
//#pragma endscop
}
int main(int argc,char **argv)
{
/* Retrieve problem size. */
int n = 500;
int tsteps = 10;
/* Variable declaration/allocation. */
double (*A)[500 + 0][500 + 0];
A = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
double (*B)[500 + 0][500 + 0];
B = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
/* Initialize array(s). */
init_array(n, *A, *B);
/* Start timer. */
polybench_timer_start();
;
/* Run kernel. */
kernel_jacobi_2d_imper(tsteps,n, *A, *B);
/* Stop and print timer. */
polybench_timer_stop();
;
polybench_timer_print();
;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
if (argc > 42 && !strcmp(argv[0],""))
print_array(n, *A);
/* Be clean. */
free(((void *)A));
;
free(((void *)B));
;
return 0;
}
|
biology_module_op.h | // -----------------------------------------------------------------------------
//
// Copyright (C) The BioDynaMo Project.
// All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#ifndef BIOLOGY_MODULE_OP_H_
#define BIOLOGY_MODULE_OP_H_
#include <cstddef> // std::size_t
#include <cstdint> // uint16_t
#include "debug.h"
namespace bdm {
using std::size_t;
struct BiologyModuleOp {
template <typename TContainer>
void operator()(TContainer* cells, uint16_t type_idx) const {
#pragma omp parallel
{
// Iterations are data independent, so threads don't need to
// wait for each other, which can improve performance when
// biology modules are not equal in workload
#pragma omp for nowait
for (size_t i = 0; i < cells->size(); i++) {
(*cells)[i].RunBiologyModules();
}
}
}
};
} // namespace bdm
#endif // BIOLOGY_MODULE_OP_H_
|
ParSHUM_solver.c | #define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libgen.h>
#include <math.h>
#include <limits.h>
#ifdef USE_PLASMA
#include <plasma.h>
#else
#include <mkl.h>
#endif
#include "ParSHUM_verbose.h"
#include "ParSHUM_enum.h"
#include "ParSHUM_matrix.h"
#include "ParSHUM_dense.h"
#include "ParSHUM_schur_matrix.h"
#include "ParSHUM_pivot_list.h"
#include "ParSHUM_paje.h"
#include "ParSHUM_auxiliary.h"
#include "ParSHUM_solver.h"
const char *usageStrign[] = {
"usage test: [--help] [--matrix matrix] [--RHS_file file] [--debug_mode] [--verbosity level] [--marko_tol tol] [--value_tol tol]",
" [--extra_space factor] [--extra_space_inbetween factor] [--nb_threads #threads] [--nb_candidates_per_block #blocks] ",
" [--output_dir dir] [--output_file file] [--nb_previous_pivots #pivtos] [--schur_density_tolerance tol]",
" [--min_pivot_per_steps #steps] [--prog_name name ] [--check_schur_symetry] [--check_schur_memory] [--check_pivots]",
" [--check_ParSHUM_with_plasma_perm] [--check_dense_with_ParSHUM_perm] [--print_each_step] [--check_GC]",
" [--group_run value_tol|marko_tol|schur_density|nb_candidates|min_pivots|nb_threads init inc nb_steps]",
" [--counters_size #double_counters] [--check_counters] [--check_schur_doubles] [--max_dense_schur size]",
" [--luby_algorithm] [--singeltons_relaxation tol] [--trace]",
NULL,
};
#ifdef USE_PLASMA
int is_plasma_init;
#endif
int ParSHUM_solver_run_group(ParSHUM_solver solver, ParSHUM_parm_type type,
void *init_val, int nb_steps, void *inc);
ParSHUM_solver
ParSHUM_solver_create()
{
ParSHUM_solver self = calloc(1, sizeof(*self));
self->exe_parms = calloc(1, sizeof(*self->exe_parms));
self->verbosity = 1;
self->size_counters = 100;
self->exe_parms->nb_threads = 1;
self->exe_parms->value_tol = 0.1;
self->exe_parms->singeltons_relaxation = 0.01;
self->exe_parms->marko_tol = 4;
self->exe_parms->extra_space = 1.0;
self->exe_parms->extra_space_inbetween = 1.0;
self->exe_parms->nb_candidates_per_block = 10;
self->exe_parms->nb_previous_pivots = 5;
self->exe_parms->min_pivot_per_steps = 5;
self->exe_parms->density_tolerance = 0.2;
self->exe_parms->max_dense_schur = 20000;
self->exe_parms->luby_algo = 1;
self->verbose = ParSHUM_verbose_create(self->exe_parms);
return self;
}
void
ParSHUM_solver_dealloc(ParSHUM_solver self)
{
ParSHUM_verbose_destroy(self->verbose);
free(self->exe_parms);
free(self);
}
int
check_ParSHUM_with_plasma_perm(int argc, char **argv)
{
ParSHUM_solver plasma;
ParSHUM_vector X, sol_plasma, sol_ParSHUM;
plasma = ParSHUM_solver_create();
ParSHUM_solver_parse_args(plasma, argc, argv, 1);
plasma->exe_parms->density_tolerance = 1.0;
plasma->exe_parms->min_pivot_per_steps = 5;
plasma->exe_parms->nb_previous_pivots = 5;
plasma->debug |= ParSHUM_CHECK_ParSHUM_W_PLASMA_PERM;
ParSHUM_solver_read_matrix(plasma);
ParSHUM_solver_init(plasma);
X = ParSHUM_vector_create(plasma->A->n);
sol_plasma = ParSHUM_vector_create(plasma->A->n);
sol_ParSHUM = ParSHUM_vector_create(plasma->A->n);
ParSHUM_vector_read_file(X, plasma->exe_parms->RHS_file);
ParSHUM_vector_copy(X, sol_plasma);
ParSHUM_solver_factorize(plasma);
ParSHUM_solver_solve(plasma, sol_plasma);
ParSHUM_solver_compute_norms(plasma, X, sol_plasma);
ParSHUM_solver_finalize(plasma);
/* apply plasma row permutation to A */
int *plasma_perms = ParSHUM_dense_get_row_perms(plasma->S_dense, plasma->row_perm);
ParSHUM_matrix debug_matrix = ParSHUM_matrix_permute(plasma->A, plasma->col_perm, plasma_perms);
ParSHUM_solver debug_solver = ParSHUM_solver_create();
debug_solver->A = debug_matrix;
debug_solver->debug |= ParSHUM_CHECK_ParSHUM_W_PLASMA_PERM;
debug_solver->exe_parms->density_tolerance = 1.0;
debug_solver->exe_parms->min_pivot_per_steps = 5;
debug_solver->exe_parms->nb_previous_pivots = 5;
ParSHUM_solver_init(debug_solver);
ParSHUM_vector_permute(X, plasma_perms, X->n);
ParSHUM_vector_copy(X, sol_ParSHUM);
ParSHUM_solver_factorize(debug_solver);
ParSHUM_solver_solve(debug_solver, sol_ParSHUM);
ParSHUM_solver_compute_norms(debug_solver, X, sol_ParSHUM);
ParSHUM_solver_finalize(debug_solver);
free(plasma_perms);
ParSHUM_vector_destroy(X);
ParSHUM_vector_destroy(sol_plasma);
ParSHUM_vector_destroy(sol_ParSHUM);
ParSHUM_solver_destroy(debug_solver);
ParSHUM_solver_destroy(plasma);
return 0;
}
int
check_dense_with_ParSHUM_perm(int argc, char **argv)
{
ParSHUM_solver self;
ParSHUM_vector X, sol_ParSHUM, sol_dense;
self = ParSHUM_solver_create();
ParSHUM_solver_parse_args(self, argc, argv, 1);
self->exe_parms->density_tolerance = 1.0;
self->exe_parms->min_pivot_per_steps = 5;
self->exe_parms->nb_previous_pivots = 5;
ParSHUM_solver_read_matrix(self);
ParSHUM_solver_init(self);
X = ParSHUM_vector_create(self->A->n);
sol_ParSHUM = ParSHUM_vector_create(self->A->n);
sol_dense = ParSHUM_vector_create(self->A->n);
ParSHUM_vector_read_file(X, self->exe_parms->RHS_file);
ParSHUM_vector_copy(X, sol_ParSHUM);
ParSHUM_vector_copy(X, sol_dense);
ParSHUM_solver_factorize(self);
ParSHUM_solver_solve(self, sol_ParSHUM);
ParSHUM_solver_compute_norms(self, X, sol_ParSHUM);
ParSHUM_solver_finalize(self);
ParSHUM_solver dense_solver = ParSHUM_solver_create();
ParSHUM_solver_parse_args(dense_solver, argc, argv, 1);
dense_solver->A = self->A;
dense_solver->debug |= ParSHUM_CHECK_DENSE_W_ParSHUM_PERM;
dense_solver->row_perm = self->row_perm;
dense_solver->col_perm = self->col_perm;
dense_solver->invr_row_perm = self->invr_row_perm;
dense_solver->invr_col_perm = self->invr_col_perm;
dense_solver->verbose->parms->prog_name = "Dense solver";
ParSHUM_solver_init(dense_solver);
ParSHUM_solver_factorize(dense_solver);
ParSHUM_solver_solve(dense_solver, sol_dense);
ParSHUM_solver_compute_norms(dense_solver, X, sol_dense);
ParSHUM_solver_finalize(dense_solver);
ParSHUM_vector_destroy(X);
ParSHUM_vector_destroy(sol_ParSHUM);
ParSHUM_vector_destroy(sol_dense);
ParSHUM_solver_destroy(dense_solver);
ParSHUM_solver_destroy(self);
return 0;
}
void
ParSHUM_solver_parse_args(ParSHUM_solver self, int argc, char **argv, int exit_on_notFound)
{
int i, run_args_start = 0;
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--verbosity")) {
self->verbose->parms->verbosity = atoi(argv[++i]);
self->verbosity = atoi(argv[i]);
continue;
} else if (!strcmp(argv[i], "--matrix")) {
self->exe_parms->matrix_file = argv[++i];
continue;
} else if (!strcmp(argv[i], "--RHS_file")) {
self->exe_parms->RHS_file = argv[++i];
continue;
} else if (!strcmp(argv[i], "--value_tol")) {
double tmp = atof(argv[++i]);
if ( tmp > 1.0 || tmp < 0.0)
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "value tolerance should be between 0 and 1");
self->exe_parms->value_tol = tmp;
continue;
} else if (!strcmp(argv[i], "--marko_tol")) {
double tmp = atof(argv[++i]);
if ( tmp < 1.0 )
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "marko tolerance should be larger then 1");
self->exe_parms->marko_tol = tmp;
continue;
} else if (!strcmp(argv[i], "--nb_threads")) {
int tmp = atoi(argv[++i]);
self->exe_parms->nb_threads = tmp;
continue;
} else if (!strcmp(argv[i], "--extra_space")) {
double tmp = atof(argv[++i]);
self->exe_parms->extra_space = tmp;
continue;
} else if (!strcmp(argv[i], "--extra_space_inbetween")) {
double tmp = atof(argv[++i]);
self->exe_parms->extra_space_inbetween = tmp;
continue;
} else if (!strcmp(argv[i], "--nb_candidates_per_block")) {
int tmp = atoi(argv[++i]);
if (tmp < 1)
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "nb_candidates_per_blocks should be at least 1");
self->exe_parms->nb_candidates_per_block = tmp;
continue;
} else if (!strcmp(argv[i], "--prog_name")) {
self->verbose->parms->prog_name = argv[++i];
continue;
} else if (!strcmp(argv[i], "--output_dir")) {
self->verbose->parms->output_dir = argv[++i];
self->verbose->parms->user_out_dir = 1;
continue;
} else if (!strcmp(argv[i], "--output_file")) {
FILE *file = fopen(argv[++i], "w+");
if ( file ) {
self->verbose->parms->out_file = file;
self->verbose->parms->user_out_file = 1;
} else {
ParSHUM_warning(__FUNCTION__, __FILE__, __LINE__,"unable to open output file, the program will write on stdout instead");
file = stdout;
}
continue;
} else if (!strcmp(argv[i], "--nb_previous_pivots")) {
int tmp = atoi(argv[++i]);
if (tmp < 1)
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "nb_previous_pivots should be at least 1");
self->exe_parms->nb_previous_pivots = tmp;
continue;
} else if (!strcmp(argv[i], "--schur_density_tolerance")) {
double tmp = atof(argv[++i]);
if ( tmp > 1.0 )
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "schur density tolerance can not be larger then 1");
if ( tmp < 0.0 )
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "schur density tolerance can not be smaller then 0");
self->exe_parms->density_tolerance = tmp;
continue;
} else if (!strcmp(argv[i], "--min_pivot_per_steps")) {
int tmp = atoi(argv[++i]);
if ( tmp < self->exe_parms->nb_previous_pivots )
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "min_pivot_per_steps should be at least nb_previous_pivots");
self->exe_parms->min_pivot_per_steps = tmp;
continue;
} else if (!strcmp(argv[i], "--debug_mode")) {
ParSHUM_warning(__FUNCTION__, __FILE__, __LINE__,"debug mode is not implemented");
continue;
} else if (!strcmp(argv[i], "--check_pivots")) {
self->debug |= ParSHUM_CHECK_PIVOTS;
continue;
} else if (!strcmp(argv[i], "--check_schur_memory")) {
self->debug |= ParSHUM_CHECK_SCHUR_MEMORY;
continue;
} else if (!strcmp(argv[i], "--check_schur_symetry")) {
self->debug |= ParSHUM_CHECK_SCHUR_SYMETRY;
continue;
} else if (!strcmp(argv[i], "--check_counters")) {
self->debug |= ParSHUM_CHECK_COUNTERS;
continue;
} else if (!strcmp(argv[i], "--print_each_step")) {
self->debug |= ParSHUM_DEBUG_VERBOSE_EACH_STEP;
continue;
} else if (!strcmp(argv[i], "--verbose_gossip_girl")) {
self->debug |= ParSHUM_DEBUG_GOSSIP_GIRL;
continue;
} else if (!strcmp(argv[i], "--check_schur_doubles")) {
self->debug |= ParSHUM_CHECK_SCHUR_DOUBLES;
continue;
} else if (!strcmp(argv[i], "--check_ParSHUM_with_plasma_perm")) {
ParSHUM_solver_dealloc(self);
exit(check_ParSHUM_with_plasma_perm(argc, argv));
} else if (!strcmp(argv[i], "--check_dense_with_ParSHUM_perm")) {
ParSHUM_solver_dealloc(self);
exit(check_dense_with_ParSHUM_perm(argc, argv));
continue;
} else if (!strcmp(argv[i], "--group_run")) {
run_args_start = ++i;
i += 3;
continue;
} else if (!strcmp(argv[i], "--counters_size")) {
self->size_counters = atoi(argv[++i]);
continue;
} else if (!strcmp(argv[i], "--max_dense_schur")) {
int tmp = atoi(argv[++i]);
if (tmp < 1)
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "max_dense_schur should be at least 1");
self->exe_parms->max_dense_schur = tmp;
continue;
} else if (!strcmp(argv[i], "--singeltons_relaxation")) {
self->exe_parms->singeltons_relaxation = atof(argv[++i]);
} else if (!strcmp(argv[i], "--luby_algorithm")) {
self->exe_parms->luby_algo = 1;
} else if (!strcmp(argv[i], "--trace")) {
self->exe_parms->trace = 1;
} else if (!strcmp(argv[i], "--help")) {
int j = 0;
while( usageStrign[j] != NULL)
printf("%s\n", usageStrign[j++]);
exit(0);
} else {
if (exit_on_notFound) {
char mess[2048];
snprintf(mess, 2048, "unrecognized option \"%s\" ", argv[i]);
int j = 0;
while( usageStrign[j] != NULL)
printf("%s\n", usageStrign[j++]);
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, mess);
}
}
}
if (run_args_start) {
ParSHUM_parm_type type;
if ( !strcmp(argv[run_args_start], "value_tol") ) {
type = ParSHUM_value_tol;
double init = atof(argv[++run_args_start]), inc = atof(argv[++run_args_start]);
int nb_steps = atoi(argv[++run_args_start]);
exit(ParSHUM_solver_run_group(self, type, (void *) &init, nb_steps, (void *) &inc));
} else if ( !strcmp(argv[run_args_start], "marko_tol") ) {
type = ParSHUM_marko_tol;
double init = atof(argv[++run_args_start]), inc = atof(argv[++run_args_start]);
int nb_steps = atoi(argv[++run_args_start]);
exit(ParSHUM_solver_run_group(self, type, (void *) &init, nb_steps, (void *) &inc));
} else if ( !strcmp(argv[run_args_start], "schur_density") ) {
type = ParSHUM_schur_density;
double init = atof(argv[++run_args_start]), inc = atof(argv[++run_args_start]);
int nb_steps = atoi(argv[++run_args_start]);
exit(ParSHUM_solver_run_group(self, type, (void *) &init, nb_steps, (void *) &inc));
} else if ( !strcmp(argv[run_args_start], "nb_candidates") ) {
type = ParSHUM_nb_candidates;
int init = atoi(argv[++run_args_start]), inc = atoi(argv[++run_args_start]);
int nb_steps = atoi(argv[++run_args_start]);
exit(ParSHUM_solver_run_group(self, type, (void *) &init, nb_steps, (void *) &inc));
} else if ( !strcmp(argv[run_args_start], "min_pivots") ) {
type = ParSHUM_min_pivots;
int init = atoi(argv[++run_args_start]), inc = atoi(argv[++run_args_start]);
int nb_steps = atoi(argv[++run_args_start]);
exit(ParSHUM_solver_run_group(self, type, (void *) &init, nb_steps, (void *) &inc));
} else if ( !strcmp(argv[run_args_start], "nb_threads") ) {
type = ParSHUM_nb_threads;
int init = atoi(argv[++run_args_start]), inc = atoi(argv[++run_args_start]);
int nb_steps = atoi(argv[++run_args_start]);
exit(ParSHUM_solver_run_group(self, type, (void *) &init, nb_steps, (void *) &inc));
} else {
int j = 0;
while( usageStrign[j] != NULL)
printf("%s\n", usageStrign[j++]);
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "for the group run, unrecognized type of argument is given" );
}
}
}
void
update_exe_parms(ParSHUM_exe_parms parms, ParSHUM_parm_type type,
void *init_val, int step, void *val, void *inc)
{
double *Dinit, *Dinc, *Dval;
int *Iinit, *Iinc, *Ival;
switch (type) {
case (ParSHUM_value_tol) :
Dinit = (double *) init_val; Dinc = (double *) inc; Dval = (double *) val;
*Dval = *Dinit * pow(*Dinc, (double) step);
parms->value_tol = *Dval;
break;
case (ParSHUM_marko_tol) :
Dinit = (double *) init_val; Dinc = (double *) inc; Dval = (double *) val;
*Dval = *Dinit + *Dinc * step;
parms->marko_tol = *Dval;
break;
case (ParSHUM_schur_density) :
Dinit = (double *) init_val; Dinc = (double *) inc; Dval = (double *) val;
*Dval = *Dinit + *Dinc * step;
parms->density_tolerance = *Dval;
break;
case (ParSHUM_nb_candidates) :
Iinit = (int *) init_val, Iinc = (int *) inc; Ival = (int *) val;
*Ival = *Iinit + *Iinc * step;
parms->nb_candidates_per_block = *Ival;
break;
case (ParSHUM_min_pivots) :
Iinit = (int *) init_val, Iinc = (int *) inc; Ival = (int *) val;
*Ival = *Iinit + *Iinc * step;
parms->min_pivot_per_steps = *Ival;
break;
case (ParSHUM_nb_threads) :
Iinit = (int *) init_val, Iinc = (int *) inc; Ival = (int *) val;
*Ival = *Iinit + *Iinc * step;
parms->nb_threads = *Ival;
break;
default :
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "unrecognized type of exe_parms");
}
}
char *
get_outfile_prefix(ParSHUM_exe_parms exe_parms, ParSHUM_parm_type type)
{
char *self = calloc(PATH_LENGTH, sizeof(*self));
size_t length = 0;
*self = '\0';
if (exe_parms->matrix_file)
snprintf(self, 2058, "%s", basename(exe_parms->matrix_file));
length = strnlen(self, PATH_LENGTH - length);
if (type == ParSHUM_value_tol)
snprintf(self + length, PATH_LENGTH - length,"_MULTIValTol");
else
snprintf(self + length, PATH_LENGTH - length,"_%fValTol", exe_parms->value_tol);
length = strnlen(self, PATH_LENGTH - length);
if (type == ParSHUM_marko_tol)
snprintf(self + length, PATH_LENGTH - length,"_MULTIMarkoTol");
else
snprintf(self + length, PATH_LENGTH - length,"_%fMarkoTol", exe_parms->marko_tol);
length = strnlen(self, PATH_LENGTH - length);
if (type == ParSHUM_nb_threads)
snprintf(self + length, PATH_LENGTH - length,"_MULTIthreads");
else
snprintf(self + length, PATH_LENGTH - length,"_%dthreads", exe_parms->nb_threads);
length = strnlen(self, PATH_LENGTH - length);
if (type == ParSHUM_nb_candidates)
snprintf(self + length, PATH_LENGTH - length,"_MULTIcandidates");
else
snprintf(self + length, PATH_LENGTH - length,"_%dcandidates", exe_parms->nb_candidates_per_block);
length = strnlen(self, PATH_LENGTH - length);
if (type == ParSHUM_schur_density)
snprintf(self + length, PATH_LENGTH - length,"_MULTIdensityTol");
else
snprintf(self + length, PATH_LENGTH - length,"_%fdensityTol", exe_parms->density_tolerance);
length = strnlen(self, PATH_LENGTH - length);
if (type == ParSHUM_min_pivots)
snprintf(self + length, PATH_LENGTH - length,"_MULTIminPivots");
else
snprintf(self + length, PATH_LENGTH - length,"_%dminPivots", exe_parms->min_pivot_per_steps);
length = strnlen(self, PATH_LENGTH - length);
self[length] = '\0';
return self;
}
int
ParSHUM_solver_run_group(ParSHUM_solver solver, ParSHUM_parm_type type,
void *init_val, int nb_steps, void *inc)
{
FILE *file;
int i;
ParSHUM_matrix A = ParSHUM_matrix_create();
ParSHUM_exe_parms exe_parms = solver->exe_parms;
char *file_ext = strrchr(exe_parms->matrix_file, '.');
ParSHUM_vector X, rhs;
char *output_runs_file = get_outfile_prefix(exe_parms, type);
char filename[PATH_LENGTH];
double current_val;
ParSHUM_verbose_create_dirs(solver->verbose->parms->output_dir);
snprintf(filename, PATH_LENGTH, "%s/data/MULTI_%s_raw.dat", solver->verbose->parms->output_dir, output_runs_file);
file = fopen(filename, "w+");
if (!strcmp(file_ext, ".mtl"))
ParSHUM_read_mtl_file(A, exe_parms->matrix_file);
#ifdef HAVE_SPRAL
else if (!strcmp(file_ext, ".rb"))
ParSHUM_read_rutherford_boeing(A, exe_parms->matrix_file);
#endif
else
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__,"unrecognized file type format");
solver->A = A;
X = ParSHUM_vector_create(A->n);
rhs = ParSHUM_vector_create(A->n);
ParSHUM_vector_read_file(X, solver->exe_parms->RHS_file);
ParSHUM_verbose_print_parms_raw(exe_parms, type, file);
for( i = 0; i < nb_steps; i++)
{
ParSHUM_solver run = ParSHUM_solver_create();
ParSHUM_matrix matrix = ParSHUM_matrix_create();
ParSHUM_exe_parms run_exe_parms = malloc(sizeof(*run_exe_parms));
*run_exe_parms = *exe_parms;
ParSHUM_matrix_copy(A, matrix);
free(run->exe_parms);
run->A = matrix;
run->exe_parms = run->verbose->exe_parms = run_exe_parms;
free(run->verbose->parms->output_dir);
run->verbose->parms->output_dir = solver->verbose->parms->output_dir;
run->verbose->parms->user_out_dir = 1;
update_exe_parms(run->exe_parms, type, init_val, i, (void *) ¤t_val, inc);
ParSHUM_solver_init(run);
ParSHUM_vector_copy(X, rhs);
ParSHUM_solver_factorize(run);
ParSHUM_solver_solve(run, rhs);
ParSHUM_solver_compute_norms(run, rhs, X);
ParSHUM_solver_finalize(run);
ParSHUM_verbose_print_group_run(run->verbose, type, (void *) ¤t_val, i, file);
ParSHUM_solver_destroy(run);
}
fclose(file);
ParSHUM_vector_destroy(X);
ParSHUM_vector_destroy(rhs);
ParSHUM_matrix_destroy(A);
free(output_runs_file);
ParSHUM_solver_dealloc(solver);
return 0;
}
/* TODO: FOR NOW WE ASUME THAT N == M */
void
ParSHUM_solver_alloc_counters(ParSHUM_solver solver, int **col_count, int **row_count)
{
int i, total;
ParSHUM_counters counter = NULL;
pthread_mutex_lock(&solver->counters_lock);
for( i = 0; i < solver->nb_counters; i++)
if ( solver->counters[i]->nb_used_counters < solver->size_counters) {
counter = solver->counters[i];
break;
}
if (!counter) {
solver->nb_counters++;
int new = solver->nb_counters - 1;
solver->counters = realloc(solver->counters, solver->nb_counters * sizeof(*solver->counters));
solver->counters[new] = calloc(1, sizeof(**solver->counters));
solver->counters[new]->array = calloc((size_t) solver->size_counters * 2 * solver->A->n, sizeof(*solver->counters[new]->array));
solver->counters[new]->used_counters = calloc((size_t) solver->size_counters, sizeof(*solver->counters[new]->used_counters));
counter = solver->counters[new];
}
total = solver->size_counters;
for(i = 0; i < total; i++)
if(!counter->used_counters[i]) {
*col_count = &counter->array[i * solver->A->n * 2 ];
*row_count = &counter->array[i * solver->A->n * 2 + solver->A->n];
counter->nb_used_counters++;
counter->used_counters[i] = 1;
pthread_mutex_unlock(&solver->counters_lock);
return;
}
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__,"this should not happened!");
}
void
ParSHUM_solver_dealloc_counters(ParSHUM_solver solver, int *col_count, int *row_count)
{
pthread_mutex_lock(&solver->counters_lock);
int i;
ParSHUM_counters counter = NULL;
long diff;
for( i = 0; i < solver->nb_counters; i++) {
diff = col_count - solver->counters[i]->array;
if ( diff >= 0 && diff < solver->A->n * 2 * solver->size_counters){
counter = solver->counters[i];
break;
}
}
if (!counter)
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__,"puffff");
counter->used_counters[ diff / ( solver->A->n * 2) ] = 0;
counter->nb_used_counters--;
pthread_mutex_unlock(&solver->counters_lock);
}
void
ParSHUM_solver_alloc_internal(ParSHUM_solver self)
{
double total_extra_space = 1 + self->exe_parms->extra_space_inbetween + self->exe_parms->extra_space;
int n = self->A->n, m = self->A->m, i;
/* TOCORRECT */
/* int needed_pivots = n < m ? n : m; */
int needed_pivots = n - self->BB_cols - 1;
int larger_size = n > m ? n : m;
/* needed_pivots -= self->BB_cols; */
self->S = ParSHUM_schur_matrix_create();
self->D = ParSHUM_matrix_create();
if (self->debug & (ParSHUM_DEBUG_VERBOSE_EACH_STEP | ParSHUM_DEBUG_GOSSIP_GIRL))
ParSHUM_matrix_print(self->A, "A on input");
ParSHUM_schur_matrix_allocate(self->S, n, m, self->A->nnz,
self->debug, self->verbose, self->exe_parms->nb_threads,
self->exe_parms->extra_space, self->exe_parms->extra_space_inbetween);
ParSHUM_schur_matrix_copy(self->A, self->S, self->exe_parms->value_tol);
if (self->debug & (ParSHUM_DEBUG_VERBOSE_EACH_STEP | ParSHUM_DEBUG_GOSSIP_GIRL))
ParSHUM_schur_matrix_print(self->S, "S on input");
ParSHUM_matrix_allocate(self->D, needed_pivots, 0, 0, 1.0, ParSHUM_Diag_matrix);
self->L = ParSHUM_L_matrix_create(needed_pivots);
self->U = ParSHUM_U_matrix_create(self->A, total_extra_space);
self->row_perm = malloc((size_t) m * sizeof(*self->row_perm));
self->invr_row_perm = malloc((size_t) m * sizeof(*self->invr_row_perm));
self->col_perm = malloc((size_t) n * sizeof(*self->col_perm));
self->invr_col_perm = malloc((size_t) n * sizeof(*self->invr_col_perm));
int_array_memset(self->row_perm, ParSHUM_UNUSED_PIVOT, m);
int_array_memset(self->invr_row_perm, ParSHUM_UNUSED_PIVOT, m);
int_array_memset(self->col_perm, ParSHUM_UNUSED_PIVOT, n);
int_array_memset(self->invr_col_perm, ParSHUM_UNUSED_PIVOT, n);
self->previous_pivots = malloc((size_t) self->exe_parms->nb_previous_pivots * sizeof(*self->previous_pivots));
int_array_memset(self->previous_pivots, INT_MAX / self->exe_parms->nb_previous_pivots, self->exe_parms->nb_previous_pivots);
/* TODO: check if this is correct for the TP algo */
self->candidates = calloc(1, sizeof(*self->candidates));
self->candidates->row = malloc((size_t) n * sizeof(*self->candidates->row));
self->candidates->marko = malloc((size_t) n * sizeof(*self->candidates->marko));
self->candidates->best_marko = malloc((size_t) self->exe_parms->nb_threads * sizeof(*self->candidates->best_marko));
self->counters = calloc(1, sizeof(*self->counters));
*self->counters = calloc(1, sizeof(**self->counters));
self->random_col = create_randomize(n);
/* TODO: check if this is correct for the TP algo */
(*self->counters)->array = calloc((size_t) self->size_counters * 2 * n, sizeof(*self->counters[0]->array));
(*self->counters)->used_counters = calloc((size_t) self->size_counters, sizeof(*self->counters[0]->used_counters));
self->nb_counters = 1;
self->allocated_U_struct = n / 100;
self->allocated_U_struct = self->allocated_U_struct ? self->allocated_U_struct : 1;
self->U_struct = calloc((size_t) self->allocated_U_struct, sizeof(*self->U_struct));
self->allocated_L_struct = m / 100;
self->allocated_L_struct = self->allocated_L_struct ? self->allocated_L_struct : 1;
self->L_struct = calloc((size_t) self->allocated_L_struct, sizeof(*self->L_struct));
self->Luby = ParSHUM_Luby_create(n - self->BB_cols);
self->cols = malloc((size_t) (n - self->BB_cols) * sizeof(*self->cols));
for( i = 0; i < n - self->BB_cols; i++)
self->cols[i] = i;
self->rows = malloc((size_t) m * sizeof(*self->rows));
for( i = 0; i < m; i++)
self->rows[i] = i;
self->distributions = malloc((size_t) (self->exe_parms->nb_threads + 1) * sizeof(*self->distributions));
/* srand(time(NULL)); */
self->seeds = malloc((size_t) self->exe_parms->nb_threads * sizeof(*self->seeds));
for(i = 0; i < self->exe_parms->nb_threads; i++)
/* TODO: Put an argument "determenistic" and call srand before if activated */
self->seeds[i] = rand();
self->workspace = malloc((size_t) self->exe_parms->nb_threads * sizeof(*self->workspace));
for(i = 0; i < self->exe_parms->nb_threads; i++)
self->workspace[i] = malloc((size_t) larger_size * (sizeof(int) + sizeof(double)));
self->logical_cols = calloc((size_t) n, sizeof(*self->logical_cols));
self->logical_rows = calloc((size_t) m, sizeof(*self->logical_rows));
pthread_mutex_init(&self->counters_lock, NULL);
}
void
ParSHUM_solver_init(ParSHUM_solver self)
{
self->verbose->n = self->A->n;
self->verbose->m = self->A->m;
self->verbose->nnz_input = self->verbose->nnz_final = self->A->nnz;
self->verbose->Luby = self->exe_parms->luby_algo;
self->verbose->parms->outfiles_prefix = get_outfile_prefix(self->exe_parms, ParSHUM_parm_none);
if (self->exe_parms->trace)
self->verbose->paje = ParSHUM_paje_create(self->exe_parms->nb_threads);
#ifdef USE_PLASMA
if (!is_plasma_init) {
plasma_init(1);
is_plasma_init = 1;
}
#endif
if ( !(self->debug & ParSHUM_CHECK_DENSE_W_ParSHUM_PERM) )
ParSHUM_solver_alloc_internal(self);
if (self->verbose->parms->verbosity > 1)
ParSHUM_verbose_create_dirs(self->verbose->parms->output_dir);
#pragma omp parallel num_threads(self->exe_parms->nb_threads) default(none) //proc_bind(spread)
{
int me = omp_get_thread_num();
me++;
}
}
void
ParSHUM_solver_read_matrix(ParSHUM_solver self)
{
char *file_ext = strrchr(self->exe_parms->matrix_file, '.');
self->A = ParSHUM_matrix_create();
if (!strcmp(file_ext, ".mtl"))
ParSHUM_read_mtl_file(self->A, self->exe_parms->matrix_file);
#ifdef HAVE_SPRAL
else if (!strcmp(file_ext, ".rb"))
ParSHUM_read_rutherford_boeing(self->A, self->exe_parms->matrix_file);
#endif
else
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__,"unsupported matrix file");
}
void
ParSHUM_solver_get_pivots(ParSHUM_solver self, ParSHUM_pivot_set set)
{
ParSHUM_pivot_cell cells = set->cells;
int n = self->A->n, i, k, nnz ;
int new_pivots = 0, old_pivots = self->found_pivots + self->nb_col_singletons + self->nb_row_singletons;
int *row_perms = self->row_perm;
int *col_perms = self->col_perm;
int *invr_row_perms = self->invr_row_perm;
int *invr_col_perms = self->invr_col_perm;
while (cells)
{
int current_pivot = new_pivots + old_pivots;
row_perms[current_pivot] = cells->row;
col_perms[current_pivot] = cells->col;
invr_row_perms[cells->row] = current_pivot;
invr_col_perms[cells->col] = current_pivot;
new_pivots++;
cells = cells->next;
}
for ( i = 0, k=0, nnz = 0; i < n; i++) {
if (set->cols_count[i] < set->base)
continue;
if (self->invr_col_perm[i] != ParSHUM_UNUSED_PIVOT) {
if (set->cols_count[i] > set->base) {
ParSHUM_warning(__FUNCTION__, __FILE__, __LINE__, "col is supposed to be a pivot but is larger then base ");
} else {
continue;
}
}
self->U_struct[k].col = i;
self->U_struct[k].nb_elem = set->cols_count[i] - set->base + 1;
nnz += self->U_struct[k].nb_elem;
if( ++k >= self->allocated_U_struct)
{
self->allocated_U_struct *= 2;
self->U_struct = realloc(self->U_struct, (size_t) self->allocated_U_struct * sizeof(*self->U_struct));
}
}
self->n_U_structs = k;
self->nnz_U_structs = nnz;
for ( i = 0, k=0, nnz = 0; i < n; i++) {
if (set->rows_count[i] < set->base)
continue;
if (self->invr_row_perm[i] != ParSHUM_UNUSED_PIVOT) {
if (set->rows_count[i] > set->base) {
ParSHUM_warning(__FUNCTION__, __FILE__, __LINE__, "row is supposed to be a pivot but is larger then base ");
} else {
continue;
}
}
self->L_struct[k].col = i;
self->L_struct[k].nb_elem = set->rows_count[i] - set->base + 1;
nnz += self->L_struct[k].nb_elem;
if( ++k >= self->allocated_L_struct)
{
self->allocated_L_struct *= 2;
self->L_struct = realloc(self->L_struct, (size_t) self->allocated_L_struct * sizeof(*self->L_struct));
}
}
self->n_L_structs = k;
self->nnz_L_structs = nnz;
self->rows_count = set->rows_count;
self->cols_count = set->cols_count;
self->found_pivots += new_pivots;
ParSHUM_verbose_update_pivots(self->verbose, new_pivots);
}
void
ParSHUM_check_logical_sum(ParSHUM_solver self, int new_Luby_pivots)
{
ParSHUM_schur_matrix S = self->S ;
int n = S->n, m = S->m, i, pivot;
int *logical_rows = calloc(m, sizeof(*logical_rows));
int *logical_cols = calloc(n, sizeof(*logical_rows));
int *invr_row_perms = self->invr_row_perm;
int *invr_col_perms = self->invr_col_perm;
int *row_perms = self->row_perm;
int *col_perms = self->col_perm;
int start_pivots = self->done_pivots;
int end_pivots = self->done_pivots + self->nb_row_singletons + self->nb_col_singletons + new_Luby_pivots;
int nb_logical_rows = 0;
int nb_logical_cols = 0;
for( pivot = start_pivots; pivot < end_pivots; pivot++) {
int col_pivot = col_perms[pivot];
CSC_struct *CSC = &S->CSC[col_pivot];
int *rows = CSC->row;
int nb_elem = CSC->nb_elem;
for ( i = 0; i < nb_elem; i++)
if (invr_row_perms[rows[i]] == ParSHUM_UNUSED_PIVOT)
logical_rows[rows[i]] = 1;
int row_pivot = row_perms[pivot];
CSR_struct *CSR = &S->CSR[row_pivot];
int *cols = CSR->col;
nb_elem = CSR->nb_elem;
for(i = 0; i < nb_elem; i++)
if (invr_col_perms[cols[i]] == ParSHUM_UNUSED_PIVOT)
logical_cols[cols[i]] = 1;
}
for ( i = 0; i < n; i++)
if (logical_cols[i])
nb_logical_cols++;
for ( i = 0; i < m; i++)
if (logical_rows[i])
nb_logical_rows++;
if (nb_logical_cols != self->n_U_structs)
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "n_U_struct not correct");
if (nb_logical_rows != self->n_L_structs)
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "n_L_struct not correct");
free(logical_rows); free(logical_cols);
}
void
ParSHUM_solver_get_Luby_pivots(ParSHUM_solver self, ParSHUM_Luby Luby, int new_Luby_pivots)
{
ParSHUM_schur_matrix S = self->S;
ParSHUM_verbose verbose = self->verbose;
int n = S->n, nb_cols = S->n - self->done_pivots - self->BB_cols, nb_rows = S->m - self->done_pivots;
int done_pivots = self->done_pivots;
int new_pivots = new_Luby_pivots + self->nb_col_singletons + self->nb_row_singletons;
int all_pivots = new_pivots + done_pivots;
int i, base = self->step + 1;
int nb_threads = self->exe_parms->nb_threads;
int nb_BB_cols = self->BB_cols;
int distribution_perms[nb_threads+1], distribution_n[nb_threads+1], distribution_m[nb_threads+1];
int row_sizes[nb_threads], col_sizes[nb_threads];
int *logical_cols = self->logical_cols;
int *logical_rows = self->logical_rows;
int *row_perms = self->row_perm;
int *col_perms = self->col_perm;
int *invr_row_perms = self->invr_row_perm;
int *invr_col_perms = self->invr_col_perm;
int *cols = self->cols;
int *rows = self->rows;
self->previous_step_pivots = new_pivots;
self->n_U_structs = 0;
self->nnz_U_structs = 0;
self->n_L_structs = 0;
self->nnz_L_structs = 0;
*distribution_perms = done_pivots + self->nb_col_singletons + self->nb_row_singletons;
for(i = 1; i < nb_threads; i++)
distribution_perms[i] = *distribution_perms + (new_Luby_pivots / nb_threads) * i;
distribution_perms[nb_threads] = all_pivots;
*distribution_n = 0;
for(i = 1; i < nb_threads; i++)
distribution_n[i] = (nb_cols / nb_threads) * i;
distribution_n[nb_threads] = nb_cols;
*distribution_m = 0;
for(i = 1; i < nb_threads; i++)
distribution_m[i] = (nb_rows / nb_threads) * i;
distribution_m[nb_threads] = nb_rows;
#pragma omp parallel num_threads(nb_threads) shared(distribution_perms, distribution_n, distribution_m, nb_cols, col_sizes, row_sizes, n, nb_BB_cols, verbose) firstprivate(self, S, base, invr_col_perms, invr_row_perms, col_perms, row_perms, logical_cols, logical_rows, nb_threads, cols, rows, all_pivots) default(none) //proc_bind(spread)
{
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_GETTING_PIVOTS);
int i, j;
int me = omp_get_thread_num();
int start = distribution_perms[me] ;
int end = distribution_perms[me+1];
int *my_col_perms = (int *) self->workspace[me];
int *my_row_perms = &my_col_perms[nb_cols];
int my_nb_cols = 0, my_nb_rows = 0;
/* Updte the invr_*_perms arrays */
for( i = start; i < end; i++)
{
invr_col_perms[col_perms[i]] = i;
invr_row_perms[row_perms[i]] = i;
}
#pragma omp barrier
/* Updte the logical arrays with the non-singelton pivots */
for ( i = start; i < end; i++)
{
CSC_struct *CSC = &S->CSC[col_perms[i]];
int *rows = CSC->row;
int nb_elem = CSC->nb_elem;
for ( j = 0; j < nb_elem; j++) {
logical_rows[rows[j]] = base;
}
CSR_struct *CSR = &S->CSR[row_perms[i]];
int *cols = CSR->col;
nb_elem = CSR->nb_elem;
for ( j = 0; j < nb_elem; j++) {
logical_cols[cols[j]] = base;
}
}
#pragma omp barrier
#pragma omp single
{
/*
Sequential updte the logical arrays with the col_singeltons.
This is done seq beacuse the update in parallel will need to use atomics.
We need to treat the col singeltons separately, because we need to indetify
entries that are in the pivotal square matrix in order to put them in U.
*/
start = self->done_pivots + self->nb_row_singletons;
end = self->done_pivots + self->nb_row_singletons + self->nb_col_singletons;
for ( i = start; i < end; i++)
{
CSR_struct *CSR = &S->CSR[row_perms[i]];
int *cols = CSR->col;
int nb_elem = CSR->nb_elem;
for ( j = 0; j < nb_elem; j++) {
int col = cols[j];
int perm = invr_col_perms[col];
if (perm != ParSHUM_UNUSED_PIVOT && perm > end)
if (col_perms[perm] < n)
col_perms[perm] += n;
logical_cols[col] = base;
}
}
*distribution_perms = self->done_pivots;
for(i = 1; i < nb_threads; i++)
distribution_perms[i] = *distribution_perms + (self->nb_row_singletons / nb_threads) * i;
distribution_perms[nb_threads] = *distribution_perms + self->nb_row_singletons;
}
#pragma omp barrier
start = distribution_perms[me] ;
end = distribution_perms[me+1];
for ( i = start; i < end; i++)
{
CSC_struct *CSC = &S->CSC[col_perms[i]];
int *rows = CSC->row;
int nb_elem = CSC->nb_elem;
for ( j = 0; j < nb_elem; j++) {
logical_rows[rows[j]] = base;
}
}
#pragma omp barrier
start = distribution_n[me];
end = distribution_n[me+1];
for( i = start; i < end; i++) {
int col = cols[i];
if(logical_cols[col] == base && invr_col_perms[col] == ParSHUM_UNUSED_PIVOT)
my_col_perms[my_nb_cols++] = col;
}
start = distribution_m[me];
end = distribution_m[me+1];
for( i = start; i < end; i++) {
int row = rows[i];
if(logical_rows[row] == base && invr_row_perms[row] == ParSHUM_UNUSED_PIVOT)
my_row_perms[my_nb_rows++] = row;
}
col_sizes[me] = my_nb_cols;
row_sizes[me] = my_nb_rows;
#pragma omp barrier
#pragma omp single
{
for (i = 1; i < nb_threads; i++) {
col_sizes[i] += col_sizes[i-1];
row_sizes[i] += row_sizes[i-1];
}
self->n_U_structs = col_sizes[nb_threads-1];
self->n_L_structs = row_sizes[nb_threads-1];
}
#pragma omp barrier
if (me) {
memcpy(&col_perms[all_pivots + col_sizes[me-1]], my_col_perms,
(size_t) (col_sizes[me] - col_sizes[me-1]) * sizeof(*col_perms));
memcpy(&row_perms[all_pivots + row_sizes[me-1]], my_row_perms,
(size_t) (row_sizes[me] - row_sizes[me-1]) * sizeof(*row_perms));
} else {
memcpy(&col_perms[all_pivots], my_col_perms, (size_t) col_sizes[me] * sizeof(*col_perms));
memcpy(&row_perms[all_pivots], my_row_perms, (size_t) row_sizes[me] * sizeof(*row_perms));
for( i = n - nb_BB_cols; i < n; i++)
if (logical_cols[i] == base && invr_col_perms[i] == ParSHUM_UNUSED_PIVOT)
col_perms[all_pivots + self->n_U_structs++] = i;
}
ParSHUM_verbose_trace_stop_event(verbose);
}
self->found_pivots = all_pivots;
ParSHUM_verbose_update_pivots(self->verbose, new_pivots);
}
void
ParSHUM_solver_check_counters(ParSHUM_solver self)
{
int i;
for (i = 0; i < self->nb_counters; i++)
ParSHUM_check_counters(i, self->counters[i]->array, self->counters[i]->used_counters,
self->done_pivots + 1, self->size_counters, self->A->n);
}
void
ParSHUM_solver_find_pivot_set(ParSHUM_solver self)
{
ParSHUM_pivot_list list;
ParSHUM_exe_parms exe_parms = self->exe_parms;
ParSHUM_verbose_per_step step = ParSHUM_verbose_get_step(self->verbose);
ParSHUM_verbose verbose = self->verbose;
int nb_threads = self->exe_parms->nb_threads;
/* TOCORRECT */
/* int needed_pivots = self->A->n < self->A->m ? self->A->n : self->A->m; */
int needed_pivots = self->A->n - self->BB_cols - 1;
needed_pivots -= self->done_pivots;
int new_pivots = 0;
ParSHUM_verbose_start_timing(&step->timing_extracting_candidates);
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_GET_SINGELTONS);
ParSHUM_schur_get_singletons(self->S, self->done_pivots, self->previous_step_pivots,
self->exe_parms->value_tol * self->exe_parms->singeltons_relaxation,
&self->nb_col_singletons, &self->nb_row_singletons, self->cols,
self->rows, self->distributions, self->BB_cols, self->col_perm,
self->row_perm, self->invr_col_perm, self->invr_row_perm, self->workspace);
/* We should check if we have found more then enought singletons */
needed_pivots -= self->nb_col_singletons + self->nb_row_singletons;
ParSHUM_verbose_trace_stop_event(verbose);
if (exe_parms->luby_algo) {
if (needed_pivots > 0) {
int nb_cols = self->S->n - self->done_pivots - self->BB_cols;
int *distributions = self->distributions;
long best_marko, best_markos[nb_threads];
int candidates[nb_threads];
int i;
*distributions = 0;
for (i = 1; i < nb_threads; i++)
distributions[i] = (nb_cols / nb_threads) * i;
distributions[nb_threads] = nb_cols;
#pragma omp parallel num_threads(nb_threads) shared(self, nb_cols, best_marko, best_markos, distributions, candidates, step) firstprivate(verbose, exe_parms, i, nb_threads) default(none) //proc_bind(spread)
{
int me = omp_get_thread_num();
int *my_col_perms = (int *) self->workspace[me];
int *my_row_perms = &my_col_perms[nb_cols];
int *global_col_perms = (int *) self->workspace[0];
int *global_row_perms = &global_col_perms[nb_cols];
int max_col_length = self->S->nnz /nb_cols ;
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_GET_ELIGEBLE);
best_markos[me] = ParSHUM_Luby_get_eligible(self->S, self->Luby, exe_parms->value_tol, self->invr_col_perm, self->invr_row_perm, self->cols, distributions[me], distributions[me + 1], max_col_length);
ParSHUM_verbose_trace_stop_event(verbose);
#pragma omp barrier
#pragma omp single
{
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_AUXILIARY);
best_marko = *best_markos;
for(i = 1; i < nb_threads; i++)
best_marko = best_marko > best_markos[i] ? best_markos[i] : best_marko;
best_marko = !best_marko ? 1 : best_marko;
best_marko *= exe_parms->marko_tol;
ParSHUM_verbose_trace_stop_event(verbose);
}
#pragma omp barrier
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_ASSIGN_SCORE);
candidates[me] = ParSHUM_Luby_assign_score(self->Luby, self->S, best_marko, &self->seeds[me], my_col_perms, my_row_perms, self->cols, distributions[me], distributions[me + 1]);
ParSHUM_verbose_trace_stop_event(verbose);
#pragma omp barrier
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_AUXILIARY);
#pragma omp single
{
for( i = 1; i < nb_threads; i++)
candidates[i] += candidates[i-1];
step->nb_candidates = candidates[nb_threads-1];
}
#pragma omp barrier
if (me) {
memcpy(&global_col_perms[candidates[me - 1]], my_col_perms, (size_t) (candidates[me] - candidates[me-1]) * sizeof(*self->col_perm));
memcpy(&global_row_perms[candidates[me - 1]], my_row_perms, (size_t) (candidates[me] - candidates[me-1]) * sizeof(*self->row_perm));
}
ParSHUM_verbose_trace_stop_event(verbose);
}
ParSHUM_verbose_stop_timing(&step->timing_extracting_candidates);
ParSHUM_verbose_start_timing(&step->timing_merging_pivots);
/*
This restrictoin most be done for the recantular (overderminated)
case, so that we do not find too many pivots
*/
if (step->nb_candidates > needed_pivots)
step->nb_candidates = needed_pivots;
*distributions = 0;
for (i = 1; i < nb_threads; i++)
distributions[i] = (step->nb_candidates / nb_threads) * i;
distributions[nb_threads] = step->nb_candidates;
#pragma omp parallel num_threads(nb_threads) shared(self, nb_cols, distributions, candidates) firstprivate(verbose, i, nb_threads) default(none) //proc_bind(spread)
{
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_FIRST_PASS);
int me = omp_get_thread_num();
int non_BB_cols = self->S->n - self->BB_cols;
int my_size = distributions[me + 1] - distributions[me];
int *tmp = (int *) self->workspace[0];
int *my_col_perms = &tmp[distributions[me]];
int *my_row_perms = &tmp[nb_cols + distributions[me]];
int *global_col_perms = &self->col_perm[self->done_pivots + self->nb_col_singletons + self->nb_row_singletons];
int *global_row_perms = &self->row_perm[self->done_pivots + self->nb_col_singletons + self->nb_row_singletons];
ParSHUM_Luby_first_pass(self->Luby, self->S, non_BB_cols, my_col_perms, my_row_perms, my_size);
ParSHUM_verbose_trace_stop_event(verbose);
#pragma omp barrier
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_DISCARDING_PIVOTS);
candidates[me] = ParSHUM_Luby_second_pass(self->S, self->Luby, my_col_perms, my_row_perms, my_size);
ParSHUM_verbose_trace_stop_event(verbose);
#pragma omp barrier
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_AUXILIARY);
#pragma omp single
{
self->Luby->chosen_base += 3;
for( i = 1; i < nb_threads; i++)
candidates[i] += candidates[i-1];
}
#pragma omp barrier
if (me) {
memcpy(&global_col_perms[candidates[me-1]], my_col_perms, (size_t) (candidates[me] - candidates[me-1]) * sizeof(*my_col_perms));
memcpy(&global_row_perms[candidates[me-1]], my_row_perms,(size_t) (candidates[me] - candidates[me-1]) * sizeof(*self->row_perm));
} else {
memcpy(global_col_perms, my_col_perms, (size_t) candidates[me] * sizeof(*my_col_perms));
memcpy(global_row_perms, my_row_perms, (size_t) candidates[me] * sizeof(*my_row_perms));
}
ParSHUM_verbose_trace_stop_event(verbose);
}
new_pivots = candidates[nb_threads-1];
} else { // needed_pivots
ParSHUM_verbose_start_timing(&step->timing_merging_pivots);
}
ParSHUM_solver_get_Luby_pivots(self, self->Luby, new_pivots);
if (self->debug & ParSHUM_CHECK_PIVOTS)
ParSHUM_check_logical_sum(self, new_pivots);
ParSHUM_verbose_stop_timing(&step->timing_merging_pivots);
if (self->debug & (ParSHUM_DEBUG_VERBOSE_EACH_STEP | ParSHUM_DEBUG_GOSSIP_GIRL)) {
char mess[2048];
snprintf(mess, 2048,"%d row singeltons, %d col_singeltons and %d luby pivots were found\ncol pemrs",
self->nb_row_singletons, self->nb_col_singletons, new_pivots);
print_int_array(self->col_perm, self->A->n, mess);
print_int_array(self->row_perm, self->A->m, "row_perms");
print_int_array(self->invr_col_perm, self->A->m, "invr_col_perms");
print_int_array(self->invr_row_perm, self->A->m, "invr_row_perms");
}
} else {
if (self->debug & ParSHUM_CHECK_COUNTERS )
ParSHUM_solver_check_counters(self);
ParSHUM_verbose_start_timing(&step->timing_extracting_candidates);
list = get_possible_pivots(self, self->S, self->random_col, self->candidates, nb_threads,
exe_parms->value_tol, exe_parms->marko_tol,
exe_parms->nb_candidates_per_block);
ParSHUM_verbose_stop_timing(&step->timing_extracting_candidates);
if( !list->nb_elem )
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "no possible pivot were found");
ParSHUM_verbose_start_timing(&step->timing_merging_pivots);
list = merge_pivot_sets(list, self->S, self);
if (list->nb_elem > 1 )
ParSHUM_warning(__FUNCTION__, __FILE__, __LINE__, "not unique set");
ParSHUM_solver_get_pivots(self, list->sets);
if (self->debug & ParSHUM_CHECK_COUNTERS )
ParSHUM_check_current_counters(self->S, &self->col_perm[self->done_pivots], &self->row_perm[self->done_pivots],
self->found_pivots - self->done_pivots,
self->cols_count, self->rows_count, self->done_pivots + 1);
if (self->debug & (ParSHUM_DEBUG_VERBOSE_EACH_STEP | ParSHUM_DEBUG_GOSSIP_GIRL))
print_pivot_list(list, "found pivots");
ParSHUM_pivot_list_destroy(list, self);
ParSHUM_verbose_stop_timing(&step->timing_merging_pivots);
}
}
void
ParSHUM_solver_update_matrix(ParSHUM_solver self)
{
ParSHUM_L_matrix L = self->L;
ParSHUM_matrix D = self->D;
ParSHUM_U_matrix U = self->U;
ParSHUM_schur_matrix S = self->S;
int nb_pivots = self->found_pivots - self->done_pivots;
ParSHUM_verbose_per_step step = ParSHUM_verbose_get_step(self->verbose);
ParSHUM_verbose_start_timing(&step->timing_update_LD);
ParSHUM_schur_matrix_update_LD(S, L, U, D, &self->row_perm[self->done_pivots],
&self->col_perm[self->done_pivots], nb_pivots,
self->invr_row_perm, self->nb_row_singletons,
self->nb_col_singletons, self->workspace);
ParSHUM_verbose_stop_timing(&step->timing_update_LD);
ParSHUM_verbose_start_timing(&step->timing_update_S);
ParSHUM_schur_matrix_update_S(S, L, U, &self->col_perm[self->found_pivots],
self->n_U_structs, &self->row_perm[self->found_pivots],
self->n_L_structs, self->row_perm, self->invr_col_perm,
self->invr_row_perm, nb_pivots, self->done_pivots,
self->exe_parms->value_tol, self->workspace);
ParSHUM_verbose_stop_timing(&step->timing_update_S);
self->done_pivots = self->found_pivots;
self->step++;
if (self->debug & ParSHUM_CHECK_SCHUR_SYMETRY )
ParSHUM_schur_matrix_check_symetry(self->S);
if (self->debug & ParSHUM_CHECK_PIVOTS)
ParSHUM_schur_matrix_check_pivots(self->S, self->row_perm, self->col_perm,
self->invr_row_perm, self->invr_col_perm,
self->done_pivots);
if (self->debug & (ParSHUM_DEBUG_VERBOSE_EACH_STEP | ParSHUM_DEBUG_GOSSIP_GIRL)) {
ParSHUM_schur_matrix_print(S, "S after update");
ParSHUM_L_matrix_print(L, "L after update");
ParSHUM_matrix_print(D, "D after update");
ParSHUM_U_matrix_print(U, "U after update");
}
if (self->debug & ParSHUM_CHECK_SCHUR_DOUBLES) {
ParSHUM_schur_check_doubles(S);
}
}
int
ParSHUM_continue_pivot_search(ParSHUM_schur_matrix S,
int nb_done_pivots,
int nb_needed_pivots,
int *previous_pivots,
int nb_previous_pivots,
double density_tolerance,
int min_pivot_per_steps,
int max_dense_schur,
int debug,
ParSHUM_verbose verbose)
{
long n_schur, m_schur, i, sum_pivots;
int retval = 1;
if ( debug & ParSHUM_CHECK_ParSHUM_W_PLASMA_PERM ||
debug & ParSHUM_CHECK_DENSE_W_ParSHUM_PERM ) {
verbose->reason = ParSHUM_reason_because;
return 0;
}
n_schur = (long) S->n - nb_done_pivots;
m_schur = (long) S->m - nb_done_pivots;
if ( S->nnz > (long) n_schur * m_schur * density_tolerance) {
verbose->reason = ParSHUM_reason_density;
retval = 0;
}
if (retval)
{
for( i = 0, sum_pivots = 0; i < nb_previous_pivots; i++)
sum_pivots += previous_pivots[i];
if (sum_pivots < min_pivot_per_steps) {
verbose->reason = ParSHUM_reason_no_pivots;
retval = 0;
}
}
if (nb_done_pivots >= nb_needed_pivots && retval) {
verbose->reason = ParSHUM_reason_no_pivots;
retval = 0;
}
if ( !retval && max_dense_schur < (nb_needed_pivots - nb_done_pivots) ) {
verbose->reason |= ParSHUM_reason_dense_too_large;
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "dense schur too large");
}
return retval;
}
void
ParSHUM_solver_factorize(ParSHUM_solver self)
{
ParSHUM_exe_parms exe_parms = self->exe_parms;
ParSHUM_verbose verbose = self->verbose;
int n = self->S->n, m = self->S->m;
int needed_pivots = n < m ? n : m;
int *previous_pivots = self->previous_pivots;
int nb_previous_pivots = exe_parms->nb_previous_pivots;
int nb_pivot_blocks = 0;
/* TOCORRECT */
/* needed_pivots -= self->BB_cols + 1; */
/* if (n - self->BB_cols + 1 < needed_pivots) */
needed_pivots = n - self->BB_cols - 1;
if (self->debug & ParSHUM_CHECK_SCHUR_DOUBLES)
ParSHUM_schur_check_doubles(self->S);
ParSHUM_verbose_start_timing(&verbose->timing_facto);
ParSHUM_verbose_start_timing(&verbose->timing_facto_sparse);
while ( ParSHUM_continue_pivot_search(self->S, self->done_pivots, needed_pivots,
previous_pivots, nb_previous_pivots,
exe_parms->density_tolerance,
exe_parms->min_pivot_per_steps,
exe_parms->max_dense_schur,
self->debug, verbose) )
{
ParSHUM_verbose_per_step step = ParSHUM_verbose_step_start(verbose);
ParSHUM_verbose_start_timing(&step->timing_step);
ParSHUM_verbose_start_timing(&step->timing_pivot_search);
ParSHUM_solver_find_pivot_set(self);
previous_pivots[nb_pivot_blocks++ % nb_previous_pivots] = self->found_pivots - self->done_pivots;
ParSHUM_verbose_stop_timing(&step->timing_pivot_search);
ParSHUM_verbose_start_timing(&step->timing_apply_perms);
ParSHUM_solver_update_matrix(self);
ParSHUM_verbose_stop_timing(&step->timing_apply_perms);
ParSHUM_verbose_stop_timing(&step->timing_step);
}
ParSHUM_verbose_stop_timing(&verbose->timing_facto_sparse);
if (verbose->reason & ParSHUM_reason_dense_too_large)
return;
ParSHUM_verbose_start_timing(&verbose->timing_convert_schur);
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_CONVERT_MATRIX);
if ( self->debug & ParSHUM_CHECK_DENSE_W_ParSHUM_PERM ) {
self->A_debug = ParSHUM_dense_2D_permute(ParSHUM_dense_2D_convert_sparse(self->A),
self->row_perm, self->col_perm);
verbose->schur_density = 1.00;
} else {
self->S_dense = ParSHUM_schur_matrix_convert(self->S, self->done_pivots,
self->col_perm, self->invr_col_perm,
self->row_perm, self->invr_row_perm);
verbose->schur_density =
(double) self->S->nnz / ((n - self->done_pivots) * (m - self->done_pivots));
/* if (self->debug & (ParSHUM_DEBUG_VERBOSE_EACH_STEP | ParSHUM_DEBUG_GOSSIP_GIRL)) { */
/* printf("done pivots = %d \n", self->done_pivots); */
/* ParSHUM_dense_matrix_print(self->S_dense, "dense schur after conversion"); */
/* print_int_array(self->col_perm, self->A->n, "col_perms"); */
/* print_int_array(self->row_perm, self->A->m, "row_perms"); */
/* print_int_array(self->invr_col_perm, self->A->n, "invr_col_perms"); */
/* print_int_array(self->invr_row_perm, self->A->m, "invr_row_perms"); */
/* } */
}
ParSHUM_verbose_trace_stop_event(verbose);
ParSHUM_verbose_stop_timing(&verbose->timing_convert_schur);
ParSHUM_verbose_start_timing(&verbose->timing_facto_dense);
ParSHUM_verbose_trace_start_event(verbose, ParSHUM_DENSE_FACTORIZATION);
if (self->debug & ParSHUM_CHECK_DENSE_W_ParSHUM_PERM) {
ParSHUM_dense_2D_facto(self->A_debug);
} else {
ParSHUM_dense_matrix_factorize(self->S_dense, self->BB_cols, exe_parms->nb_threads);
self->dense_pivots = self->A->n - self->done_pivots;
ParSHUM_verbose_update_dense_pivots(verbose, self->dense_pivots);
verbose->nnz_final = self->L->nnz + self->U->nnz + self->D->n +
(self->S_dense->n - self->BB_cols) * self->S_dense->m + self->BB_cols * (self->S_dense->m - self->BB_cols);
verbose->nnz_L = self->L->nnz + ( self->S_dense->n - self->BB_cols ) * self->S_dense->m -
((self->S_dense->n - self->BB_cols)*(self->S_dense->n - self->BB_cols) - self->S_dense->n + self->BB_cols ) / 2;
verbose->nnz_U = self->U->nnz + self->D->n +
((self->S_dense->n-self->BB_cols) * (self->S_dense->n-self->BB_cols) - self->S_dense->m + self->BB_cols)/2
+ self->S_dense->n - self->BB_cols + self->BB_cols * (self->S_dense->m - self->BB_cols);
verbose->nnz_S_dense = (self->S_dense->n - self->BB_cols) * self->S_dense->m +
self->BB_cols * (self->S_dense->m - self->BB_cols);
}
ParSHUM_verbose_trace_stop_event(verbose);
ParSHUM_verbose_stop_timing(&verbose->timing_facto_dense);
ParSHUM_verbose_stop_timing(&verbose->timing_facto);
}
void
ParSHUM_solver_solve(ParSHUM_solver self, ParSHUM_vector RHS)
{
if (self->verbose->reason & ParSHUM_reason_dense_too_large)
return;
double *RHS_vals = RHS->vect;
ParSHUM_verbose verbose = self->verbose;
ParSHUM_verbose_start_timing(&verbose->timing_solve);
if (self->debug & ParSHUM_CHECK_DENSE_W_ParSHUM_PERM ) {
ParSHUM_vector_permute(RHS, self->row_perm, self->A_debug->m);
ParSHUM_dense_2D_solve(self->A_debug, RHS);
ParSHUM_vector_permute(RHS, self->invr_col_perm, self->A_debug->m);
} else {
ParSHUM_verbose_start_timing(&verbose->timing_solve_L);
if (self->debug & ParSHUM_DEBUG_GOSSIP_GIRL)
ParSHUM_vector_print(RHS, "Init RHS");
ParSHUM_L_matrix_solve(self->L, RHS, self->row_perm);
if (self->debug & ParSHUM_DEBUG_GOSSIP_GIRL)
ParSHUM_vector_print(RHS, "after forward solve");
ParSHUM_verbose_stop_timing(&verbose->timing_solve_L);
ParSHUM_verbose_start_timing(&verbose->timing_solve_dense);
if (self->S_dense->n && self->S_dense->m) {
if (self->S_dense->n == self->S_dense->m) {
double *dense_RHS = (double *) *self->workspace;
ParSHUM_dense_matrix_get_RHS(self->S_dense, dense_RHS, &self->row_perm[self->done_pivots], RHS_vals, ParSHUM_perm_global);
#ifdef USE_PLASMA
plasma_dgetrs(self->S_dense->n, 1, self->S_dense->val, self->S_dense->n,
self->S_dense->pivots, dense_RHS, self->S_dense->n);
#else
LAPACKE_dgetrs(LAPACK_COL_MAJOR, 'N', self->S_dense->n, 1, self->S_dense->val, self->S_dense->n, self->S_dense->pivots, dense_RHS, self->S_dense->n);
#endif
ParSHUM_dense_matrix_update_RHS(self->S_dense, dense_RHS, &self->row_perm[self->done_pivots], RHS_vals);
} else if ( self->S_dense->n < self->S_dense->m ) {
int diff_size = self->S_dense->m - self->S_dense->n;
double *dense_RHS = (double *) *self->workspace;
ParSHUM_dense_matrix_get_RHS(self->S_dense, dense_RHS, &self->row_perm[self->done_pivots], RHS_vals, ParSHUM_perm_both);
#ifdef USE_PLASMA
plasma_dtrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaUnit, self->S_dense->n, 1, 1.0, self->S_dense->val,self->S_dense->m, dense_RHS, self->S_dense->m);
plasma_dgemm(PlasmaNoTrans, PlasmaNoTrans, diff_size, 1, self->S_dense->n, -1.0, &self->S_dense->val[self->S_dense->m - diff_size], self->S_dense->m, dense_RHS, self->S->m, 1.0, &dense_RHS[self->S_dense->n], self->S->m);
plasma_dtrsm(PlasmaLeft, PlasmaUpper, PlasmaNoTrans, PlasmaNonUnit, self->S_dense->n, 1, 1.0, self->S_dense->val, self->S_dense->m, dense_RHS, self->S_dense->m);
#else
cblas_dtrsm(CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit, self->S_dense->n, 1, 1.0, self->S_dense->val,self->S_dense->m, dense_RHS, self->S_dense->m);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, diff_size, 1, self->S_dense->n, -1.0, &self->S_dense->val[self->S_dense->m - diff_size], self->S_dense->m, dense_RHS, self->S->m, 1.0, &dense_RHS[self->S_dense->n], self->S->m);
cblas_dtrsm(CblasColMajor, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, self->S_dense->n, 1, 1.0, self->S_dense->val, self->S_dense->m, dense_RHS, self->S_dense->m);
#endif
ParSHUM_dense_matrix_update_RHS(self->S_dense, dense_RHS, &self->row_perm[self->done_pivots], RHS_vals);
} else {
ParSHUM_fatal_error(__FUNCTION__, __FILE__, __LINE__, "not implemeted");
}
}
if (self->debug & ParSHUM_DEBUG_GOSSIP_GIRL)
ParSHUM_vector_print(RHS, "after dense solve");
ParSHUM_verbose_stop_timing(&verbose->timing_solve_dense);
ParSHUM_verbose_start_timing(&verbose->timing_solve_U);
ParSHUM_U_matrix_solve(self->U, self->D, RHS, self->col_perm, self->row_perm, self->dense_pivots);
if (self->debug & (ParSHUM_DEBUG_VERBOSE_EACH_STEP | ParSHUM_DEBUG_GOSSIP_GIRL))
ParSHUM_vector_print(RHS, "after backward solve");
ParSHUM_vector_permute(RHS, self->row_perm, self->S->m);
if (self->debug & ParSHUM_DEBUG_GOSSIP_GIRL)
ParSHUM_vector_print(RHS, "P RHS");
ParSHUM_vector_permute(RHS, self->invr_col_perm, self->S->n);
if (self->debug & (ParSHUM_DEBUG_VERBOSE_EACH_STEP | ParSHUM_DEBUG_GOSSIP_GIRL))
ParSHUM_vector_print(RHS, "after solve operation");
ParSHUM_verbose_stop_timing(&verbose->timing_solve_U);
}
ParSHUM_verbose_computed_norms(verbose);
ParSHUM_verbose_stop_timing(&verbose->timing_solve);
}
/* #include <mpi.h> */
/* void */
/* ParSHUM_solver_SBBD_solve(ParSHUM_solver self, ParSHUM_vector RHS, ParSHUM_vector schur_RHS_v, */
/* ParSHUM_dense_matrix global_schur, int *distribution, */
/* int **BB_index, int *BB_sizes, ParSHUM_MPI_info MPI_info) */
/* { */
/* double *RHS_vals = RHS->vect; */
/* int rank = MPI_info->rank; */
/* MPI_Comm comm = MPI_info->world; */
/* int BB_cols = self->BB_cols; */
/* int nb_blocks = MPI_info->MPI_size; */
/* int square_n = self->S_dense->n - BB_cols; */
/* int rest_m = self->S_dense->m - square_n; */
/* double *dense_RHS = (double *) *self->workspace; */
/* double *BB_rhs = malloc(BB_cols * sizeof(*BB_rhs)); */
/* MPI_Status status; */
/* if (self->debug & ParSHUM_DEBUG_VERBOSE_EACH_STEP) */
/* ParSHUM_vector_print(RHS, "Init RHS"); */
/* ParSHUM_L_matrix_solve(self->L, RHS, self->row_perm); */
/* if (self->debug & ParSHUM_DEBUG_VERBOSE_EACH_STEP) */
/* ParSHUM_vector_print(RHS, "after forward solve"); */
/* ParSHUM_dense_matrix_get_RHS(self->S_dense, dense_RHS, &self->row_perm[self->done_pivots], RHS_vals, ParSHUM_perm_both); */
/* #ifdef USE_PLASMA */
/* plasma_dtrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaUnit, square_n, 1, 1.0, */
/* self->S_dense->val, self->S_dense->m, dense_RHS, self->S_dense->m); */
/* plasma_dgemm(PlasmaNoTrans, PlasmaNoTrans, rest_m, 1, square_n, -1.0, */
/* &self->S_dense->val[square_n], self->S_dense->m, */
/* dense_RHS, self->S->m, 1.0, &dense_RHS[square_n], self->S->m); */
/* #else */
/* cblas_dtrsm(CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit, square_n, */
/* 1, 1.0, self->S_dense->val, self->S_dense->m, dense_RHS, self->S_dense->m); */
/* cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, rest_m, 1, square_n, -1.0, */
/* &self->S_dense->val[square_n], self->S_dense->m, */
/* dense_RHS, self->S->m, 1.0, &dense_RHS[square_n], self->S->m); */
/* #endif */
/* if (rank == 0) { */
/* int block, i; */
/* double *send_buff; */
/* int max_size = 0; */
/* double *schur_RHS = schur_RHS_v->vect; */
/* memcpy(schur_RHS, &dense_RHS[square_n], rest_m * sizeof(*schur_RHS)); */
/* for( block = 1; block < nb_blocks; block++) { */
/* MPI_Recv(&schur_RHS[distribution[block]], distribution[block+1] - distribution[block], */
/* MPI_DOUBLE, block, 0, comm, &status); */
/* } */
/* #ifdef USE_PLASMA */
/* plasma_dgetrs(global_schur->n, 1, global_schur->val, global_schur->n, */
/* global_schur->pivots, schur_RHS, global_schur->n); */
/* #else */
/* LAPACKE_dgetrs(LAPACK_COL_MAJOR, 'N', global_schur->n, 1, global_schur->val, global_schur->n, global_schur->pivots, schur_RHS, global_schur->n); */
/* #endif */
/* if (self->debug & ParSHUM_DEBUG_VERBOSE_EACH_STEP) */
/* ParSHUM_vector_print(schur_RHS_v, "global schur RHS"); */
/* for( block = 1; block < nb_blocks; block++) { */
/* int local_size = BB_sizes[block]; */
/* max_size = max_size > local_size ? max_size : local_size; */
/* } */
/* send_buff = malloc(max_size * sizeof(*send_buff)); */
/* for( block = 1; block < nb_blocks; block++) { */
/* int *indices = BB_index[block]; */
/* for ( i =0; i < BB_sizes[block]; i++) */
/* send_buff[i] = schur_RHS[indices[i]]; */
/* MPI_Send(send_buff, BB_sizes[block], MPI_DOUBLE, block, 0, comm); */
/* } */
/* int *indices = *BB_index; */
/* for(i = 0; i < BB_cols; i++) */
/* BB_rhs[i] = schur_RHS[indices[i]]; */
/* } else { */
/* MPI_Send(&dense_RHS[square_n], rest_m, MPI_DOUBLE, 0, 0, comm); */
/* MPI_Recv(BB_rhs, BB_cols, MPI_DOUBLE, 0, 0, comm, &status); */
/* } */
/* #ifdef USE_PLASMA */
/* plasma_dgemm(PlasmaNoTrans, PlasmaNoTrans, square_n, 1, BB_cols, -1.0, */
/* &self->S_dense->val[square_n*self->S_dense->m], self->S_dense->m, */
/* BB_rhs, BB_cols, 1.0, dense_RHS, self->S->m); */
/* plasma_dtrsm(PlasmaLeft, PlasmaUpper, PlasmaNoTrans, PlasmaNonUnit, square_n, 1, 1.0, */
/* self->S_dense->val, self->S_dense->m, dense_RHS, self->S_dense->m); */
/* #else */
/* cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, square_n, 1, BB_cols, -1.0, */
/* &self->S_dense->val[square_n*self->S_dense->m], self->S_dense->m, */
/* BB_rhs, BB_cols, 1.0, dense_RHS, self->S->m); */
/* cblas_dtrsm(CblasColMajor, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, square_n, 1, 1.0, */
/* self->S_dense->val, self->S_dense->m, dense_RHS, self->S_dense->m); */
/* #endif */
/* ParSHUM_dense_matrix_update_RHS(self->S_dense, dense_RHS, &self->row_perm[self->done_pivots], RHS_vals); */
/* if (self->debug & ParSHUM_DEBUG_VERBOSE_EACH_STEP) */
/* ParSHUM_vector_print(RHS, "after dense solve"); */
/* ParSHUM_U_BB_matrix_solve(self->U, self->D, RHS, BB_rhs, self->col_perm, self->row_perm, */
/* self->dense_pivots, BB_cols); */
/* if (self->debug & ParSHUM_DEBUG_VERBOSE_EACH_STEP) */
/* ParSHUM_vector_print(RHS, "after backward solve"); */
/* ParSHUM_vector_permute(RHS, self->row_perm, self->S->m); */
/* if (self->debug & ParSHUM_DEBUG_VERBOSE_EACH_STEP) */
/* ParSHUM_vector_print(RHS, "P RHS"); */
/* ParSHUM_vector_permute(RHS, self->invr_col_perm, self->S->n - BB_cols); */
/* if (self->debug & ParSHUM_DEBUG_VERBOSE_EACH_STEP) */
/* ParSHUM_vector_print(RHS, "after solve operation"); */
/* } */
void
ParSHUM_solver_compute_norms(ParSHUM_solver self,
ParSHUM_vector X,
ParSHUM_vector rhs)
{
if (self->verbose->reason & ParSHUM_reason_dense_too_large)
return;
double x_norm, A_norm, b_norm;
ParSHUM_vector r = ParSHUM_vector_create(X->n);
/* || r = Ax - b || */
ParSHUM_matrix_SpMV(self->A, X, r);
ParSHUM_vector_add(r, 1.00, rhs, -1.00, r);
self->verbose->backward_error = ParSHUM_vector_2norm(r);
A_norm = ParSHUM_matrix_get_norm(self->A);
x_norm = ParSHUM_vector_2norm(X);
b_norm = ParSHUM_vector_2norm(rhs);
self->verbose->backward_error /= A_norm * x_norm + b_norm;
printf("error = %e\n", self->verbose->backward_error);
ParSHUM_vector_destroy(r);
}
/* void */
/* ParSHUM_solver_iterative_refinement(ParSHUM_solver self, */
/* ParSHUM_vector X, */
/* ParSHUM_vector rhs, */
/* double wanted_precision) */
/* { */
/* if (self->verbose->reason & ParSHUM_reason_dense_too_large) */
/* return; */
/* ParSHUM_vector sol = ParSHUM_vector_create(self->A->n); */
/* ParSHUM_vector tmp = ParSHUM_vector_create(self->A->n); */
/* int i = 0; */
/* ParSHUM_vector_copy(rhs, sol); */
/* ParSHUM_solver_solve(self, sol); */
/* ParSHUM_solver_copmpute_norms(self, X, sol, rhs); */
/* printf("iteration %d: backward error = %e and forward error = %e\n", */
/* i++, */
/* self->verbose->backward_error, */
/* self->verbose->forward_error); */
/* while ( i < 20 && self->verbose->backward_error > wanted_precision) { */
/* ParSHUM_matrix_SpMV(self->A, sol, tmp); */
/* ParSHUM_vector_add(rhs, 1.00, tmp, -1.00, tmp); */
/* ParSHUM_solver_solve(self, tmp); */
/* ParSHUM_vector_add(sol, 1.00, tmp, 1.00, sol); */
/* ParSHUM_solver_copmpute_norms(self, X, sol, rhs); */
/* printf("iteration %d: backward error = %e and forward error = %e\n", */
/* i++, */
/* self->verbose->backward_error, */
/* self->verbose->forward_error); */
/* } */
/* ParSHUM_vector_destroy(sol); */
/* ParSHUM_vector_destroy(tmp); */
/* } */
void
ParSHUM_solver_finalize(ParSHUM_solver self)
{
#ifdef USE_PLASMA
if (is_plasma_init) {
plasma_finalize();
is_plasma_init = 0;
}
#endif
ParSHUM_verbose_print(self->verbose);
ParSHUM_verbose_draw_graph(self->verbose);
}
void
ParSHUM_solver_destroy(ParSHUM_solver self)
{
int i;
if (self->debug & ParSHUM_CHECK_DENSE_W_ParSHUM_PERM) {
ParSHUM_dense_2D_destroy(self->A_debug);
} else {
ParSHUM_matrix_destroy(self->A);
ParSHUM_schur_matrix_destroy(self->S);
ParSHUM_L_matrix_destroy(self->L);
ParSHUM_matrix_destroy(self->D);
ParSHUM_U_matrix_destroy(self->U);
if(self->S_dense)
ParSHUM_dense_matrix_destroy(self->S_dense);
free(self->candidates->row);
free(self->candidates->marko);
free(self->candidates->best_marko);
free(self->candidates);
for(i = 0; i < self->nb_counters; i++) {
free(self->counters[i]->array);
free(self->counters[i]->used_counters);
free(self->counters[i]);
}
free(self->counters);
free(self->U_struct);
free(self->L_struct);
pthread_mutex_destroy(&self->counters_lock);
free(self->row_perm);
free(self->col_perm);
free(self->invr_row_perm);
free(self->invr_col_perm);
free(self->random_col);
free(self->previous_pivots);
ParSHUM_Luby_destroy(self->Luby);
}
ParSHUM_solver_dealloc(self);
}
|
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/TypeLoc.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/BitmaskEnum.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/SmallSet.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Frontend/OpenMP/OMPConstants.h"
#include <deque>
#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;
}
};
/// Keeps track of expected type during expression parsing. 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 allows
/// to avoid updating the type on hot paths in the parser.
class PreferredTypeBuilder {
public:
PreferredTypeBuilder() = default;
explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
void enterCondition(Sema &S, SourceLocation Tok);
void enterReturn(Sema &S, SourceLocation Tok);
void enterVariableInit(SourceLocation Tok, Decl *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.
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);
QualType get(SourceLocation Tok) const {
if (Tok != ExpectedLoc)
return QualType();
if (!Type.isNull())
return Type;
if (ComputeType)
return ComputeType();
return QualType();
}
private:
/// 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;
/// A key method to reduce duplicate debug info from Sema.
virtual void anchor();
///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;
/// 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;
void Act(SourceLocation PragmaLocation,
PragmaClangSectionAction Action,
StringLiteral* Name);
};
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)
};
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;
// #pragma pack.
// Sentinel to represent when the stack is set to mac68k alignment.
static const unsigned kMac68kAlignmentSentinel = ~0U;
PragmaStack<unsigned> PackStack;
// The current #pragma pack values and locations at each #include.
struct PackIncludeState {
unsigned CurrentValue;
SourceLocation CurrentPragmaLocation;
bool HasNonDefaultValue, ShouldWarnOnInclude;
};
SmallVector<PackIncludeState, 8> PackIncludeStack;
// Segment #pragmas.
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
// This stack tracks the current state of Sema.CurFPFeatures.
PragmaStack<unsigned> FpPragmaStack;
FPOptionsOverride CurFPFeatureOverrides() {
FPOptionsOverride result;
if (!FpPragmaStack.hasValue()) {
result = FPOptionsOverride();
} else {
result = FPOptionsOverride(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;
}
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;
/// A flag to indicate that we're in a context that permits abstract
/// references to fields. This is really a
bool AllowAbstractFieldReference;
/// 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;
/// Whether we are in a decltype expression.
bool IsDecltype;
/// 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.
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;
}
unsigned getOverrides() { return OldOverrides; }
private:
Sema& S;
FPOptions OldFPFeaturesState;
unsigned OldOverrides;
};
void addImplicitTypedef(StringRef Name, QualType T);
bool WarnedStackExhausted = false;
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();
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; }
///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. SemaDiagnosticBuilder 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 SemaDiagnosticBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
SemaDiagnosticBuilder(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 ~SemaDiagnosticBuilder is a safe no-op
// in that case anwyay.
SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
~SemaDiagnosticBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
// Otherwise, we need to emit the diagnostic. First flush the underlying
// DiagnosticBuilder data, and 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.
FlushCounts();
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 SemaDiagnosticBuilder &operator<<(
const SemaDiagnosticBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
};
/// Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
return SemaDiagnosticBuilder(DB, *this, DiagID);
}
/// Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
/// Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
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.
SmallVector<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 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();
/// 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;
}
};
/// 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);
/// 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);
}
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 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 a non-type, and an expression representing
/// that name has been formed.
NC_ContextIndependentExpr,
/// 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 ContextIndependentExpr(ExprResult E) {
NameClassification Result(NC_ContextIndependentExpr);
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_ContextIndependentExpr);
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);
/// 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);
Decl *ActOnDeclarator(Scope *S, Declarator &D);
NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists);
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());
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);
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);
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(const 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);
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);
/// We've found a use of a template specialization that would select a
/// partial specialization. Check that the partial specialization is visible,
/// and diagnose if not.
void checkPartialSpecializationVisibility(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,
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,
};
/// 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);
NoSpeculativeLoadHardeningAttr *
mergeNoSpeculativeLoadHardeningAttr(Decl *D,
const NoSpeculativeLoadHardeningAttr &AL);
SpeculativeLoadHardeningAttr *
mergeSpeculativeLoadHardeningAttr(Decl *D,
const SpeculativeLoadHardeningAttr &AL);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
const AttributeCommonInfo &CI);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
const InternalLinkageAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
WebAssemblyImportNameAttr *mergeImportNameAttr(
Decl *D, const WebAssemblyImportNameAttr &AL);
WebAssemblyImportModuleAttr *mergeImportModuleAttr(
Decl *D, const WebAssemblyImportModuleAttr &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);
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
const VarDecl *NRVOCandidate,
QualType ResultType,
Expr *Value,
bool AllowNRVO = true);
bool CanPerformAggregateInitializationForOverloadResolution(
const InitializedEntity &Entity, InitListExpr *From);
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_NewExpr, ///< Constant expression in a noptr-new-declarator.
CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
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);
/// 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);
// 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 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);
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_StringTemplate
};
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);
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,
QualType T1, QualType T2,
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);
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
ArrayRef<QualType> ArgTys,
bool AllowRaw,
bool AllowTemplate,
bool AllowStringTemplate,
bool DiagnoseMissing);
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);
/// 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);
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;
/// Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt,
const ParsedAttributesView &Attrs,
SourceRange Range);
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 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 ActOnAttributedStmt(SourceLocation AttrLoc,
ArrayRef<const Attr*> Attrs,
Stmt *SubStmt);
class ConditionResult;
StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
Stmt *InitStmt,
ConditionResult Cond);
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);
enum CopyElisionSemanticsKind {
CES_Strict = 0,
CES_AllowParameters = 1,
CES_AllowDifferentTypes = 2,
CES_AllowExceptionVariables = 4,
CES_FormerDefault = (CES_AllowParameters),
CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
CES_AllowExceptionVariables),
};
VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
CopyElisionSemanticsKind CESK);
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
CopyElisionSemanticsKind CESK);
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
Scope *CurScope);
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
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);
/// 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
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);
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 BuildUniqueStableName(SourceLocation Loc, TypeSourceInfo *Operand);
ExprResult BuildUniqueStableName(SourceLocation Loc, Expr *E);
ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc,
SourceLocation LParen,
SourceLocation RParen, ParsedType Ty);
ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc,
SourceLocation LParen,
SourceLocation RParen, Expr *E);
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);
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 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);
//===---------------------------- 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 HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
const LookupResult &PreviousDecls,
UsingShadowDecl *&PrevShadow);
UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
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);
NamedDecl *BuildUsingDeclaration(
Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList, bool IsInstantiation);
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 *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;
}
};
/// Determine what sort of exception specification a defaulted
/// copy constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// default constructor of a class will have, and whether the parameter
/// will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// copy assignment operator of a class will have, and whether the
/// parameter will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// assignment operator of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// destructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification an inheriting
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
CXXConstructorDecl *CD);
/// 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,
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);
/// 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(SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildCXXFoldExpr(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);
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<unsigned, bool, 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);
/// 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);
/// 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);
/// \brief Emit diagnostics explaining why a constraint expression was deemed
/// unsatisfied because it was ill-formed.
void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
StringRef Diagnostic);
void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old,
SourceLocation New);
// 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.
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 AttachTypeConstraint(NestedNameSpecifierLoc NS,
DeclarationNameInfo NameInfo,
ConceptDecl *NamedConcept,
const TemplateArgumentListInfo *TemplateArgs,
TemplateTypeParmDecl *ConstrainedParameter,
SourceLocation EllipsisLoc);
bool AttachTypeConstraint(AutoTypeLoc TL,
NonTypeTemplateParmDecl *ConstrainedParameter,
SourceLocation EllipsisLoc);
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);
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
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
};
/// 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 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);
/// 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);
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, void *InsertPos,
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);
VarDecl *getVarTemplateSpecialization(
VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
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
};
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 PragmaPackDiagnoseKind {
NonDefaultStateAtInclude,
ChangedStateAtExit
};
void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
SourceLocation IncludeLoc);
void DiagnoseUnterminatedPragmaPack();
/// 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,
DeclaratorDecl *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 to set 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);
/// FreePackedContext - Deallocate and null out PackContext.
void FreePackedContext();
/// 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);
/// 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);
//===--------------------------------------------------------------------===//
// OpenCL extensions.
//
private:
std::string CurrOpenCLExtension;
/// Extensions required by an OpenCL type.
llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
/// Extensions required by an OpenCL declaration.
llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
public:
llvm::StringRef getCurrentOpenCLExtension() const {
return CurrOpenCLExtension;
}
/// Check if a function declaration \p FD associates with any
/// extensions present in OpenCLDeclExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
/// Check if a function type \p FT associates with any
/// extensions present in OpenCLTypeExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
/// Find an extension in an appropriate extension map and return its name
template<typename T, typename MapT>
std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
void setCurrentOpenCLExtension(llvm::StringRef Ext) {
CurrOpenCLExtension = std::string(Ext);
}
/// Set OpenCL extensions for a type which can only be used when these
/// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
/// Set OpenCL extensions for a declaration which can only be
/// used when these OpenCL extensions are enabled. If \p Exts is empty, do
/// nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
/// Set current OpenCL extensions for a type which can only be used
/// when these OpenCL extensions are enabled. If current OpenCL extension is
/// empty, do nothing.
void setCurrentOpenCLExtensionForType(QualType T);
/// Set current OpenCL extensions for a declaration which
/// can only be used when these OpenCL extensions are enabled. If current
/// OpenCL extension is empty, do nothing.
void setCurrentOpenCLExtensionForDecl(Decl *FD);
bool isOpenCLDisabledDecl(Decl *FD);
/// Check if type \p T corresponding to declaration specifier \p DS
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
/// Check if declaration \p D used by expression \p E
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
//===--------------------------------------------------------------------===//
// OpenMP directives and clauses.
//
private:
void *VarDataSharingAttributesStack;
/// Number of nested '#pragma omp declare target' directives.
unsigned DeclareTargetNestingLevel = 0;
/// Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
ExprResult
VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
bool StrictlyPositive = true);
/// 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);
/// Checks if a type or a declaration is disabled due to the owning extension
/// being disabled, and emits diagnostic messages if it is disabled.
/// \param D type or declaration to be checked.
/// \param DiagLoc source location for the diagnostic message.
/// \param DiagInfo information to be emitted for the diagnostic message.
/// \param SrcRange source range of the declaration.
/// \param Map maps type or declaration to the extensions.
/// \param Selector selects diagnostic message: 0 for type and 1 for
/// declaration.
/// \return true if the type or declaration is disabled.
template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
MapT &Map, unsigned Selector = 0,
SourceRange SrcRange = SourceRange());
/// 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);
};
/// The current `omp begin/end declare variant` scopes.
SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
/// 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.
FunctionDecl *
ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S,
Declarator &D);
/// Register \p FD as specialization of \p BaseFD in the current `omp
/// begin/end declare variant` scope.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
FunctionDecl *FD, FunctionDecl *BaseFD);
public:
/// Can we exit a scope at the moment.
bool isInOpenMPDeclareVariantScope() {
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 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'.
OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
Decl *PrevDeclInScope = nullptr);
/// Build the mapper variable of '#pragma omp declare mapper'.
void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
Scope *S, QualType MapperType,
SourceLocation StartLoc,
DeclarationName VN);
/// Called at the end of '#pragma omp declare mapper'.
DeclGroupPtrTy
ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
ArrayRef<OMPClause *> ClauseList);
/// Called on the start of target region i.e. '#pragma omp declare target'.
bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
/// Called at the end of target region i.e. '#pragme omp end declare target'.
void ActOnFinishOpenMPDeclareTargetDirective();
/// Searches for the provided declaration name for OpenMP declare target
/// directive.
NamedDecl *
lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
NamedDeclSetType &SameDirectiveDecls);
/// 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 DeclareTargetNestingLevel > 0;
}
/// 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);
/// 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 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);
/// 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-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 'destroy' clause.
OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc,
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);
/// 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<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'from' clause.
OMPClause *ActOnOpenMPFromClause(
ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId, 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_RValue,
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 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,
AssignmentAction Action,
bool AllowExplicit,
ImplicitConversionSequence& ICS);
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_RValue,
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 CheckGNUVectorConditionalTypes(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 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 ¶mType);
// 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 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
virtual ~VerifyICEDiagnoser() { }
};
/// 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,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
unsigned DiagID,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result = nullptr);
/// 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;
/// Diagnostic builder for CUDA/OpenMP devices 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 DeviceDiagBuilder {
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
};
DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
FunctionDecl *Fn, Sema &S);
DeviceDiagBuilder(DeviceDiagBuilder &&D);
DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
~DeviceDiagBuilder();
/// 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 (DeviceDiagBuilder(...) << foo << bar)
/// return ExprError();
///
/// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
/// want to use these instead of creating a DeviceDiagBuilder yourself.
operator bool() const { return ImmediateDiag.hasValue(); }
template <typename T>
friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &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;
}
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<SemaDiagnosticBuilder> ImmediateDiag;
llvm::Optional<unsigned> PartialDiagId;
};
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as device code".
///
/// - If CurContext is a __host__ function, does not emit any diagnostics.
/// - 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.
DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as host code".
///
/// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder 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.
DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder 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.
DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
/// Check if the expression is allowed to be used in expressions for the
/// offloading devices.
void checkDeviceDecl(const 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);
/// 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);
/// Reports signatures for a call to CodeCompleteConsumer and returns the
/// preferred type for the current argument. Returned type can be null.
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,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto,
SourceLocation Loc);
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 CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum);
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 SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
bool SemaBuiltinVSX(CallExpr *TheCall);
bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
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 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);
// 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 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 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__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;
/// 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 DeviceDiagBuilder 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";
DeviceDiagBuilder 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;
};
} // 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.getRawEncoding());
}
static bool isEqual(const FunctionDeclAndLoc &LHS,
const FunctionDeclAndLoc &RHS) {
return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
}
};
} // namespace llvm
#endif
|
vednnLaunch.h | #pragma once
#include "vednn.h"
#ifdef VEDNN_USE_OPENMP
#include <omp.h>
#endif
#include <algorithm>
/** TODO: Also 2d parallelize Linear. Be careful, there are calls that require
* the OC to be a even number! */
//------------------------------------------------------------------------------
template<typename F>
inline vednnError_t vednn_launch_1d(const int cnt, F func) {
int rc = VEDNN_SUCCESS;
if(cnt == 1) {
return func(0, cnt);
} else {
#pragma omp parallel reduction(|:rc)
{
int nthreads = omp_get_num_threads();
int tcnt = (cnt + nthreads - 1) / nthreads;
int tx = omp_get_thread_num();
int min = tx * tcnt;
int max = std::min((tx+1) * tcnt, cnt);
if(min < max)
rc |= (int)func(min, max);
}
}
return (vednnError_t)rc;
}
//------------------------------------------------------------------------------
template<typename F>
inline vednnError_t vednn_launch_2d(const int x, const int y, F func) {
int rc = VEDNN_SUCCESS;
int cnt = x * y;
if(cnt == 1) {
return func(0, x, 0, y);
} else {
#pragma omp parallel reduction(|:rc)
{
int nthreads = omp_get_num_threads();
int tx = omp_get_thread_num();
if(x > (nthreads/2)) {
int xcnt = (x + nthreads - 1) / nthreads;
int min_x = tx * xcnt;
int max_x = std::min((tx+1) * xcnt, x);
if(min_x < max_x)
rc |= func(min_x, max_x, 0, y);
} else {
int xthreads = x;
int ythreads = nthreads / x;
int ty = tx / xthreads;
tx = tx % xthreads;
int min_x = tx % xthreads;
int max_x = min_x + 1;
int ycnt = (y + ythreads - 1) / ythreads;
int min_y = ty * ycnt;
int max_y = std::min((ty+1) * ycnt, y);
if(min_y < max_y)
rc |= func(min_x, max_x, min_y, max_y);
}
}
}
return (vednnError_t)rc;
}
//------------------------------------------------------------------------------
|
pr6.c | //Write an OpenMP program to show how thread private clause works.
#include <omp.h>
#include<stdio.h>
int a, b, i, tid;
float x;
#pragma omp threadprivate(a, x)
int main ()
{
/* Explicitly turn off dynamic threads */
omp_set_dynamic(0);
printf("1st Parallel Region:\n");
#pragma omp parallel private(b,tid)
{
tid = omp_get_thread_num();
a = tid;
b = tid;
x = 1.1 * tid +1.0;
printf("Thread %d: a,b,x= %d %d %f\n",tid,a,b,x);
} /* end of parallel section */
printf("************************************\n");
printf("Master thread doing serial work here\n");
printf("************************************\n");
printf("2nd Parallel Region:\n");
#pragma omp parallel private(tid)
{
tid = omp_get_thread_num();
printf("Thread %d: a,b,x= %d %d %f\n",tid,a,b,x);
} /* end of parallel section */
}
|
chadphys.h | #ifndef CHAD_PHYS_H
#define CHAD_PHYS_H
#include "3dMath.h"
typedef struct {
aabb shape; //c.d[3] is sphere radius.
//if it's zero or less, it's not a sphere, it's a box
mat4 localt; //Local Transform.
vec3 v; //velocity
vec3 a; //Body specific acceleration, combined with gravity
void* d; //User defined pointer.
f_ mass; //0 means kinematic, or static. Defaults to zero.
f_ bounciness; //default 0, put portion of displacement into velocity.
f_ airfriction; //default 1, multiplied by velocity every time timestep.
f_ friction; //default 0.1
} phys_body;
typedef struct{
vec3 g; //gravity
phys_body** bodies;
f_ ms; //max speed
int nbodies; //number of bodies
} phys_world;
static inline void initPhysBody(phys_body* body){
body->shape = (aabb){
.c=(vec4){.d[0] = 0,.d[1] = 0,.d[2] = 0,.d[3] = 0},
.e=(vec3){.d[0] = 0,.d[1] = 0,.d[2] = 0}
};
body->mass = 0;
body->bounciness = 0;
body->friction = 0.99; //The amount of coplanar velocity preserved in collisions.
body->airfriction = 1.0;
body->a = (vec3){.d[0] = 0,.d[1] = 0,.d[2] = 0};
body->localt = identitymat4();
body->d = NULL;
}
static inline mat4 getPhysBodyRenderTransform(phys_body* body){
return multm4(
translate(downv4(body->shape.c)),
body->localt
);
}
//Check for and, if necessary, resolve colliding bodies.
static inline void resolveBodies(phys_body* a, phys_body* b){
if(a->mass > 0 || b->mass > 0){ //Perform a preliminary check. Do we even have to do anything?
/*We must do shit*/
} else {return;}
//Optimized for branch prediction.
vec4 penvec = (vec4){
.d[0]=0,
.d[1]=0,
.d[2]=0,
.d[3]=0
};
//Check if the two bodies are colliding.
if(a->shape.c.d[3] > 0 && b->shape.c.d[3] > 0) //Both Spheres!
{
penvec = spherevsphere(a->shape.c, b->shape.c);
} else if(a->shape.c.d[3] <= 0 && b->shape.c.d[3] <= 0) //Both boxes!
{
penvec = boxvbox(a->shape,b->shape);
} else if (a->shape.c.d[3] > 0 && b->shape.c.d[3] <= 0) //a is a sphere, b is a box
{
penvec = spherevaabb(a->shape.c,b->shape);
} else if (a->shape.c.d[3] <= 0 && b->shape.c.d[3] > 0){ //a is a box, b is a sphere
penvec = spherevaabb(b->shape.c,a->shape);
penvec.d[0] *= -1;
penvec.d[1] *= -1;
penvec.d[2] *= -1;
}
#ifdef CHADPHYS_DEBUG
else {
puts("\nInvalid configuration. Error.\n");
}
#endif
if(penvec.d[3] <= 0) return; //No penetration detected, or invalid configuration.
vec3 penvecnormalized = scalev3(1.0/penvec.d[3], downv4(penvec)); //the penetration vector points into B...
f_ friction = a->friction * b->friction;
//We now have the penetration vector. There is a penetration.
//determine how much each should be displaced by.
//The penvec points INTO A and is of length penvec.d[3]
f_ bdisplacefactor = a->mass / (a->mass + b->mass);
f_ adisplacefactor = b->mass / (a->mass + b->mass);
vec3 comvel;
if(!(a->mass > 0)) {
adisplacefactor = 0; bdisplacefactor = 1;comvel = (vec3){{0,0,0}};
}else if(!(b->mass > 0)) {
bdisplacefactor = 0; adisplacefactor = 1;comvel = (vec3){{0,0,0}};
}else{
comvel = addv3( scalev3(bdisplacefactor, a->v), scalev3(adisplacefactor, b->v));
}
if(a->mass > 0){
vec4 displacea = scalev4(-adisplacefactor, penvec);
vec3 a_relvel = subv3(a->v, comvel);
vec3 a_planarvel = subv3(a_relvel,
scalev3(
dotv3(a_relvel, penvecnormalized),
penvecnormalized
)
);
a->shape.c.d[0] += displacea.d[0];
a->shape.c.d[1] += displacea.d[1];
a->shape.c.d[2] += displacea.d[2];
a->v = addv3( comvel, scalev3(1-friction, a_planarvel) ); //The center of mass velocity, plus a portion of coplanar velocity.
a->v = addv3(a->v, scalev3( a->bounciness, downv4(displacea) ) );
}
if(b->mass > 0){
vec4 displaceb = scalev4(bdisplacefactor, penvec);
vec3 b_relvel = subv3(b->v, comvel);
vec3 b_planarvel = subv3(b_relvel, //brelvel - portion of brelvel in the direction of penvecnormalized
scalev3(
dotv3(b_relvel, penvecnormalized), //the component in that direction
penvecnormalized //that direction
)
);
#pragma omp simd
for(int i = 0; i < 3; i++)
b->shape.c.d[i] += displaceb.d[i];
b->v = addv3(comvel, scalev3(1-friction, b_planarvel) ); //The center of mass velocity, plus a portion of coplanar velocity.
b->v = addv3(b->v, scalev3( b->bounciness, downv4(displaceb) ) );
}
}
static inline void stepPhysWorld(phys_world* world, const int collisioniter){
for(int i = 0; i < world->nbodies; i++)
if(world->bodies[i] && world->bodies[i]->mass > 0){
phys_body* body = world->bodies[i];
vec3 bodypos = addv3(downv4(body->shape.c),body->v);
body->shape.c.d[0] = bodypos.d[0];
body->shape.c.d[1] = bodypos.d[1];
body->shape.c.d[2] = bodypos.d[2];
body->v = addv3(body->v, body->a);
body->v = addv3(body->v, world->g);
}
//Resolve collisions (if any)
for(int iter = 0; iter < collisioniter; iter++)
for(int i = 0; i < (int)(world->nbodies-1); i++)
if(world->bodies[i])
for(int j = i+1; j < (int)world->nbodies; j++)
if(world->bodies[j])
resolveBodies(world->bodies[i], world->bodies[j]);
}
#endif
|
lbfgsbsolver.h | // CppNumericalSolver
// based on:
// L-BFGS-B: A LIMITED MEMORY ALGORITHM FOR BOUND CONSTRAINED OPTIMIZATION
// Richard H. Byrd, Peihuang Lu, Jorge Nocedal and Ciyou Zhu
#include <iostream>
#include <list>
#include <Eigen/LU>
#include "isolver.h"
#include "../boundedproblem.h"
#include "../linesearch/morethuente.h"
#ifndef LBFGSBSOLVER_H
#define LBFGSBSOLVER_H
namespace cppoptlib {
template<typename TProblem>
class LbfgsbSolver : public ISolver<TProblem, 1> {
public:
using Superclass = ISolver<TProblem, 1>;
using typename Superclass::Scalar;
using typename Superclass::TVector;
using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
using VariableTVector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
protected:
// workspace matrices
MatrixType W, M;
Scalar theta;
int DIM;
int m_historySize = 5;
/**
* @brief sort pairs (k,v) according v ascending
* @details [long description]
*
* @param v [description]
* @return [description]
*/
std::vector<int> sort_indexes(const std::vector< std::pair<int, Scalar> > &v) {
std::vector<int> idx(v.size());
for (size_t i = 0; i != idx.size(); ++i)
idx[i] = v[i].first;
sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {
return v[i1].second < v[i2].second;
});
return idx;
}
void clampToBound(const TProblem &problem, TVector &x) {
for (int r = 0; r < x.rows(); ++r)
{
if(x(r) < problem.lowerBound()(r))
x(r) = problem.lowerBound()(r);
else if (x(r) > problem.upperBound()(r))
x(r) = problem.upperBound()(r);
}
}
/**
* @brief Algorithm CP: Computation of the generalized Cauchy point
* @details PAGE 8
*
* @param c [description]
*/
void getGeneralizedCauchyPoint(const TProblem &problem, const TVector &x, const TVector &g, TVector &x_cauchy, VariableTVector &c) {
const int DIM = x.rows();
// Given x,l,u,g, and B = \theta I-WMW
// {all t_i} = { (idx,value), ... }
// TODO: use "std::set" ?
std::vector<std::pair<int, Scalar> > SetOfT;
// the feasible set is implicitly given by "SetOfT - {t_i==0}"
TVector d = -g;
// n operations
for (int j = 0; j < DIM; j++) {
if (g(j) == 0) {
SetOfT.push_back(std::make_pair(j, std::numeric_limits<Scalar>::max()));
} else {
Scalar tmp = 0;
if (g(j) < 0) {
tmp = (x(j) - problem.upperBound()(j)) / g(j);
} else {
tmp = (x(j) - problem.lowerBound()(j)) / g(j);
}
SetOfT.push_back(std::make_pair(j, tmp));
if (tmp == 0) d(j) = 0;
}
}
// sortedindices [1,0,2] means the minimal element is on the 1-st entry
std::vector<int> sortedIndices = sort_indexes(SetOfT);
x_cauchy = x;
// Initialize
// p := W^Scalar*p
VariableTVector p = (W.transpose() * d); // (2mn operations)
// c := 0
c = VariableTVector::Zero(W.cols());
// f' := g^Scalar*d = -d^Td
Scalar f_prime = -d.dot(d); // (n operations)
// f'' := \theta*d^Scalar*d-d^Scalar*W*M*W^Scalar*d = -\theta*f' - p^Scalar*M*p
Scalar f_doubleprime = (Scalar)(-1.0 * theta) * f_prime - p.dot(M * p); // (O(m^2) operations)
f_doubleprime = std::max<Scalar>(std::numeric_limits<Scalar>::epsilon(), f_doubleprime);
Scalar f_dp_orig = f_doubleprime;
// \delta t_min := -f'/f''
Scalar dt_min = -f_prime / f_doubleprime;
// t_old := 0
Scalar t_old = 0;
// b := argmin {t_i , t_i >0}
int i = 0;
for (int j = 0; j < DIM; j++) {
i = j;
if (SetOfT[sortedIndices[j]].second > 0)
break;
}
int b = sortedIndices[i];
// see below
// t := min{t_i : i in F}
Scalar t = SetOfT[b].second;
// \delta Scalar := t - 0
Scalar dt = t ;
// examination of subsequent segments
while ((dt_min >= dt) && (i < DIM)) {
if (d(b) > 0)
x_cauchy(b) = problem.upperBound()(b);
else if (d(b) < 0)
x_cauchy(b) = problem.lowerBound()(b);
// z_b = x_p^{cp} - x_b
Scalar zb = x_cauchy(b) - x(b);
// c := c +\delta t*p
c += dt * p;
// cache
VariableTVector wbt = W.row(b);
f_prime += dt * f_doubleprime + (Scalar) g(b) * g(b) + (Scalar) theta * g(b) * zb - (Scalar) g(b) *
wbt.transpose() * (M * c);
f_doubleprime += (Scalar) - 1.0 * theta * g(b) * g(b)
- (Scalar) 2.0 * (g(b) * (wbt.dot(M * p)))
- (Scalar) g(b) * g(b) * wbt.transpose() * (M * wbt);
f_doubleprime = std::max<Scalar>(std::numeric_limits<Scalar>::epsilon() * f_dp_orig, f_doubleprime);
p += g(b) * wbt.transpose();
d(b) = 0;
dt_min = -f_prime / f_doubleprime;
t_old = t;
++i;
if (i < DIM) {
b = sortedIndices[i];
t = SetOfT[b].second;
dt = t - t_old;
}
}
dt_min = std::max<Scalar>(dt_min, (Scalar)0.0);
t_old += dt_min;
#pragma omp parallel for
for (int ii = i; ii < x_cauchy.rows(); ii++) {
x_cauchy(sortedIndices[ii]) = x(sortedIndices[ii]) + t_old * d(sortedIndices[ii]);
}
c += dt_min * p;
}
/**
* @brief find alpha* = max {a : a <= 1 and l_i-xc_i <= a*d_i <= u_i-xc_i}
* @details [long description]
*
* @param FreeVariables [description]
* @return [description]
*/
Scalar findAlpha(const TProblem &problem, TVector &x_cp, VariableTVector &du, std::vector<int> &FreeVariables) {
Scalar alphastar = 1;
const unsigned int n = FreeVariables.size();
assert(du.rows() == n);
for (unsigned int i = 0; i < n; i++) {
if (du(i) > 0) {
alphastar = std::min<Scalar>(alphastar, (problem.upperBound()(FreeVariables[i]) - x_cp(FreeVariables[i])) / du(i));
} else {
alphastar = std::min<Scalar>(alphastar, (problem.lowerBound()(FreeVariables[i]) - x_cp(FreeVariables[i])) / du(i));
}
}
return alphastar;
}
/**
* @brief solving unbounded probelm
* @details [long description]
*
* @param SubspaceMin [description]
*/
void SubspaceMinimization(const TProblem &problem, TVector &x_cauchy, TVector &x, VariableTVector &c, TVector &g,
TVector &SubspaceMin) {
Scalar theta_inverse = 1 / theta;
std::vector<int> FreeVariablesIndex;
for (int i = 0; i < x_cauchy.rows(); i++) {
if ((x_cauchy(i) != problem.upperBound()(i)) && (x_cauchy(i) != problem.lowerBound()(i))) {
FreeVariablesIndex.push_back(i);
}
}
const int FreeVarCount = FreeVariablesIndex.size();
MatrixType WZ = MatrixType::Zero(W.cols(), FreeVarCount);
for (int i = 0; i < FreeVarCount; i++)
WZ.col(i) = W.row(FreeVariablesIndex[i]);
TVector rr = (g + theta * (x_cauchy - x) - W * (M * c));
// r=r(FreeVariables);
MatrixType r = MatrixType::Zero(FreeVarCount, 1);
for (int i = 0; i < FreeVarCount; i++)
r.row(i) = rr.row(FreeVariablesIndex[i]);
// STEP 2: "v = w^T*Z*r" and STEP 3: "v = M*v"
VariableTVector v = M * (WZ * r);
// STEP 4: N = 1/theta*W^T*Z*(W^T*Z)^T
MatrixType N = theta_inverse * WZ * WZ.transpose();
// N = I - MN
N = MatrixType::Identity(N.rows(), N.rows()) - M * N;
// STEP: 5
// v = N^{-1}*v
if (v.size() > 0)
v = N.lu().solve(v);
// STEP: 6
// HERE IS A MISTAKE IN THE ORIGINAL PAPER!
VariableTVector du = -theta_inverse * r - theta_inverse * theta_inverse * WZ.transpose() * v;
// STEP: 7
Scalar alpha_star = findAlpha(problem, x_cauchy, du, FreeVariablesIndex);
// STEP: 8
VariableTVector dStar = alpha_star * du;
SubspaceMin = x_cauchy;
for (int i = 0; i < FreeVarCount; i++) {
SubspaceMin(FreeVariablesIndex[i]) = SubspaceMin(FreeVariablesIndex[i]) + dStar(i);
}
}
public:
void setHistorySize(const int hs) { m_historySize = hs; }
void minimize(TProblem &problem, TVector &x0) {
if(!problem.isValid(x0))
std::cerr << "start with invalid x0" << std::endl;
DIM = x0.rows();
theta = 1.0;
W = MatrixType::Zero(DIM, 0);
M = MatrixType::Zero(0, 0);
MatrixType yHistory = MatrixType::Zero(DIM, 0);
MatrixType sHistory = MatrixType::Zero(DIM, 0);
TVector x = x0, g = x0;
Scalar f = problem.value(x);
problem.gradient(x, g);
// conv. crit.
auto noConvergence =
[&](TVector &x, TVector &g)->bool {
return (((x - g).cwiseMax(problem.lowerBound()).cwiseMin(problem.upperBound()) - x).template lpNorm<Eigen::Infinity>() >= 1e-4);
};
this->m_current.reset();
this->m_status = Status::Continue;
while (problem.callback(this->m_current, x) && noConvergence(x, g) && (this->m_status == Status::Continue)) {
Scalar f_old = f;
TVector x_old = x;
TVector g_old = g;
// STEP 2: compute the cauchy point
TVector CauchyPoint = TVector::Zero(DIM);
VariableTVector c = VariableTVector::Zero(W.cols());
getGeneralizedCauchyPoint(problem, x, g, CauchyPoint, c);
// STEP 3: compute a search direction d_k by the primal method for the sub-problem
TVector SubspaceMin;
SubspaceMinimization(problem, CauchyPoint, x, c, g, SubspaceMin);
// STEP 4: perform linesearch and STEP 5: compute gradient
Scalar alpha_init = 1.0;
const Scalar rate = MoreThuente<TProblem, 1>::linesearch(x, SubspaceMin-x , problem, alpha_init);
// update current guess and function information
x = x - rate*(x-SubspaceMin);
// if current solution is out of bound, we clip it
clampToBound(problem, x);
f = problem.value(x);
problem.gradient(x, g);
// prepare for next iteration
TVector newY = g - g_old;
TVector newS = x - x_old;
// STEP 6:
Scalar test = newS.dot(newY);
test = (test < 0) ? -1.0 * test : test;
if (test > 1e-7 * newY.squaredNorm()) {
if (yHistory.cols() < m_historySize) {
yHistory.conservativeResize(DIM, yHistory.cols() + 1);
sHistory.conservativeResize(DIM, sHistory.cols() + 1);
} else {
yHistory.leftCols(m_historySize - 1) = yHistory.rightCols(m_historySize - 1).eval();
sHistory.leftCols(m_historySize - 1) = sHistory.rightCols(m_historySize - 1).eval();
}
yHistory.rightCols(1) = newY;
sHistory.rightCols(1) = newS;
// STEP 7:
theta = (Scalar)(newY.transpose() * newY) / (newY.transpose() * newS);
W = MatrixType::Zero(yHistory.rows(), yHistory.cols() + sHistory.cols());
W << yHistory, (theta * sHistory);
MatrixType A = sHistory.transpose() * yHistory;
MatrixType L = A.template triangularView<Eigen::StrictlyLower>();
MatrixType MM(A.rows() + L.rows(), A.rows() + L.cols());
MatrixType D = -1 * A.diagonal().asDiagonal();
MM << D, L.transpose(), L, ((sHistory.transpose() * sHistory) * theta);
M = MM.inverse();
}
if (fabs(f_old - f) < 1e-8) {
// successive function values too similar
break;
}
++this->m_current.iterations;
this->m_current.gradNorm = g.norm();
this->m_status = checkConvergence(this->m_stop, this->m_current);
}
x0 = x;
if (this->m_debug > DebugLevel::None) {
std::cout << "Stop status was: " << this->m_status << std::endl;
std::cout << "Stop criteria were: " << std::endl << this->m_stop << std::endl;
std::cout << "Current values are: " << std::endl << this->m_current << std::endl;
}
}
};
}
/* namespace cppoptlib */
#endif /* LBFGSBSOLVER_H_ */
|
GB_bitmap_assign_A_whole_template.c | //------------------------------------------------------------------------------
// GB_bitmap_assign_A_whole_template: traverse A for bitmap assignment into C
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// This template traverses over all the entries of the matrix A and operates on
// the corresponding entry in C(i,j), using the GB_AIJ_WORK macro. A can be
// hypersparse or sparse, not bitmap or full. It is not a scalar.
{
//--------------------------------------------------------------------------
// matrix assignment: slice the entries of A for each task
//--------------------------------------------------------------------------
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
const int64_t avlen = A->vlen ;
int A_ntasks, A_nthreads ;
GB_SLICE_MATRIX (A, 8, chunk) ;
//--------------------------------------------------------------------------
// traverse of the entries of the matrix A
//--------------------------------------------------------------------------
int tid ;
#pragma omp parallel for num_threads(A_nthreads) schedule(dynamic,1) \
reduction(+:cnvals)
for (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] ;
int64_t task_cnvals = 0 ;
//----------------------------------------------------------------------
// traverse over A (:,kfirst:klast)
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// find the part of A(:,k) for this task
//------------------------------------------------------------------
int64_t j = GBH (Ah, k) ;
int64_t pA_start, pA_end ;
GB_get_pA (&pA_start, &pA_end, tid, k, kfirst,
klast, pstart_Aslice, Ap, avlen) ;
//------------------------------------------------------------------
// traverse over A(:,j), the kth vector of A
//------------------------------------------------------------------
int64_t pC0 = j * cvlen ; // first entry in C(:,j)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
int64_t i = Ai [pA] ;
int64_t pC = i + pC0 ;
// operate on C(i,j) at pC, and A(i,j) at pA. The mask
// can be accessed at pC if M is bitmap or full. A has any
// sparsity format so only A(i,j) can be accessed at pA.
GB_AIJ_WORK (pC, pA) ;
}
}
cnvals += task_cnvals ;
}
//--------------------------------------------------------------------------
// free workspace
//--------------------------------------------------------------------------
GB_WERK_POP (A_ek_slicing, int64_t) ;
}
|
opencl_odf_fmt_plug.c | /* Modified by Dhiru Kholia <dhiru at openwall.com> for ODF Blowfish 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_odf;
#elif FMT_REGISTERS_H
john_register_one(&fmt_opencl_odf);
#else
#include <stdint.h>
#include <string.h>
#include <openssl/blowfish.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "arch.h"
#include "sha.h"
#include "aes.h"
#include "formats.h"
#include "common.h"
#include "misc.h"
#include "options.h"
#include "common.h"
#include "formats.h"
#include "common-opencl.h"
#define FORMAT_LABEL "ODF-opencl"
#define FORMAT_NAME ""
#define FORMAT_TAG "$odf$*"
#define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1)
#define ALGORITHM_NAME "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(odf_cpu_salt)
#define BINARY_ALIGN MEM_ALIGN_WORD
#define SALT_ALIGN 4
typedef struct {
uint32_t length;
uint8_t v[20]; // hash of password
} odf_password;
typedef struct {
uint32_t v[32/4];
} odf_hash;
typedef struct {
uint32_t iterations;
uint32_t outlen;
uint32_t skip_bytes;
uint8_t length;
uint8_t salt[64];
} odf_salt;
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static uint32_t (*crypt_out)[32 / sizeof(uint32_t)];
typedef struct {
int cipher_type;
int checksum_type;
int iterations;
int key_size;
int iv_length;
int salt_length;
int content_length;
unsigned char iv[16];
unsigned char salt[32];
unsigned char content[1024];
} odf_cpu_salt;
static odf_cpu_salt *cur_salt;
static struct fmt_tests odf_tests[] = {
{"$odf$*0*0*1024*16*df6c10f64d191a841812af53874b636d014ce3fe*8*07e28aff39d2660e*16*b124be9f3346fb77e0ebcc3bb80028f8*0*2276a1077f6a2a027bd565ce89824d6a20086e378876be05c4b8e3796a460e828c9803a692caf7a53492c220d1d7ecbf4e2d336c7abf5a7672acc804ca267318252cbc13676616d1fde38820f9fbeef1360067d9de096ba8c1032ae947bde1d0fedaf37b6020663d49faf36b7c095c5b9aae11c8fc2be74148f008edbdbb180b44028ad8259f1215b483542bf3027f56dee5f962448333b30f88e6ae4790b60d24abb286edff9adee831a4b3351fc47259043f0d683d7a25be7e47aff3aedca140005d866e218c8efcca32093c19bbece50bd96656d0f94a712d3c60d1e5342db86482fc73f05faf513ca0b137378126597b95986c372b412c953e97011259aab0839fe453c756559497a28ba88dce009e1e7980436131029d38e56a34f608e6471970d9959068808c898608024db9eb394c4feae7a364ea9272ec4ea2315a9f0407a4b27d5e49a8ab1e3ddce5c84927d5aecd7e68e4437a820ea8743c6b5b4e2abbb47b0001e2f77ceac4603e8774e4ccbc1adde794428c11ae4a7492727b620334302e63f72b0c06c1cf83800366916ee8295176819272d557863a831ee0a576841191482959aad69095831fa1d64e3e0e6f6c6a751bcdadf0fbaa27a17458709f708c04587cb208984c9525da6786e0e5aabefe30ad1dbbef66e85ce9d6dbe456fd85e4135de5cf16d9455976d7ca8de7b1b530661c74c0fae90c0fff1a2b5fcdfab19fcff75fadcec445ed8af6ab5babf1463e08458918be8045083de6db988c37e4be582cfac5cdf741d1f0322fb2902665c7ff347813348109e5d442e91fcb010c28f042da481e807084fcb4759b40ccf2cae77bad00cdfbfba4acf36aa1f74c30a315e3d7f1ca522b6306e8903352aafa51dc523d582d418934398d5eb88120e3656bfb640a239db507b285302a86855ea850ddc9af72fc62dc79336c9bc29ee8314c65adb0574e9c701d73d7fa977edd1d52a1ff2da5b8b94e1a0fdd01ffcc6583758f0a1f51750e45f12b58c6d38b140e5676cf3474224520ef7c52ca5e634f85456651f3d6f43d016ed7cc5da54ea640a3bc50c2b9d3dea8f93c0340d66ccd06efc5ae002108c33cf3a470c4a50f6a6ca2f11b8ad15511688c282b94ba6f1c332e239d10946dc46f763f08d12cb9edc1e79c0e07f7151f548e6d7d20ec13b52d911bf980cac60694e192651403c9a69abea045190e847be093fc9ba43fec55b32f77f5796ddca25b441f259d5c51e06df6c6588c6414899481ba9e06bcebec58f82ff3021b09c6beae13a5d22bc94870f72ab813d0c0be01d91f3d075192e7a5de765599d72244757d09539529a8347e077a36678166e5ed9f73a5aad2e147d8154095c397e3e5e4ba1987ca64c1301a0c6c3e438097ede9b701a105ec38fcb54abb31b367c7740cd9ac459e561094a34f01acee555e60267157e6", "test"},
{"$odf$*0*0*1024*16*43d3dbd907785c4fa5282a2e73a5914db3372505*8*b3d676d4519e6b5a*16*34e3f7fdfa67fb0078360b0df4011270*0*7eff7a7abf1e6b0c4a9fafe6bdcfcfeaa5b1886592a52bd255f1b51096973d6fa50d792c695f3ef82c6232ae7f89c771e27db658258ad029e82415962b270d2c859b0a3efb231a0519ec1c807082638a9fad7537dec22e20d59f2bfadfa84dd941d59dd07678f9e60ffcc1eb27d8a2ae47b616618e5e80e27309cd027724355bf78b03d5432499c1d2a91d9c67155b7f49e61bd8405e75420d0cfb9e64b238623a9d8ceb47a3fdb5e7495439bb96e79882b850a0c8d3c0fbef5e6d425ae359172b9a82ec0566c3578a9f07b86a70d75b5ad339569c1c8f588143948d63bdf88d6ed2e751ac07f25ecc5778dc06247e5a9edca869ee3335e5dae351666a618d00ec05a35bc73d330bef12a46fb53b2ff96e1b2919af4e692730b9c9664aca761df10d6cf55396c4d4c268e6e96c96515c527c8fe2716ac7a9f016941aa46e6b03e8a5069c29ec8e8614b7da3e2e154a77510393051a0b693ae40da6afb5712a4ce4ac0ebacda1f45bdccc8a7b21e153d1471665cae3205fbfa00129bf00c06777bfecba2c43a1481a00111b4f0bd30c2378bd1e2e219700406411c6f897a3dfa51b31613cb241d56b68f3c241428783b353be26fa8b2df68ca215d1cf892c10fdef94faf2381a13f8cb2bce1a7dbb7522ef0b2a83e5a96ca66417fd2928784054e80d74515c1582ad356dd865837b5ea90674a30286a72a715f621c9226f19a321b413543fbbdb7cd9d1f99668b19951304e7267554d87992fbf9a96116601d0cee9e23cb22ba474c3f721434400cacf15bae05bbe9fa17f69967d03689c48a26fa57ff9676c96767762f2661b6c8f8afa4f96f989086aa02b6f8d039c6f4d158cc33a56cbf77640fb5087b2d5a5251692bb9255d0ae8148c7157c40031fdb0ea90d5fab546a7e1e1c15bd6a27f3716776c8a3fdbdd4f34c19fef22c36117c124876606b1395bf96266d647aaf5208eefd729a42a4efe42367475315a979fb74dcb9cd30917a811ed8283f2b111bb5a5d2b0f5589b3652f17d23e352e1494f231027bb93209e3c6a0388f8b2214577dca8aa9d705758aa334d6947491488770ed8066f692f8922ff0d852c2d0f965ab3d8a13c6de0ef3cff5a15ee7b64f9b1003817f0cb919ad021d5f3b0b5c1ad58db22e8fbd63abfb40e61065bad008cdffbbe3c563780a548f4515df5c935d9aa2a3033bc8a4011c9c173a0366c9b7b07f2a27de0e55373fb4b0c7726997be6f410a2ee5980393ea005516e89538be796131e450403420d72cdbd75475fd11c50efce5eb340d55d2dd0a67ca45ddb53aa582a2ec56b46452e26a505bf730998513837c96a121e4ad13af5030392ff7fb660955e03f65894733862f2367d529f0e8cdb73272b9ce01491747cb3e1a22f5c85ab6d40ddd35d15b9d46d73600e0971da90f93cb0e9be357c4f1227fbf5b123e5b", "jumper9"},
{"$odf$*0*0*1024*16*4ec0370ab589f943131240e407a35b58a341e052*8*19cadc01889f78c0*16*dcfcb8baccda277764e4e99833ab9640*0*a7bd859d68298fbdc36b6b51eb06f7055befe08f76ca9833c6e298db8ed971bfd1315065a19e1b31b8a93624757a2583816f35d6f251ff7943be626b3dc72f0b320c9ce5d80b7cc676aa02e6a4996abd752da573ecc339d2c80a2c8bfc28a9f4ceea51c2969adf20c8762b2ee0b1835bbd31bd90d5a638cfe523a596ea95feca64ae20010ad9957a724143e25a875f3cec3cedb4df1c16ac82b46b35db269da98270c813acd5e55a2c138306decdf96b1c1079d9cfd3704d519fbc5a4a547ba5286a7e80dc434f1bf34260433cbb79c4bcbb2a5bfc5a6c2430944ef2e34e7b9c76b21a97003c1fa85f6e9c4ed984108a7d301afe4a8f6625502a4bf17b24e009717c711571da2d6acd25868892bb9e29a77da8018222cd57c91d9aad96c954355e50a4760f08aa1f1b4257f7eb1a235c9234e8fc4ed97e8ad3e5d7d128807b726a4eb0038246d8580397c0ff5873d34b5a688a4a931be7c5737e5ada3e830b02d3efb075e338d71be55751a765a21d560933812856986a4d0d0a6d4954c50631fa3dff8565057149c4c4951858be4d5dca8e492093cfd88b56a19a161e7595e2e98764e91eb51c5289dc4efa65c7b207c517e269e3c699373fe1bf177c5d641cf2cfa4bd2afe8bff53a98b2d64bedc5a2e2f2973416c66791cf012696a0e95f7a4dadb86f925fc1943cb2b75fb3eda30f7779edff7cce95ae6f0f7b45ac207a4de4ec012a3654103136e11eb496276647d5e8f6e1659951fc7ef78d60e9430027e826f2aaab7c93ef58a5af47b92cec2f17903a26e2cc5d8d09b1db55e568bfb23a6b6b46125daf71a2f3a708676101d1b657cd38e81deb74d5d877b3321349cd667c29359b45b82218ad96f6c805ac3439fc63f0c91d66da36bae3f176c23b45b8ca1945fb4a4cea5c4a7b0f6ffd547614e7016f94d3e7889ccac868578ea779cd7e6b015aafd296dd5e2da2aa7e2f2af2ce6605f53613f069194dff35ffb9a2ebb30e011c26f669ededa2c91ffb06fedc44cf23f35d7d2716abcd50a8f561721d613d8f2c689ac245a5ac084fa86c72bbe80da7d508e63d891db528fa9e8f0d608034cd97dfde70f739857672e2d70070e850c3a6521067c1774244b86cca835ca8ff1748516e694ea2b5b42555f0df9cb9ec78825c351df51a76b6fe23b58ab3e87ba94ffbb98c9fa9d50c0c282ed0e506bcad24c02d8b625b4bdac822a9e5c911d095c5e4d3bf03448add978e0e7fab7f8a7008568f01a4f06f155223086bdcfe6879e76f199afb9caeadebaa9ec4ec8120f4ccfc4f5f7d7e3cc4dd0cba4d11546d8540030769c4b6d54abdd51fa1f30da642e5ff5c35d3e711c8931ff79e9f256ac6416e99943b0000bf32a5efdd5cf1cd668a62381febe959ca472be9c1a9bade59dbba07eb035ddb1e64ae2923bd276deed788db7600d776f49339215", "RickRoll"},
{"$odf$*0*0*1024*16*399a33262bbef99543bae29a6bb069c36e3a8f1b*8*6b721193b04fa933*16*99a6342ca7221c81890035dc5033c16f*0*ef8692296b67a8a77344e87b6193dc0a370b115d9e8c85e901c1a19d03ee2a34b7bf989bf9c2edab61022ea49f2a3ce5a6c807af374afd21b52ccbd0aa13784c73d2c8feda1fe0c8ebbb94e46e32904d95d1f135759e2733c2bd30b8cb0050c1cb8a2336c1151c498b9609547e96243aed9473e0901b55137ed78e2c6057e5826cfbfb94b0d77cb12b1fb6ac2752ea71c9c05cdb6a2f3d9611cb24f6e23065b408601518e3182ba1b8cef4cfcdf6ceecb2f33267cf733d3da715562e6977015b2b6423fb416781a1b6a67252eec46cda2741163f86273a68cd241a06263fdd8fc25f1c30fd4655724cc3e5c3d8f3e84abf446dd545155e440991c5fa613b7c18bd0dabd1ad45beb508cfb2b08d4337179cba63df5095b3d640eadbd72ca07f5c908241caf384ca268355c0d13471c241ea5569a5d04a9e3505883eb1c359099c1578e4bc33a73ba74ceb4a0520e0712e3c88582549a668a9c11b8680368cfbc3c5ec02663ddd97963d9dacefed89912ffa9cd945a8634a653296163bb873f3afd1d02449494fab168e7f652230c16d35853df1164219c04c4bd17954b85eb1939d87412eeeb2a039a8bb087178c03a9a40165a28a985e8bc443071b3764d846d342ca2073223f9809fe2ee3a1dfa65b9d897877ebb33a48a760c8fb32062b51a96421256a94896e93b41f559fdec7743680a8deacff9132d6129574d1a62be94308b195d06a275947a1455600030468dde53639fd239a8ab074ec1c7f661f2c9e8d60d6e0e743d351017d5c3d3be21b67d05310d0c5f3fd670acd95ca24f91b0d84d761d15259848f736ff08610e300c31b242f6d24ac2418cdd1fe0248f8a2a2f5775c08e5571c8d25d65ff573cc403ea9cad3bafd56c166fbcec9e64909df3c6ec8095088a8992493b7180c4dbb4053dcb55d9c5f46d728a97ae4ec7ac4b5941bcc3b64a4af31f7dc673e6715a52c9cdbe23dc21e51784f8314c019fc90e8612fcffe01d026fd9e15d1474e73dedf1d3830da81320097be6953173e4293372b5e5a8ecc49ac8b1a658cff16ffa04a8c1728d02ab67694170f10bc9030939ff6df3f901faa019d9b9fd2ba23e89eb0bbaf7a69a2272ee1df0403e6435aee147da217e8bf4c1ee5c53eb83aac1b3f8772d5cd2a2686f312ac4f4f2b0733593e28305a550dbbd18d3405a464ff20e0d9364cfe49b82a97ef7303aec92004a3476cf9ad012eaaf10fd07d3823e1b6871e82113ecfe4392854de9ab21ab1e33ce93d1abb07018007f50d641c8eb85b28fd335fd2281745772c98f8f0bba3f4d40ba602545ef8a0db3062f02d7ee5f49b42cbe19c0c2124952f98c49aff6927110314e54fe8d47a10f13d2d4055c1f3f2d679d4043c9b2f68b2220b6c6c738f6402c01d000c9394c8ed27e70c7ee6108d3e7e809777bab9be30b33a3fb83271cbf3b", "WhoCanItBeNow"},
{NULL}
};
static cl_int cl_error;
static odf_password *inbuffer;
static odf_hash *outbuffer;
static odf_salt currentsalt;
static cl_mem mem_in, mem_out, mem_setting;
static struct fmt_main *self;
size_t insize, outsize, settingsize, cracked_size;
#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(odf_password) * gws;
outsize = sizeof(odf_hash) * gws;
settingsize = sizeof(odf_salt);
cracked_size = sizeof(*crypt_out) * gws;
inbuffer = mem_calloc(1, insize);
outbuffer = mem_alloc(outsize);
saved_key = mem_calloc(gws, sizeof(*saved_key));
crypt_out = mem_calloc(1, cracked_size);
/// 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(odf_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) {
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;
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) != res) // Hmm. res==16, length of p == 40??? Not sure about this one.
// goto err;
if (!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* iv length */
goto err;
res = atoi(p);
if (res > 16)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* iv */
goto err;
if (hexlenl(p, &extra) != res * 2 || extra)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* salt length */
goto err;
res = atoi(p);
if (res > 32)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* salt */
goto err;
if (hexlenl(p, &extra) != res * 2 || extra)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* something */
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* content */
goto err;
res = strlen(p);
if (res > 2048 || res & 1)
goto err;
if (!ishexlc(p))
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 odf_cpu_salt cs;
ctcopy += FORMAT_TAG_LEN; /* skip over "$odf$*" */
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);
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, "*");
p = strtokm(NULL, "*");
memset(cs.content, 0, sizeof(cs.content));
for (i = 0; p[i * 2] && i < 1024; i++)
cs.content[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
cs.content_length = i;
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 "$odf$*" */
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 = (odf_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, ¤tsalt, 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, (unsigned char*)outbuffer[index].v);
BF_cfb64_encrypt(cur_salt->content, output, cur_salt->content_length, &bf_key, ivec, &bf_ivec_pos, 0);
SHA1_Init(&ctx);
SHA1_Update(&ctx, output, cur_salt->content_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;
}
struct fmt_main fmt_opencl_odf = {
{
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 | FMT_HUGE_INPUT,
{ NULL },
{ FORMAT_TAG },
odf_tests
}, {
init,
done,
reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
#endif /* HAVE_OPENCL */
|
bn_layer.c | #include "bn_layer.h"
bn_layer *bn_alloc(int in_channels, int in_spatial) {
bn_layer *layer = aalloc(sizeof(*layer));
layer->in_channels = in_channels;
layer->in_spatial = in_spatial;
layer->gamma = matrix_alloc(1, layer->in_channels);
layer->beta = matrix_alloc(1, layer->in_channels);
layer->run_var = matrix_alloc(1, layer->in_channels);
layer->run_mean = matrix_alloc(1, layer->in_channels);
#pragma omp parallel for
for (int i = 0; i < in_channels; i++) {
layer->gamma->data[i] = 1.0f;
}
layer->variance = layer->out_cache = NULL;
return layer;
}
static void clear_cache(bn_layer *layer) {
matrix_free(layer->variance);
matrix_free(layer->out_cache);
}
void bn_free(bn_layer *layer) {
matrix_free(layer->gamma);
matrix_free(layer->beta);
matrix_free(layer->run_mean);
matrix_free(layer->run_var);
clear_cache(layer);
free(layer);
}
static void bn_update_status(bn_layer *layer, matrix *mean, matrix *variance) {
const float momentum = 0.99f;
const float nmomentum = 1.0f - momentum;
#pragma omp parallel for
for (int i = 0; i < layer->in_channels; i++) {
layer->run_mean->data[i] = (momentum * layer->run_mean->data[i]) + (nmomentum * mean->data[i]);
layer->run_var->data[i] = (momentum * layer->run_var->data[i]) + (nmomentum * variance->data[i]);
}
}
matrix* bn_forward(bn_layer *layer, matrix *input, bool training) {
clear_cache(layer);
if (training == true) {
matrix *_mean;
_mean = mean(input, layer->in_spatial, layer->in_channels);
layer->variance = variance(input, _mean, layer->in_spatial, layer->in_channels);
bn_update_status(layer, _mean, layer->variance);
layer->out_cache = normalized(input, _mean, layer->variance, layer->in_spatial, layer->in_channels);
matrix_free(_mean);
}
else {
layer->out_cache = normalized(input, layer->run_mean, layer->run_var, layer->in_spatial, layer->in_channels);
layer->variance = NULL;
}
return scale_shifted(layer->out_cache, layer->gamma, layer->beta, layer->in_channels, layer->in_spatial);
}
void bn_norm_del(matrix *dout, matrix *gamma, matrix *out_norm, matrix *variance, int spatial, int channels) {
const float n = (float)(dout->rows * spatial);
const float eps = 1e-5f;
#pragma omp parallel for
for (int c = 0; c < channels; c++) {
register float dp1 = 0.0f, dp2 = 0.0f;
const float _gamma = gamma->data[c];
const float stddev_inv_n = 1.0f / (sqrtf(variance->data[c] + eps) * n);
for (int b = 0; b < dout->rows; b++) {
int index = spatial * (b * channels + c);
float *dout_ptr = dout->data + index;
float *out_norm_ptr = out_norm->data + index;
for (int i = 0; i < spatial; i++) {
dout_ptr[i] *= _gamma;
dp1 += dout_ptr[i];
dp2 += dout_ptr[i] * out_norm_ptr[i];
dout_ptr[i] *= n;
}
}
for (int b = 0; b < dout->rows; b++) {
int index = spatial * (b * channels + c);
float *dout_ptr = dout->data + index;
float *out_norm_ptr = out_norm->data + index;
for (int i = 0; i < spatial; i++) {
dout_ptr[i] -= (dp1 + (out_norm_ptr[i] * dp2));
dout_ptr[i] *= stddev_inv_n;
}
}
}
}
static matrix* sum_spatial(matrix *src, int spatial, int channels) {
matrix *out = matrix_alloc(1, channels);
#pragma omp parallel for
for (int c = 0; c < channels; c++) {
float sum = 0.0f;
for (int b = 0; b < src->rows; b++) {
float *src_ptr = src->data + spatial * (b * channels + c);
for (int i = 0; i < spatial; i++) {
sum += src_ptr[i];
}
}
out->data[c] = sum;
}
return out;
}
matrix* bn_backward(bn_layer *layer, matrix *dout, float l_rate) {
matrix *out = mat_copy(dout);
// scale shift del
matrix *dp = elemwise_mul(out, layer->out_cache);
matrix *dgamma = sum_spatial(dp, layer->in_spatial, layer->in_channels);
matrix *dbeta = sum_spatial(out, layer->in_spatial, layer->in_channels);
//norm del
bn_norm_del(out, layer->gamma, layer->out_cache, layer->variance, layer->in_spatial, layer->in_channels);
apply_sum(layer->gamma, dgamma, -l_rate);
apply_sum(layer->beta, dbeta, -l_rate);
matrix_free(dp);
matrix_free(dgamma);
matrix_free(dbeta);
return out;
} |
WriteMCLClusters.h | /****************************************************************/
/* Parallel Combinatorial BLAS Library (for Graph Computations) */
/* version 1.6 -------------------------------------------------*/
/* date: 6/15/2017 ---------------------------------------------*/
/* authors: Ariful Azad, Aydin Buluc --------------------------*/
/****************************************************************/
#include <mpi.h>
#include <stdint.h>
#include <sys/time.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream> // Required for stringstreams
#include <ctime>
#include <cmath>
#include "CombBLAS/CombBLAS.h"
namespace combblas {
class HipMCLClusterSaveHandler
{
public:
// no reader
template <typename c, typename t, typename VT>
void save(std::basic_ostream<c,t>& os, std::vector<VT> & strvec, int64_t index)
{
for (auto it = strvec.begin() ; it != strvec.end(); ++it)
os << *it << " ";
}
};
/**
* Write clusters to file: vertices belonging to a cluster are written in a single line separated by space.
* TODO: sort clusters by their sizes
* @param[in] ofName {output file name}
* @param[in] clustIdForVtx {the ith entry stores the cluster id of the ith vertex}
* @param[in] vtxLabels {labels of vertices}
*/
template <class IT>
void WriteMCLClusters(std::string ofName, FullyDistVec<IT, IT> clustIdForVtx, FullyDistVec<IT, std::array<char, MAXVERTNAME> > vtxLabels)
{
auto commGrid = clustIdForVtx.getcommgrid();
MPI_Comm World = commGrid->GetWorld();
int nprocs = commGrid->GetSize();
// find the number of clusters
IT nclusters = clustIdForVtx.Reduce(maximum<IT>(), (IT) 0 ) ;
nclusters ++; // because of zero based indexing for clusters
std::vector<int> rdispls(nprocs+1);
std::vector<int> recvcnt(nprocs);
std::vector<int> sendcnt(nprocs,0);
std::vector<int> sdispls(nprocs+1);
IT ploclen = clustIdForVtx.LocArrSize();
const IT* larr = clustIdForVtx.GetLocArr(); // local part of cluster ids for vertices
//just to get the destination processor
FullyDistVec<IT,IT> temp(commGrid, nclusters,0);
for(IT i=0; i < ploclen; ++i)
{
IT locind;
int owner = temp.Owner(larr[i], locind);
sendcnt[owner]++;
}
MPI_Alltoall(sendcnt.data(), 1, MPI_INT, recvcnt.data(), 1, MPI_INT, World);
sdispls[0] = 0;
rdispls[0] = 0;
for(int i=0; i<nprocs; ++i)
{
sdispls[i+1] = sdispls[i] + sendcnt[i];
rdispls[i+1] = rdispls[i] + recvcnt[i];
}
typedef std::array<char, MAXVERTNAME> STRASARRAY;
typedef std::pair< IT, STRASARRAY> TYPE2SEND;
const STRASARRAY* lVtxLabels = vtxLabels.GetLocArr();
std::vector<TYPE2SEND> senddata(ploclen);
// Pack cluster and vertex information to send
std::vector<int> count(nprocs, 0);
for(IT i=0; i < ploclen; ++i)
{
IT locind;
int owner = temp.Owner(larr[i], locind);
int idx = sdispls[owner] + count[owner];
count[owner]++;
senddata[idx] = TYPE2SEND(locind, lVtxLabels[i]); // sending local cluster ids for the destination processor
}
MPI_Datatype MPI_CLUST;
MPI_Type_contiguous(sizeof(TYPE2SEND), MPI_CHAR, &MPI_CLUST);
MPI_Type_commit(&MPI_CLUST);
IT totrecv = rdispls[nprocs];
std::vector<TYPE2SEND> recvdata(totrecv);
MPI_Alltoallv(senddata.data(), sendcnt.data(), sdispls.data(), MPI_CLUST, recvdata.data(), recvcnt.data(), rdispls.data(), MPI_CLUST, World);
// Receiver groups vertices by cluster ids
std::vector< std::vector<std::string> > vtxGroupbyCC(temp.LocArrSize());
for(int i=0; i<totrecv; ++i)
{
IT clusterID = recvdata[i].first;
auto locnull = std::find(recvdata[i].second.begin(), recvdata[i].second.end(), '\0'); // find the null character (or string::end)
std::string vtxstr(recvdata[i].second.begin(), locnull);
vtxGroupbyCC[clusterID].push_back(vtxstr);
}
// in each cluster sort vertex labels
#ifdef THREADED
#pragma omp parallel for
#endif
for(unsigned int i=0; i<vtxGroupbyCC.size(); ++i)
{
std::sort(vtxGroupbyCC[i].begin(), vtxGroupbyCC[i].end());
}
// Create a vector locally populate it
FullyDistVec<IT,std::vector<std::string> > clusters(commGrid, nclusters, std::vector<std::string>{});
for(int i=0; i<clusters.LocArrSize(); i++)
{
clusters.SetLocalElement(i, vtxGroupbyCC[i]);
}
// do not write header and 1-based
clusters.ParallelWrite(ofName, 1, HipMCLClusterSaveHandler(), false);
}
/**
* Write clusters to file: vertices belonging to a cluster are written in a single line separated by space.
* Ids of vertices are used as labels
* TODO: sort clusters by their sizes
* @param[in] ofName {output file name}
* @param[in] clustIdForVtx {the ith entry stores the cluster id of the ith vertex}
*/
template <class IT>
void WriteMCLClusters(std::string ofName, FullyDistVec<IT, IT> clustIdForVtx, int base)
{
auto commGrid = clustIdForVtx.getcommgrid();
MPI_Comm World = commGrid->GetWorld();
int nprocs = commGrid->GetSize();
IT lenuntil = clustIdForVtx.LengthUntil();
// find the number of clusters
IT nclusters = clustIdForVtx.Reduce(maximum<IT>(), (IT) 0 ) ;
nclusters ++; // because of zero based indexing for clusters
std::vector<int> rdispls(nprocs+1);
std::vector<int> recvcnt(nprocs);
std::vector<int> sendcnt(nprocs,0);
std::vector<int> sdispls(nprocs+1);
IT ploclen = clustIdForVtx.LocArrSize();
const IT* larr = clustIdForVtx.GetLocArr(); // local part of cluster ids for vertices
//just to get the destination processor
FullyDistVec<IT,IT> temp(commGrid, nclusters,0);
for(IT i=0; i < ploclen; ++i)
{
IT locind;
int owner = temp.Owner(larr[i], locind);
sendcnt[owner]++;
}
MPI_Alltoall(sendcnt.data(), 1, MPI_INT, recvcnt.data(), 1, MPI_INT, World);
sdispls[0] = 0;
rdispls[0] = 0;
for(int i=0; i<nprocs; ++i)
{
sdispls[i+1] = sdispls[i] + sendcnt[i];
rdispls[i+1] = rdispls[i] + recvcnt[i];
}
std::vector<std::pair<IT, IT>> senddata(ploclen);
// Pack cluster and vertex information to send
std::vector<int> count(nprocs, 0);
for(IT i=0; i < ploclen; ++i)
{
IT locind;
int owner = temp.Owner(larr[i], locind);
int idx = sdispls[owner] + count[owner];
count[owner]++;
senddata[idx] = std::make_pair(locind, i+lenuntil+base); // sending local cluster ids for the destination processor
}
MPI_Datatype MPI_CLUST;
MPI_Type_contiguous(sizeof(std::pair<IT, IT>), MPI_CHAR, &MPI_CLUST);
MPI_Type_commit(&MPI_CLUST);
IT totrecv = rdispls[nprocs];
std::vector<std::pair<IT, IT>> recvdata(totrecv);
MPI_Alltoallv(senddata.data(), sendcnt.data(), sdispls.data(), MPI_CLUST, recvdata.data(), recvcnt.data(), rdispls.data(), MPI_CLUST, World);
// Receiver groups vertices by cluster ids
std::vector< std::vector<IT> > vtxGroupbyCC(temp.LocArrSize());
for(int i=0; i<totrecv; ++i)
{
IT clusterID = recvdata[i].first;
vtxGroupbyCC[clusterID].push_back(recvdata[i].second);
}
// Create a vector locally populate it
FullyDistVec<IT,std::vector<IT> > clusters(commGrid, nclusters, std::vector<IT>{});
for(int i=0; i<clusters.LocArrSize(); i++)
{
clusters.SetLocalElement(i, vtxGroupbyCC[i]);
}
// do not write header and 1-based
clusters.ParallelWrite(ofName, 1, HipMCLClusterSaveHandler(), false);
}
}
|
omp.c | // RUN: mlir-clang %s --function=* -fopenmp -S | FileCheck %s
void square(double* x, int sstart, int send, int sinc) {
#pragma omp parallel for
for(int i=sstart; i < send; i+= sinc) {
x[i] = i;
}
}
// CHECK: func @square(%arg0: memref<?xf64>, %arg1: i32, %arg2: i32, %arg3: i32) attributes {llvm.linkage = #llvm.linkage<external>} {
// CHECK-DAG: %c1 = arith.constant 1 : index
// CHECK-DAG: %[[i0:.+]] = arith.index_cast %arg1 : i32 to index
// CHECK-DAG: %[[i1:.+]] = arith.index_cast %arg2 : i32 to index
// CHECK-DAG: %[[i2:.+]] = arith.index_cast %arg3 : i32 to index
// CHECK-NEXT: %[[i3:.+]] = arith.subi %[[i1]], %[[i0]] : index
// CHECK-NEXT: %4 = arith.subi %[[i3]], %c1 : index
// CHECK-NEXT: %5 = arith.addi %4, %[[i2]] : index
// CHECK-NEXT: %6 = arith.divui %5, %[[i2]] : index
// CHECK-NEXT: %7 = arith.muli %6, %[[i2]] : index
// CHECK-NEXT: %8 = arith.addi %[[i0]], %7 : index
// CHECK-NEXT: scf.parallel (%arg4) = (%[[i0]]) to (%8) step (%[[i2]]) {
// CHECK-NEXT: %9 = arith.index_cast %arg4 : index to i32
// CHECK-NEXT: %10 = arith.sitofp %9 : i32 to f64
// CHECK-NEXT: memref.store %10, %arg0[%arg4] : memref<?xf64>
// CHECK-NEXT: scf.yield
// CHECK-NEXT: }
// CHECK-NEXT: return
// CHECK-NEXT: }
|
parallel.h | #pragma once
//***************************************
// All the pbbs library uses only four functions for
// accessing parallelism.
// These can be implemented on top of any scheduler.
//***************************************
// number of threads available from OS
// template <>
int num_workers();
// id of running thread, should be numbered from [0...num-workers)
int worker_id();
void set_num_workers(int n);
// the granularity of a simple loop (e.g. adding one to each element
// of an array) to reasonably hide cost of scheduler
// #define PAR_GRANULARITY 2000
// parallel loop from start (inclusive) to end (exclusive) running
// function f.
// f should map long to void.
// granularity is the number of iterations to run sequentially
// if 0 (default) then the scheduler will decide
// conservative uses a safer scheduler
template <typename F>
static void parallel_for(long start, long end, F f, long granularity = 0,
bool conservative = false);
// runs the thunks left and right in parallel.
// both left and write should map void to void
// conservative uses a safer scheduler
template <typename Lf, typename Rf>
static void par_do(Lf left, Rf right, bool conservative = false);
template <typename A, typename Af, typename Df, typename F>
static void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity = 0,
bool conservative = false);
//***************************************
// cilkplus
#if defined(CILK)
#include <cilk/cilk.h>
#include <cilk/cilk_api.h>
#include <cilk/reducer.h>
#include <iostream>
#include <sstream>
#define PAR_GRANULARITY 2000
template <typename F>
inline void parallel_for(long start, long end, F f, long granularity,
bool conservative) {
if (granularity == 0)
cilk_for(long i = start; i < end; i++) f(i);
else if ((end - start) <= granularity)
for (long i = start; i < end; i++) f(i);
else {
long n = end - start;
long mid = (start + (9 * (n + 1)) / 16);
cilk_spawn parallel_for(start, mid, f, granularity);
parallel_for(mid, end, f, granularity);
cilk_sync;
}
}
template <typename F>
inline void parallel_for_1(long start, long end, F f, long granularity,
bool conservative) {
_Pragma("cilk grainsize = 1") cilk_for(long i = start; i < end; i++) f(i);
}
template <typename Lf, typename Rf>
inline void par_do(Lf left, Rf right, bool conservative) {
cilk_spawn right();
left();
cilk_sync;
}
template <typename A>
class alloc_holder {
struct Monoid : cilk::monoid_base<A> {
static void reduce(A *left, A *right) {}
};
public:
cilk::reducer<Monoid> imp_;
alloc_holder() : imp_() {}
};
// TODO try parallel_for_1
template <typename A, typename Af, typename Df, typename F>
inline void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity,
bool conservative) {
alloc_holder<A> alloc;
parallel_for_1(start, end,
[&](size_t i) {
init_alloc(&alloc.imp_.view());
f(i, &(alloc.imp_.view()));
// finish_alloc(&(alloc.imp_.view()));
},
granularity, conservative);
}
// openmp
#elif defined(OPENMP)
#include <omp.h>
#define PAR_GRANULARITY 200000
template <class F>
inline void parallel_for(long start, long end, F f, long granularity,
bool conservative) {
_Pragma("omp parallel for") for (long i = start; i < end; i++) f(i);
}
template <typename F>
inline void parallel_for_1(long start, long end, F f, long granularity,
bool conservative) {
#pragma omp for schedule(dynamic, 1) nowait
for (long i = start; i < end; i++) f(i);
}
bool in_par_do = false;
template <typename Lf, typename Rf>
inline void par_do(Lf left, Rf right, bool conservative) {
if (!in_par_do) {
in_par_do = true; // at top level start up tasking
#pragma omp parallel
#pragma omp single
#pragma omp task
left();
#pragma omp task
right();
#pragma omp taskwait
in_par_do = false;
} else { // already started
#pragma omp task
left();
#pragma omp task
right();
}
}
template <typename Job>
inline void parallel_run(Job job, int num_threads = 0) {
job();
}
template <typename A, typename Af, typename Df, typename F>
inline void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity,
bool conservative) {
A* alloc = nullptr;
#pragma omp parallel private(alloc)
{
alloc = new A();
init_alloc(alloc);
parallel_for_1(start, end, [&](size_t i) { f(i, alloc); }, granularity,
conservative);
//#pragma omp for schedule(dynamic, 1) nowait
// for(long i=start; i<end; i++) f(i, alloc);
finish_alloc(alloc);
}
}
// Guy's scheduler (ABP)
#elif defined(HOMEGROWN)
#include "scheduler.h"
#define PAR_GRANULARITY 512
template <class F>
inline void parallel_for(long start, long end, F f, long granularity,
bool conservative) {
global_scheduler.parfor(start, end, f, granularity, conservative);
}
template <typename Lf, typename Rf>
inline void par_do(Lf left, Rf right, bool conservative) {
return global_scheduler.pardo(left, right, conservative);
}
template <typename Job>
inline void parallel_run(Job job, int num_threads = 0) {
job();
}
template <typename A, typename Af, typename Df, typename F>
inline void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity,
bool conservative) {
parallel_for(start, end,
[&](long i) {
static thread_local A* alloc = new A();
init_alloc(alloc);
f(i, alloc);
},
granularity, conservative);
// finish_alloc(alloc);
}
// c++
#else
#define PAR_GRANULARITY 1000
template <class F>
inline void parallel_for(long start, long end, F f, long granularity,
bool conservative) {
for (long i = start; i < end; i++) {
f(i);
}
}
template <typename Lf, typename Rf>
inline void par_do(Lf left, Rf right, bool conservative) {
left();
right();
}
template <typename Job>
inline void parallel_run(Job job, int num_threads = 0) {
job();
}
template <typename A, typename Af, typename Df, typename F>
inline void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity,
bool conservative) {
A* alloc = new A();
init_alloc(alloc);
for (long i = start; i < end; i++) {
f(i, alloc);
}
finish_alloc(alloc);
}
#endif
|
GB_unaryop__identity_uint32_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__identity_uint32_uint8
// op(A') function: GB_tran__identity_uint32_uint8
// C type: uint32_t
// A type: uint8_t
// cast: uint32_t cij = (uint32_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint8_t
#define GB_CTYPE \
uint32_t
// 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) \
uint32_t z = (uint32_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_UINT32 || GxB_NO_UINT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_uint32_uint8
(
uint32_t *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__identity_uint32_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
|
omp_task_depend_resize_hashmap.c | // RUN: %libomp-compile && env KMP_ENABLE_TASK_THROTTLING=0 %libomp-run
// This test is known to be fragile on NetBSD kernel at the moment,
// https://bugs.llvm.org/show_bug.cgi?id=42020.
// UNSUPPORTED: netbsd
#include<omp.h>
#include<stdlib.h>
#include<string.h>
// The first hashtable static size is 997
#define NUM_DEPS 4000
int main()
{
int *deps = calloc(NUM_DEPS, sizeof(int));
int i;
int failed = 0;
#pragma omp parallel
#pragma omp master
{
for (i = 0; i < NUM_DEPS; i++) {
#pragma omp task firstprivate(i) depend(inout: deps[i])
{
deps[i] = 1;
}
#pragma omp task firstprivate(i) depend(inout: deps[i])
{
deps[i] = 2;
}
}
}
for (i = 0; i < NUM_DEPS; i++) {
if (deps[i] != 2)
failed++;
}
return failed;
}
|
pdf_fmt_plug.c | /* PDF cracker patch for JtR. Hacked together during Monsoon of 2012 by
* Dhiru Kholia <dhiru.kholia at gmail.com>.
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>
*
* Uses code from Sumatra PDF and MuPDF which are under GPL.
*
* Edited by Shane Quigley in 2013.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_pdf;
#elif FMT_REGISTERS_H
john_register_one(&fmt_pdf);
#else
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 64
#endif
#endif
#include "arch.h"
#include "params.h"
#include "common.h"
#include "formats.h"
#include "misc.h"
#include "md5.h"
#include "aes.h"
#include "sha2.h"
#include "rc4.h"
#include "pdfcrack_md5.h"
#include "loader.h"
#include "memdbg.h"
#define FORMAT_LABEL "PDF"
#define FORMAT_NAME ""
#define FORMAT_TAG "$pdf$"
#define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1)
#define FORMAT_TAG_OLD "$pdf$Standard*"
#define FORMAT_TAG_OLD_LEN (sizeof(FORMAT_TAG_OLD)-1)
#define ALGORITHM_NAME "MD5 SHA2 RC4/AES 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1000
#define PLAINTEXT_LENGTH 32
#define BINARY_SIZE 0
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN 1
#define SALT_ALIGN sizeof(int)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#if defined (_OPENMP)
static int omp_t = 1;
#endif
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int *cracked;
static int any_cracked;
static size_t cracked_size;
static struct custom_salt {
int V;
int R;
int P;
char encrypt_metadata;
unsigned char u[127];
unsigned char o[127];
unsigned char ue[32];
unsigned char oe[32];
unsigned char id[128];
int length;
int length_id;
int length_u;
int length_o;
int length_ue;
int length_oe;
} *crypt_out;
static struct fmt_tests pdf_tests[] = {
{"$pdf$4*4*128*-1028*1*16*e03460febe17a048b0adc7f7631bcc56*32*3456205208ad52066d5604018d498a6400000000000000000000000000000000*32*6d598152b22f8fa8085b19a866dce1317f645788a065a74831588a739a579ac4", "openwall"},
{"$pdf$2*3*128*-4*1*16*34b1b6e593787af681a9b63fa8bf563b*32*289ece9b5ce451a5d7064693dab3badf101112131415161718191a1b1c1d1e1f*32*badad1e86442699427116d3e5d5271bc80a27814fc5e80f815efeef839354c5f", "test"},
{"$pdf$4*4*128*-1028*1*16*c015cff8dbf99345ac91c84a45667784*32*0231a4c9cae29b53892874e168cfae9600000000000000000000000000000000*32*137ad7063db5114a66ce1900d47e5cab9c5d7053487d92ac978f54db86eca393", "testpassword"},
{"$pdf$5*6*256*-1028*1*16*05e5abeb21ad2e47adac1c2b2c7b7a31*127*51d3a6a09a675503383e5bc0b53da77ec5d5ea1d1998fb94e00a02a1c2e49313c177905272a4e8e68b382254ec8ed74800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*127*dc38f01ef129aae2fca847396465ed518f9c7cf4f2c8cb4399a849d0fe9110227739ab88ddc9a6cf388ae11941270af500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*32*b8e137baf316e0789ffa73f888d26495c14d31f2cfff3799e339e2fa078649f5*32*835a9e07461992791914c3d62d37493e07d140937529ab43e26ac2a657152c3c", "testpassword"},
{"$pdf$5*5*256*-1028*1*16*762896ef582ca042a15f380c63ab9f2c*127*8713e2afdb65df1d3801f77a4c4da4905c49495e7103afc2deb06d9fba7949a565143288823871270d9d882075a75da600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*127*15d0b992974ff80529e4b616b8c4c79d787705b6c8a9e0f85446498ae2432e0027d8406b57f78b60b11341a0757d7c4a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*32*a7a0f3891b469ba7261ce04752dad9c6de0db9c4155c4180e721938a7d9666c7*32*2fa9a0c52badebae2c19dfa7b0005a9cfc909b92babbe7db66a794e96a9f91e3", "openwall"},
/* following are old-style hashes */
{"$pdf$Standard*badad1e86442699427116d3e5d5271bc80a27814fc5e80f815efeef839354c5f*289ece9b5ce451a5d7064693dab3badf101112131415161718191a1b1c1d1e1f*16*34b1b6e593787af681a9b63fa8bf563b*1*1*0*1*4*128*-4*3*2", "test"},
{"$pdf$Standard*9a1156c38ab8177598d1608df7d7e340ae639679bd66bc4cda9bc9a4eedeb170*1f300cd939dd5cf0920c787f12d16be22205e55a5bec5c9c6d563ab4fd0770d7*16*c015cff8dbf99345ac91c84a45667784*1*1*0*1*6*40*-4*2*1", "testpassword"},
{"$pdf$Standard*7303809eaf677bdb5ca64b9d8cb0ccdd47d09a7b28ad5aa522c62685c6d9e499*bf38d7a59daaf38365a338e1fc07976102f1dfd6bdb52072032f57920109b43a*16*c56bbc4145d25b468a873618cd71c2d3*1*1*0*1*6*40*-4*2*1", "test"},
{"$pdf$Standard*137ad7063db5114a66ce1900d47e5cab9c5d7053487d92ac978f54db86eca393*0231a4c9cae29b53892874e168cfae9600000000000000000000000000000000*16*c015cff8dbf99345ac91c84a45667784*1*1*0*1*6*128*-1028*3*2", "testpassword"},
{"$pdf$Standard*d83a8ab680f144dfb2ff2334c206a6060779e007701ab881767f961aecda7984*a5ed4de7e078cb75dfdcd63e8da7a25800000000000000000000000000000000*16*06a7f710cf8dfafbd394540d40984ae2*1*1*0*1*4*128*-1028*3*2", "July2099"},
{"$pdf$Standard*6a80a547b8b8b7636fcc5b322f1c63ce4b670c9b01f2aace09e48d85e1f19f83*e64eb62fc46be66e33571d50a29b464100000000000000000000000000000000*16*14a8c53ffa4a79b3ed9421ef15618420*1*1*0*1*4*128*-1028*3*2", "38r285a9"},
{"$pdf$Standard*2446dd5ed2e18b3ce1ac9b56733226018e3f5c2639051eb1c9b2b215b30bc820*fa3af175d761963c8449ee7015b7770800000000000000000000000000000000*16*12a4da1abe6b7a1ceb84610bad87236d*1*1*0*1*4*128*-1028*3*2", "WHATwhatWHERE?"},
{"$pdf$Standard*e600ecc20288ad8b0d64a929c6a83ee2517679aa0218beceea8b7986726a8cdb*38aca54678d67c003a8193381b0fa1cc101112131415161718191a1b1c1d1e1f*16*1521fbe61419fcad51878cc5d478d5ff*1*1*0*1*4*128*-3904*3*2", ""},
/* CMIYC 2013 "pro" hashes */
{"$pdf$4*4*128*-4*1*16*f7bc2744e1652cf61ca83cac8fccb535*32*f55cc5032f04b985c5aeacde5ec4270f0122456a91bae5134273a6db134c87c4*32*785d891cdcb5efa59893c78f37e7b75acef8924951039b4fa13f62d92bb3b660", "L4sV3g4z"},
{"$pdf$4*4*128*-4*1*16*ec8ea2af2977db1faa4a955904dc956f*32*fc413edb049720b1f8eac87a358faa740122456a91bae5134273a6db134c87c4*32*1ba7aed2f19c77ac6b5061230b62e80b48fc42918f92aef689ceb07d26204991", "ZZt0pr0x"},
{"$pdf$4*4*128*-4*1*16*56761d6da774d8d47387dccf1a84428c*32*640782cab5b7c8f6cf5eab82c38016540122456a91bae5134273a6db134c87c4*32*b5720d5f3d9675a280c6bb8050cbb169e039b578b2de4a42a40dc14765e064cf", "24Le`m0ns"},
/* This hash exposed a problem with our length_id check */
{"$pdf$1*2*40*-4*1*36*65623237393831382d636439372d343130332d613835372d343164303037316639386134*32*c7230519f7db63ab1676fa30686428f0f997932bf831f1c1dcfa48cfb3b7fe99*32*161cd2f7c95283ca9db930b36aad3571ee6f5fb5632f30dc790e19c5069c86b8", "vision"},
{NULL}
};
static void init(struct fmt_main *self)
{
#if defined (_OPENMP)
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(sizeof(*saved_key), self->params.max_keys_per_crypt);
any_cracked = 0;
cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt;
cracked = mem_calloc(sizeof(*cracked), self->params.max_keys_per_crypt);
}
static void done(void)
{
MEM_FREE(cracked);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *keeptr;
char *p;
int res;
if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN))
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += FORMAT_TAG_LEN;
if ((p = strtokm(ctcopy, "*")) == NULL) /* V */
goto err;
if (!isdec(p)) goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* R */
goto err;
if (!isdec(p)) goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* length */
goto err;
if (!isdec(p)) goto err;
res = atoi(p);
if (res > 256)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* P */
goto err;
if (!isdec_negok(p)) goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* encrypt_metadata */
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* length_id */
goto err;
if (!isdec(p)) goto err;
res = atoi(p);
if (res > 128)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* id */
goto err;
if (strlen(p) != res * 2)
goto err;
if (!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* length_u */
goto err;
if (!isdec(p)) goto err;
res = atoi(p);
if (res > 127)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* u */
goto err;
if (strlen(p) != res * 2)
goto err;
if (!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* length_o */
goto err;
if (!isdec(p)) goto err;
res = atoi(p);
if (res > 127)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* o */
goto err;
if (strlen(p) != res * 2)
goto err;
if (!ishexlc(p))
goto err;
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
static int old_valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *ptr, *keeptr;
int res;
if (strncmp(ciphertext, FORMAT_TAG_OLD, FORMAT_TAG_OLD_LEN))
return 0;
if (!(ctcopy = strdup(ciphertext)))
return 0;
keeptr = ctcopy;
ctcopy += FORMAT_TAG_OLD_LEN;
if (!(ptr = strtokm(ctcopy, "*"))) /* o_string */
goto error;
if (!ishexlc(ptr))
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* u_string */
goto error;
if (!ishexlc(ptr))
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* fileIDLen */
goto error;
if (strncmp(ptr, "16", 2))
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* fileID */
goto error;
if (!ishexlc(ptr))
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* encryptMetaData */
goto error;
res = atoi(ptr);
if (res != 0 && res != 1)
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* work_with_user */
goto error;
res = atoi(ptr);
if (res != 0 && res != 1)
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* have_userpassword */
goto error;
res = atoi(ptr);
if (res != 0 && res != 1)
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* version_major */
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* version_minor */
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* length */
goto error;
res = atoi(ptr);
if (res < 0 || res > 256)
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* permissions */
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* revision */
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* version */
goto error;
MEM_FREE(keeptr);
return 1;
error:
MEM_FREE(keeptr);
return 0;
}
char * convert_old_to_new(char ciphertext[])
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
char *out = mem_alloc_tiny(strlen(ctcopy), MEM_ALIGN_NONE);
const char *fields[14];
char *p;
int c = 0;
p = strtokm(ctcopy, "*");
for (c = 0; c < 14; c++) {
fields[c] = p;
p = strtokm(NULL, "*");
}
strcpy(out,FORMAT_TAG);
strcat(out,fields[13]);
strcat(out,"*");
strcat(out,fields[12]);
strcat(out,"*");
strcat(out,fields[10]);
strcat(out,"*");
strcat(out,fields[11]);
strcat(out,"*");
strcat(out,fields[5]);
strcat(out,"*");
strcat(out,fields[3]);
strcat(out,"*");
strcat(out,fields[4]);
strcat(out,"*32*");
strcat(out,fields[2]);
strcat(out,"*32*");
strcat(out,fields[1]);
MEM_FREE(keeptr);
return out;
}
static char *prepare(char *split_fields[10], struct fmt_main *self)
{
// Convert old format to new one
if (!strncmp(split_fields[1], FORMAT_TAG_OLD, FORMAT_TAG_OLD_LEN) &&
old_valid(split_fields[1], self))
return convert_old_to_new(split_fields[1]);
return split_fields[1];
}
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
int i;
char *p;
static struct custom_salt cs;
memset(&cs, 0, sizeof(cs));
ctcopy += FORMAT_TAG_LEN; /* skip over "$pdf$" marker */
p = strtokm(ctcopy, "*");
cs.V = atoi(p);
p = strtokm(NULL, "*");
cs.R = atoi(p);
p = strtokm(NULL, "*");
cs.length = atoi(p);
p = strtokm(NULL, "*");
cs.P = atoi(p);
p = strtokm(NULL, "*");
cs.encrypt_metadata = atoi(p);
p = strtokm(NULL, "*");
cs.length_id = atoi(p);
p = strtokm(NULL, "*");
for (i = 0; i < cs.length_id; i++)
cs.id[i] =
atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
p = strtokm(NULL, "*");
cs.length_u = atoi(p);
p = strtokm(NULL, "*");
for (i = 0; i < cs.length_u; i++)
cs.u[i] =
atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
p = strtokm(NULL, "*");
cs.length_o = atoi(p);
p = strtokm(NULL, "*");
for (i = 0; i < cs.length_o; i++)
cs.o[i] =
atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
MEM_FREE(keeptr);
return (void *)&cs;
}
static void set_salt(void *salt)
{
crypt_out = (struct custom_salt *)salt;
}
static void pdf_set_key(char *key, int index)
{
strnzcpy(saved_key[index], key, sizeof(*saved_key));
}
static char *get_key(int index)
{
return saved_key[index];
}
static const unsigned char padding[32] =
{
0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a
};
/* Compute an encryption key (PDF 1.7 algorithm 3.2) */
static void
pdf_compute_encryption_key(unsigned char *password, int pwlen, unsigned char *key)
{
unsigned char buf[32];
unsigned int p;
int n;
MD5_CTX md5;
n = crypt_out->length / 8;
/* Step 1 - copy and pad password string */
if (pwlen > 32)
pwlen = 32;
memcpy(buf, password, pwlen);
memcpy(buf + pwlen, padding, 32 - pwlen);
/* Step 2 - init md5 and pass value of step 1 */
MD5_Init(&md5);
MD5_Update(&md5, buf, 32);
/* Step 3 - pass O value */
MD5_Update(&md5, crypt_out->o, 32);
/* Step 4 - pass P value as unsigned int, low-order byte first */
p = (unsigned int) crypt_out->P;
buf[0] = (p) & 0xFF;
buf[1] = (p >> 8) & 0xFF;
buf[2] = (p >> 16) & 0xFF;
buf[3] = (p >> 24) & 0xFF;
MD5_Update(&md5, buf, 4);
/* Step 5 - pass first element of ID array */
MD5_Update(&md5, crypt_out->id, crypt_out->length_id);
/* Step 6 (revision 4 or greater) - if metadata is not encrypted pass 0xFFFFFFFF */
if (crypt_out->R >= 4)
{
if (!crypt_out->encrypt_metadata)
{
buf[0] = 0xFF;
buf[1] = 0xFF;
buf[2] = 0xFF;
buf[3] = 0xFF;
MD5_Update(&md5, buf, 4);
}
}
/* Step 7 - finish the hash */
MD5_Final(buf, &md5);
/* Step 8 (revision 3 or greater) - do some voodoo 50 times */
if (crypt_out->R >= 3)
{
/* for (i = 0; i < 50; i++)
{
MD5_Init(&md5);
MD5_Update(&md5, buf, n);
MD5_Final(buf, &md5);
} */
md5_50(buf);
}
/* Step 9 - the key is the first 'n' bytes of the result */
memcpy(key, buf, n);
}
/* Compute an encryption key (PDF 1.7 ExtensionLevel 3 algorithm 3.2a) */
static void
pdf_compute_encryption_key_r5(unsigned char *password, int pwlen, int ownerkey, unsigned char *validationkey)
{
unsigned char buffer[128 + 8 + 48];
SHA256_CTX sha256;
/* Step 2 - truncate UTF-8 password to 127 characters */
if (pwlen > 127)
pwlen = 127;
/* Step 3/4 - test password against owner/user key and compute encryption key */
memcpy(buffer, password, pwlen);
if (ownerkey)
{
memcpy(buffer + pwlen, crypt_out->o + 32, 8);
memcpy(buffer + pwlen + 8, crypt_out->u, 48);
}
else
memcpy(buffer + pwlen, crypt_out->u + 32, 8);
SHA256_Init(&sha256);
SHA256_Update(&sha256, buffer, pwlen + 8 + (ownerkey ? 48 : 0));
SHA256_Final(validationkey, &sha256);
}
/* SumatraPDF: support crypt version 5 revision 6 */
/*
* Compute an encryption key (PDF 1.7 ExtensionLevel 8 algorithm 3.2b)
* http://esec-lab.sogeti.com/post/The-undocumented-password-validation-algorithm-of-Adobe-Reader-X
*/
static void
pdf_compute_hardened_hash_r6(unsigned char *password, int pwlen, unsigned char salt[8],
unsigned char *ownerkey, unsigned char hash[32])
{
unsigned char data[(128 + 64 + 48) * 64];
unsigned char block[64];
int block_size = 32;
int data_len = 0;
int i, j, sum;
SHA256_CTX sha256;
SHA512_CTX sha384;
SHA512_CTX sha512;
AES_KEY aes;
/* Step 1: calculate initial data block */
SHA256_Init(&sha256);
SHA256_Update(&sha256, password, pwlen);
SHA256_Update(&sha256, salt, 8);
if (ownerkey)
SHA256_Update(&sha256, ownerkey, 48);
SHA256_Final(block, &sha256);
for (i = 0; i < 64 || i < data[data_len * 64 - 1] + 32; i++)
{
/* Step 2: repeat password and data block 64 times */
memcpy(data, password, pwlen);
memcpy(data + pwlen, block, block_size);
// ownerkey is always NULL
// memcpy(data + pwlen + block_size, ownerkey, ownerkey ? 48 : 0);
data_len = pwlen + block_size + (ownerkey ? 48 : 0);
for (j = 1; j < 64; j++)
memcpy(data + j * data_len, data, data_len);
/* Step 3: encrypt data using data block as key and iv */
AES_set_encrypt_key(block, 128, &aes);
// aes_crypt_cbc(&aes, AES_ENCRYPT, data_len * 64, block + 16, data, data);
AES_cbc_encrypt(data, data, data_len * 64, &aes, block + 16, AES_ENCRYPT);
/* Step 4: determine SHA-2 hash size for this round */
for (j = 0, sum = 0; j < 16; j++)
sum += data[j];
/* Step 5: calculate data block for next round */
block_size = 32 + (sum % 3) * 16;
switch (block_size)
{
case 32:
SHA256_Init(&sha256);
SHA256_Update(&sha256, data, data_len * 64);
SHA256_Final(block, &sha256);
break;
case 48:
SHA384_Init(&sha384);
SHA384_Update(&sha384, data, data_len * 64);
SHA384_Final(block, &sha384);
break;
case 64:
SHA512_Init(&sha512);
SHA512_Update(&sha512, data, data_len * 64);
SHA512_Final(block, &sha512);
break;
}
}
memset(data, 0, sizeof(data));
memcpy(hash, block, 32);
}
/* Computing the user password (PDF 1.7 algorithm 3.4 and 3.5) */
static void pdf_compute_user_password(unsigned char *password, unsigned char *output)
{
int pwlen = strlen((char*)password);
unsigned char key[128];
if (crypt_out->R == 2) {
RC4_KEY arc4;
int n;
n = crypt_out->length / 8;
pdf_compute_encryption_key(password, pwlen, key);
RC4_set_key(&arc4, n, key);
RC4(&arc4, 32, padding, output);
}
if (crypt_out->R == 3 || crypt_out->R == 4) {
unsigned char xor[32];
unsigned char digest[16];
MD5_CTX md5;
RC4_KEY arc4;
int i, x, n;
n = crypt_out->length / 8;
pdf_compute_encryption_key(password, pwlen, key);
MD5_Init(&md5);
MD5_Update(&md5, (char*)padding, 32);
MD5_Update(&md5, crypt_out->id, crypt_out->length_id);
MD5_Final(digest, &md5);
RC4_set_key(&arc4, n, key);
RC4(&arc4, 16, digest, output);
for (x = 1; x <= 19; x++) {
for (i = 0; i < n; i++)
xor[i] = key[i] ^ x;
RC4_set_key(&arc4, n, xor);
RC4(&arc4, 16, output, output);
}
memcpy(output + 16, padding, 16);
}
if (crypt_out->R == 5) {
pdf_compute_encryption_key_r5(password, pwlen, 0, output);
}
/* SumatraPDF: support crypt version 5 revision 6 */
if (crypt_out->R == 6)
pdf_compute_hardened_hash_r6(password, pwlen, crypt_out->u + 32, NULL, output);
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
if (any_cracked) {
memset(cracked, 0, cracked_size);
any_cracked = 0;
}
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
#if !defined(_OPENMP) && defined (__CYGWIN32__) && defined (MEMDBG_ON)
static /* work around for some 'unknown' bug in cygwin gcc when using memdbg.h code. I have NO explanation, JimF. */
#endif
unsigned char output[32];
pdf_compute_user_password((unsigned char*)saved_key[index], output);
if (crypt_out->R == 2 || crypt_out->R == 5 || crypt_out->R == 6)
if (memcmp(output, crypt_out->u, 32) == 0) {
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
if (crypt_out->R == 3 || crypt_out->R == 4)
if (memcmp(output, crypt_out->u, 16) == 0) {
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
}
return count;
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return cracked[index];
}
/*
* Report revision as tunable cost, since between revisions 2 and 6,
* only revisions 3 and 4 seem to have a similar c/s rate.
*/
static unsigned int pdf_revision(void *salt)
{
struct custom_salt *my_salt;
my_salt = salt;
return (unsigned int) my_salt->R;
}
struct fmt_main fmt_pdf = {
{
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,
{
"revision",
},
{ FORMAT_TAG, FORMAT_TAG_OLD },
pdf_tests
},
{
init,
done,
fmt_default_reset,
prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
{
pdf_revision,
},
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
pdf_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
compare.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC OOO M M PPPP AAA RRRR EEEEE %
% C O O MM MM P P A A R R E %
% C O O M M M PPPP AAAAA RRRR EEE %
% C O O M M P A A R R E %
% CCCC OOO M M P A A R R EEEEE %
% %
% %
% MagickCore Image Comparison Methods %
% %
% Software Design %
% Cristy %
% December 2003 %
% %
% %
% Copyright 1999-2017 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/compare.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string_.h"
#include "MagickCore/statistic.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"
#include "MagickCore/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p a r e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CompareImages() compares one or more pixel channels of an image to a
% reconstructed image and returns the difference image.
%
% The format of the CompareImages method is:
%
% Image *CompareImages(const Image *image,const Image *reconstruct_image,
% const MetricType metric,double *distortion,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o metric: the metric.
%
% o distortion: the computed distortion between the images.
%
% o exception: return any errors or warnings in this structure.
%
*/
static size_t GetImageChannels(const Image *image)
{
register ssize_t
i;
size_t
channels;
channels=0;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) != 0)
channels++;
}
return(channels == 0 ? (size_t) 1 : channels);
}
MagickExport Image *CompareImages(Image *image,const Image *reconstruct_image,
const MetricType metric,double *distortion,ExceptionInfo *exception)
{
CacheView
*highlight_view,
*image_view,
*reconstruct_view;
const char
*artifact;
double
fuzz;
Image
*clone_image,
*difference_image,
*highlight_image;
MagickBooleanType
status;
PixelInfo
highlight,
lowlight,
masklight;
RectangleInfo
geometry;
size_t
columns,
rows;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
assert(distortion != (double *) NULL);
*distortion=0.0;
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=GetImageDistortion(image,reconstruct_image,metric,distortion,
exception);
if (status == MagickFalse)
return((Image *) NULL);
columns=MagickMax(image->columns,reconstruct_image->columns);
rows=MagickMax(image->rows,reconstruct_image->rows);
SetGeometry(image,&geometry);
geometry.width=columns;
geometry.height=rows;
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageMask(clone_image,ReadPixelMask,(Image *) NULL,exception);
difference_image=ExtentImage(clone_image,&geometry,exception);
clone_image=DestroyImage(clone_image);
if (difference_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageAlphaChannel(difference_image,OpaqueAlphaChannel,exception);
highlight_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (highlight_image == (Image *) NULL)
{
difference_image=DestroyImage(difference_image);
return((Image *) NULL);
}
status=SetImageStorageClass(highlight_image,DirectClass,exception);
if (status == MagickFalse)
{
difference_image=DestroyImage(difference_image);
highlight_image=DestroyImage(highlight_image);
return((Image *) NULL);
}
(void) SetImageMask(highlight_image,ReadPixelMask,(Image *) NULL,exception);
(void) SetImageAlphaChannel(highlight_image,OpaqueAlphaChannel,exception);
(void) QueryColorCompliance("#f1001ecc",AllCompliance,&highlight,exception);
artifact=GetImageArtifact(image,"compare:highlight-color");
if (artifact != (const char *) NULL)
(void) QueryColorCompliance(artifact,AllCompliance,&highlight,exception);
(void) QueryColorCompliance("#ffffffcc",AllCompliance,&lowlight,exception);
artifact=GetImageArtifact(image,"compare:lowlight-color");
if (artifact != (const char *) NULL)
(void) QueryColorCompliance(artifact,AllCompliance,&lowlight,exception);
(void) QueryColorCompliance("#888888cc",AllCompliance,&masklight,exception);
artifact=GetImageArtifact(image,"compare:masklight-color");
if (artifact != (const char *) NULL)
(void) QueryColorCompliance(artifact,AllCompliance,&masklight,exception);
/*
Generate difference image.
*/
status=MagickTrue;
fuzz=GetFuzzyColorDistance(image,reconstruct_image);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
highlight_view=AcquireAuthenticCacheView(highlight_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,highlight_image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
MagickBooleanType
sync;
register const Quantum
*magick_restrict p,
*magick_restrict q;
register Quantum
*magick_restrict r;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
r=QueueCacheViewAuthenticPixels(highlight_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) ||
(r == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
MagickStatusType
difference;
register ssize_t
i;
if ((GetPixelReadMask(image,p) == 0) ||
(GetPixelReadMask(reconstruct_image,q) == 0))
{
SetPixelViaPixelInfo(highlight_image,&masklight,r);
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
r+=GetPixelChannels(highlight_image);
continue;
}
difference=MagickFalse;
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q);
if ((distance*distance) > fuzz)
{
difference=MagickTrue;
break;
}
}
if (difference == MagickFalse)
SetPixelViaPixelInfo(highlight_image,&lowlight,r);
else
SetPixelViaPixelInfo(highlight_image,&highlight,r);
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
r+=GetPixelChannels(highlight_image);
}
sync=SyncCacheViewAuthenticPixels(highlight_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
highlight_view=DestroyCacheView(highlight_view);
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
(void) CompositeImage(difference_image,highlight_image,image->compose,
MagickTrue,0,0,exception);
(void) SetImageAlphaChannel(difference_image,OffAlphaChannel,exception);
highlight_image=DestroyImage(highlight_image);
if (status == MagickFalse)
difference_image=DestroyImage(difference_image);
return(difference_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e D i s t o r t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageDistortion() compares one or more pixel channels of an image to a
% reconstructed image and returns the specified distortion metric.
%
% The format of the GetImageDistortion method is:
%
% MagickBooleanType GetImageDistortion(const Image *image,
% const Image *reconstruct_image,const MetricType metric,
% double *distortion,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o metric: the metric.
%
% o distortion: the computed distortion between the images.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType GetAbsoluteDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
fuzz;
MagickBooleanType
status;
size_t
columns,
rows;
ssize_t
y;
/*
Compute the absolute difference in pixels between two images.
*/
status=MagickTrue;
fuzz=GetFuzzyColorDistance(image,reconstruct_image);
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
j,
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
MagickBooleanType
difference;
register ssize_t
i;
if (GetPixelWriteMask(image,p) == 0)
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
difference=MagickFalse;
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q);
if ((distance*distance) > fuzz)
{
channel_distortion[i]++;
difference=MagickTrue;
}
}
if (difference != MagickFalse)
channel_distortion[CompositePixelChannel]++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetAbsoluteError)
#endif
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]+=channel_distortion[j];
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType GetFuzzDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
area;
MagickBooleanType
status;
register ssize_t
j;
size_t
columns,
rows;
ssize_t
y;
status=MagickTrue;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
area=0.0;
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,rows,1) reduction(+:area)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
register ssize_t
i;
if ((GetPixelReadMask(image,p) == 0) ||
(GetPixelReadMask(reconstruct_image,q) == 0))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image,
channel,q));
channel_distortion[i]+=distance*distance;
channel_distortion[CompositePixelChannel]+=distance*distance;
}
area++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetFuzzDistortion)
#endif
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]+=channel_distortion[j];
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
area=PerceptibleReciprocal(area);
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]*=area;
distortion[CompositePixelChannel]/=(double) GetImageChannels(image);
distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]);
return(status);
}
static MagickBooleanType GetMeanAbsoluteDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
area;
MagickBooleanType
status;
register ssize_t
j;
size_t
columns,
rows;
ssize_t
y;
status=MagickTrue;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
area=0.0;
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,rows,1) reduction(+:area)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
register ssize_t
i;
if ((GetPixelReadMask(image,p) == 0) ||
(GetPixelReadMask(reconstruct_image,q) == 0))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=QuantumScale*fabs(Sa*p[i]-Da*GetPixelChannel(reconstruct_image,
channel,q));
channel_distortion[i]+=distance;
channel_distortion[CompositePixelChannel]+=distance;
}
area++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetMeanAbsoluteError)
#endif
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]+=channel_distortion[j];
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
area=PerceptibleReciprocal(area);
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]*=area;
distortion[CompositePixelChannel]/=(double) GetImageChannels(image);
return(status);
}
static MagickBooleanType GetMeanErrorPerPixel(Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
MagickBooleanType
status;
double
area,
maximum_error,
mean_error;
size_t
columns,
rows;
ssize_t
y;
status=MagickTrue;
area=0.0;
maximum_error=0.0;
mean_error=0.0;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
for (y=0; y < (ssize_t) rows; y++)
{
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
register ssize_t
i;
if ((GetPixelReadMask(image,p) == 0) ||
(GetPixelReadMask(reconstruct_image,q) == 0))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=fabs(Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q));
distortion[i]+=distance;
distortion[CompositePixelChannel]+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
area++;
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
image->error.mean_error_per_pixel=distortion[CompositePixelChannel]/area;
image->error.normalized_mean_error=QuantumScale*QuantumScale*mean_error/area;
image->error.normalized_maximum_error=QuantumScale*maximum_error;
return(status);
}
static MagickBooleanType GetMeanSquaredDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
area;
MagickBooleanType
status;
register ssize_t
j;
size_t
columns,
rows;
ssize_t
y;
status=MagickTrue;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
area=0.0;
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,rows,1) reduction(+:area)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
register ssize_t
i;
if ((GetPixelReadMask(image,p) == 0) ||
(GetPixelReadMask(reconstruct_image,q) == 0))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image,
channel,q));
channel_distortion[i]+=distance*distance;
channel_distortion[CompositePixelChannel]+=distance*distance;
}
area++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetMeanSquaredError)
#endif
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]+=channel_distortion[j];
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
area=PerceptibleReciprocal(area);
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]*=area;
distortion[CompositePixelChannel]/=GetImageChannels(image);
return(status);
}
static MagickBooleanType GetNormalizedCrossCorrelationDistortion(
const Image *image,const Image *reconstruct_image,double *distortion,
ExceptionInfo *exception)
{
#define SimilarityImageTag "Similarity/Image"
CacheView
*image_view,
*reconstruct_view;
ChannelStatistics
*image_statistics,
*reconstruct_statistics;
double
area;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
size_t
columns,
rows;
ssize_t
y;
/*
Normalize to account for variation due to lighting and exposure condition.
*/
image_statistics=GetImageStatistics(image,exception);
reconstruct_statistics=GetImageStatistics(reconstruct_image,exception);
if ((image_statistics == (ChannelStatistics *) NULL) ||
(reconstruct_statistics == (ChannelStatistics *) NULL))
{
if (image_statistics != (ChannelStatistics *) NULL)
image_statistics=(ChannelStatistics *) RelinquishMagickMemory(
image_statistics);
if (reconstruct_statistics != (ChannelStatistics *) NULL)
reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory(
reconstruct_statistics);
return(MagickFalse);
}
status=MagickTrue;
progress=0;
for (i=0; i <= MaxPixelChannels; i++)
distortion[i]=0.0;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
area=0.0;
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
for (y=0; y < (ssize_t) rows; y++)
{
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) columns; x++)
{
if ((GetPixelReadMask(image,p) == 0) ||
(GetPixelReadMask(reconstruct_image,q) == 0))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
area++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
}
area=PerceptibleReciprocal(area);
for (y=0; y < (ssize_t) rows; y++)
{
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
if ((GetPixelReadMask(image,p) == 0) ||
(GetPixelReadMask(reconstruct_image,q) == 0))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*(image->alpha_trait != UndefinedPixelTrait ?
GetPixelAlpha(image,p) : OpaqueAlpha);
Da=QuantumScale*(reconstruct_image->alpha_trait != UndefinedPixelTrait ?
GetPixelAlpha(reconstruct_image,q) : OpaqueAlpha);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
{
distortion[i]+=area*QuantumScale*(p[i]-
image_statistics[channel].mean)*(GetPixelChannel(
reconstruct_image,channel,q)-
reconstruct_statistics[channel].mean);
}
else
{
distortion[i]+=area*QuantumScale*(Sa*p[i]-
image_statistics[channel].mean)*(Da*GetPixelChannel(
reconstruct_image,channel,q)-
reconstruct_statistics[channel].mean);
}
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SimilarityImageTag,progress++,rows);
if (proceed == MagickFalse)
{
status=MagickFalse;
break;
}
}
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
/*
Divide by the standard deviation.
*/
distortion[CompositePixelChannel]=0.0;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
gamma;
PixelChannel channel=GetPixelChannelChannel(image,i);
gamma=image_statistics[channel].standard_deviation*
reconstruct_statistics[channel].standard_deviation;
gamma=PerceptibleReciprocal(gamma);
distortion[i]=QuantumRange*gamma*distortion[i];
distortion[CompositePixelChannel]+=distortion[i]*distortion[i];
}
distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]/
GetImageChannels(image));
/*
Free resources.
*/
reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory(
reconstruct_statistics);
image_statistics=(ChannelStatistics *) RelinquishMagickMemory(
image_statistics);
return(status);
}
static MagickBooleanType GetPeakAbsoluteDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
MagickBooleanType
status;
size_t
columns,
rows;
ssize_t
y;
status=MagickTrue;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
j,
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
register ssize_t
i;
if ((GetPixelReadMask(image,p) == 0) ||
(GetPixelReadMask(reconstruct_image,q) == 0))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=QuantumScale*fabs(Sa*p[i]-Da*GetPixelChannel(reconstruct_image,
channel,q));
if (distance > channel_distortion[i])
channel_distortion[i]=distance;
if (distance > channel_distortion[CompositePixelChannel])
channel_distortion[CompositePixelChannel]=distance;
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetPeakAbsoluteError)
#endif
for (j=0; j <= MaxPixelChannels; j++)
if (channel_distortion[j] > distortion[j])
distortion[j]=channel_distortion[j];
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
return(status);
}
static inline double MagickLog10(const double x)
{
#define Log10Epsilon (1.0e-11)
if (fabs(x) < Log10Epsilon)
return(log10(Log10Epsilon));
return(log10(fabs(x)));
}
static MagickBooleanType GetPeakSignalToNoiseRatio(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
MagickBooleanType
status;
register ssize_t
i;
status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception);
for (i=0; i <= MaxPixelChannels; i++)
if (fabs(distortion[i]) >= MagickEpsilon)
distortion[i]=20.0*MagickLog10((double) 1.0/sqrt(distortion[i]));
return(status);
}
static MagickBooleanType GetPerceptualHashDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
ChannelPerceptualHash
*channel_phash,
*reconstruct_phash;
const char
*artifact;
MagickBooleanType
normalize;
ssize_t
channel;
/*
Compute perceptual hash in the sRGB colorspace.
*/
channel_phash=GetImagePerceptualHash(image,exception);
if (channel_phash == (ChannelPerceptualHash *) NULL)
return(MagickFalse);
reconstruct_phash=GetImagePerceptualHash(reconstruct_image,exception);
if (reconstruct_phash == (ChannelPerceptualHash *) NULL)
{
channel_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(
channel_phash);
return(MagickFalse);
}
artifact=GetImageArtifact(image,"phash:normalize");
normalize=(artifact == (const char *) NULL) ||
(IsStringTrue(artifact) == MagickFalse) ? MagickFalse : MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4)
#endif
for (channel=0; channel < MaxPixelChannels; channel++)
{
double
difference;
register ssize_t
i;
difference=0.0;
for (i=0; i < MaximumNumberOfImageMoments; i++)
{
double
alpha,
beta;
register ssize_t
j;
for (j=0; j < (ssize_t) channel_phash[0].number_colorspaces; j++)
{
alpha=channel_phash[channel].phash[j][i];
beta=reconstruct_phash[channel].phash[j][i];
if (normalize == MagickFalse)
difference+=(beta-alpha)*(beta-alpha);
else
difference=sqrt((beta-alpha)*(beta-alpha)/
channel_phash[0].number_channels);
}
}
distortion[channel]+=difference;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetPerceptualHashDistortion)
#endif
distortion[CompositePixelChannel]+=difference;
}
/*
Free resources.
*/
reconstruct_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(
reconstruct_phash);
channel_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(channel_phash);
return(MagickTrue);
}
static MagickBooleanType GetRootMeanSquaredDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
MagickBooleanType
status;
register ssize_t
i;
status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception);
for (i=0; i <= MaxPixelChannels; i++)
distortion[i]=sqrt(distortion[i]);
return(status);
}
MagickExport MagickBooleanType GetImageDistortion(Image *image,
const Image *reconstruct_image,const MetricType metric,double *distortion,
ExceptionInfo *exception)
{
double
*channel_distortion;
MagickBooleanType
status;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
assert(distortion != (double *) NULL);
*distortion=0.0;
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
/*
Get image distortion.
*/
length=MaxPixelChannels+1;
channel_distortion=(double *) AcquireQuantumMemory(length,
sizeof(*channel_distortion));
if (channel_distortion == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(channel_distortion,0,length*
sizeof(*channel_distortion));
switch (metric)
{
case AbsoluteErrorMetric:
{
status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion,
exception);
break;
}
case FuzzErrorMetric:
{
status=GetFuzzDistortion(image,reconstruct_image,channel_distortion,
exception);
break;
}
case MeanAbsoluteErrorMetric:
{
status=GetMeanAbsoluteDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case MeanErrorPerPixelErrorMetric:
{
status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion,
exception);
break;
}
case MeanSquaredErrorMetric:
{
status=GetMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case NormalizedCrossCorrelationErrorMetric:
default:
{
status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PeakAbsoluteErrorMetric:
{
status=GetPeakAbsoluteDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PeakSignalToNoiseRatioErrorMetric:
{
status=GetPeakSignalToNoiseRatio(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PerceptualHashErrorMetric:
{
status=GetPerceptualHashDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case RootMeanSquaredErrorMetric:
{
status=GetRootMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
}
*distortion=channel_distortion[CompositePixelChannel];
channel_distortion=(double *) RelinquishMagickMemory(channel_distortion);
(void) FormatImageProperty(image,"distortion","%.*g",GetMagickPrecision(),
*distortion);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e D i s t o r t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageDistortions() compares the pixel channels of an image to a
% reconstructed image and returns the specified distortion metric for each
% channel.
%
% The format of the GetImageDistortions method is:
%
% double *GetImageDistortions(const Image *image,
% const Image *reconstruct_image,const MetricType metric,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o metric: the metric.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport double *GetImageDistortions(Image *image,
const Image *reconstruct_image,const MetricType metric,
ExceptionInfo *exception)
{
double
*channel_distortion;
MagickBooleanType
status;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
/*
Get image distortion.
*/
length=MaxPixelChannels+1UL;
channel_distortion=(double *) AcquireQuantumMemory(length,
sizeof(*channel_distortion));
if (channel_distortion == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(channel_distortion,0,length*
sizeof(*channel_distortion));
status=MagickTrue;
switch (metric)
{
case AbsoluteErrorMetric:
{
status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion,
exception);
break;
}
case FuzzErrorMetric:
{
status=GetFuzzDistortion(image,reconstruct_image,channel_distortion,
exception);
break;
}
case MeanAbsoluteErrorMetric:
{
status=GetMeanAbsoluteDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case MeanErrorPerPixelErrorMetric:
{
status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion,
exception);
break;
}
case MeanSquaredErrorMetric:
{
status=GetMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case NormalizedCrossCorrelationErrorMetric:
default:
{
status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PeakAbsoluteErrorMetric:
{
status=GetPeakAbsoluteDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PeakSignalToNoiseRatioErrorMetric:
{
status=GetPeakSignalToNoiseRatio(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PerceptualHashErrorMetric:
{
status=GetRootMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case RootMeanSquaredErrorMetric:
{
status=GetRootMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
}
if (status == MagickFalse)
{
channel_distortion=(double *) RelinquishMagickMemory(channel_distortion);
return((double *) NULL);
}
return(channel_distortion);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s I m a g e s E q u a l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsImagesEqual() compare the pixels of two images and returns immediately
% if any pixel is not identical.
%
% The format of the IsImagesEqual method is:
%
% MagickBooleanType IsImagesEqual(const Image *image,
% const Image *reconstruct_image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType IsImagesEqual(const Image *image,
const Image *reconstruct_image,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
size_t
columns,
rows;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
for (y=0; y < (ssize_t) rows; y++)
{
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) columns; x++)
{
register ssize_t
i;
if (GetPixelWriteMask(image,p) == 0)
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=fabs(p[i]-(double) GetPixelChannel(reconstruct_image,
channel,q));
if (distance >= MagickEpsilon)
break;
}
if (i < (ssize_t) GetPixelChannels(image))
break;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
if (x < (ssize_t) columns)
break;
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
return(y < (ssize_t) rows ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C o l o r M e t r i c %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageColorMetric() measures the difference between colors at each pixel
% location of two images. A value other than 0 means the colors match
% exactly. Otherwise an error measure is computed by summing over all
% pixels in an image the distance squared in RGB space between each image
% pixel and its corresponding pixel in the reconstruct image. The error
% measure is assigned to these image members:
%
% o mean_error_per_pixel: The mean error for any single pixel in
% the image.
%
% o normalized_mean_error: The normalized mean quantization error for
% any single pixel in the image. This distance measure is normalized to
% a range between 0 and 1. It is independent of the range of red, green,
% and blue values in the image.
%
% o normalized_maximum_error: The normalized maximum quantization
% error for any single pixel in the image. This distance measure is
% normalized to a range between 0 and 1. It is independent of the range
% of red, green, and blue values in your image.
%
% A small normalized mean square error, accessed as
% image->normalized_mean_error, suggests the images are very similar in
% spatial layout and color.
%
% The format of the SetImageColorMetric method is:
%
% MagickBooleanType SetImageColorMetric(Image *image,
% const Image *reconstruct_image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageColorMetric(Image *image,
const Image *reconstruct_image,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
area,
maximum_error,
mean_error,
mean_error_per_pixel;
MagickBooleanType
status;
size_t
columns,
rows;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
area=0.0;
maximum_error=0.0;
mean_error_per_pixel=0.0;
mean_error=0.0;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
for (y=0; y < (ssize_t) rows; y++)
{
register const Quantum
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) columns; x++)
{
register ssize_t
i;
if (GetPixelWriteMask(image,p) == 0)
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=fabs(p[i]-(double) GetPixelChannel(reconstruct_image,
channel,q));
if (distance >= MagickEpsilon)
{
mean_error_per_pixel+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
}
area++;
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
image->error.mean_error_per_pixel=(double) (mean_error_per_pixel/area);
image->error.normalized_mean_error=(double) (QuantumScale*QuantumScale*
mean_error/area);
image->error.normalized_maximum_error=(double) (QuantumScale*maximum_error);
status=image->error.mean_error_per_pixel == 0.0 ? MagickTrue : MagickFalse;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S i m i l a r i t y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SimilarityImage() compares the reference image of the image and returns the
% best match offset. In addition, it returns a similarity image such that an
% exact match location is completely white and if none of the pixels match,
% black, otherwise some gray level in-between.
%
% The format of the SimilarityImageImage method is:
%
% Image *SimilarityImage(const Image *image,const Image *reference,
% const MetricType metric,const double similarity_threshold,
% RectangleInfo *offset,double *similarity,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o reference: find an area of the image that closely resembles this image.
%
% o metric: the metric.
%
% o similarity_threshold: minimum distortion for (sub)image match.
%
% o offset: the best match offset of the reference image within the image.
%
% o similarity: the computed similarity between the images.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double GetSimilarityMetric(const Image *image,const Image *reference,
const MetricType metric,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
double
distortion;
Image
*similarity_image;
MagickBooleanType
status;
RectangleInfo
geometry;
SetGeometry(reference,&geometry);
geometry.x=x_offset;
geometry.y=y_offset;
similarity_image=CropImage(image,&geometry,exception);
if (similarity_image == (Image *) NULL)
return(0.0);
distortion=0.0;
status=GetImageDistortion(similarity_image,reference,metric,&distortion,
exception);
similarity_image=DestroyImage(similarity_image);
if (status == MagickFalse)
return(0.0);
return(distortion);
}
MagickExport Image *SimilarityImage(const Image *image,const Image *reference,
const MetricType metric,const double similarity_threshold,
RectangleInfo *offset,double *similarity_metric,ExceptionInfo *exception)
{
#define SimilarityImageTag "Similarity/Image"
CacheView
*similarity_view;
Image
*similarity_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
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);
assert(offset != (RectangleInfo *) NULL);
SetGeometry(reference,offset);
*similarity_metric=MagickMaximumValue;
similarity_image=CloneImage(image,image->columns-reference->columns+1,
image->rows-reference->rows+1,MagickTrue,exception);
if (similarity_image == (Image *) NULL)
return((Image *) NULL);
status=SetImageStorageClass(similarity_image,DirectClass,exception);
if (status == MagickFalse)
{
similarity_image=DestroyImage(similarity_image);
return((Image *) NULL);
}
(void) SetImageAlphaChannel(similarity_image,DeactivateAlphaChannel,
exception);
/*
Measure similarity of reference image against image.
*/
status=MagickTrue;
progress=0;
similarity_view=AcquireAuthenticCacheView(similarity_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) \
shared(progress,status,similarity_metric) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) (image->rows-reference->rows+1); y++)
{
double
similarity;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp flush(similarity_metric)
#endif
if (*similarity_metric <= similarity_threshold)
continue;
q=GetCacheViewAuthenticPixels(similarity_view,0,y,similarity_image->columns,
1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) (image->columns-reference->columns+1); x++)
{
register ssize_t
i;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp flush(similarity_metric)
#endif
if (*similarity_metric <= similarity_threshold)
break;
similarity=GetSimilarityMetric(image,reference,metric,x,y,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SimilarityImage)
#endif
if ((metric == NormalizedCrossCorrelationErrorMetric) ||
(metric == UndefinedErrorMetric))
similarity=1.0-similarity;
if (similarity < *similarity_metric)
{
offset->x=x;
offset->y=y;
*similarity_metric=similarity;
}
if (metric == PerceptualHashErrorMetric)
similarity=MagickMin(0.01*similarity,1.0);
if (GetPixelWriteMask(similarity_image,q) == 0)
{
SetPixelBackgoundColor(similarity_image,q);
q+=GetPixelChannels(similarity_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait similarity_traits=GetPixelChannelTraits(similarity_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(similarity_traits == UndefinedPixelTrait) ||
((similarity_traits & UpdatePixelTrait) == 0))
continue;
SetPixelChannel(similarity_image,channel,ClampToQuantum(QuantumRange-
QuantumRange*similarity),q);
}
q+=GetPixelChannels(similarity_image);
}
if (SyncCacheViewAuthenticPixels(similarity_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SimilarityImage)
#endif
proceed=SetImageProgress(image,SimilarityImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
similarity_view=DestroyCacheView(similarity_view);
if (status == MagickFalse)
similarity_image=DestroyImage(similarity_image);
return(similarity_image);
}
|
GB_unop__log2_fp64_fp64.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__log2_fp64_fp64)
// op(A') function: GB (_unop_tran__log2_fp64_fp64)
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = log2 (aij)
#define GB_ATYPE \
double
#define GB_CTYPE \
double
// 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 = log2 (x) ;
// casting
#define GB_CAST(z, aij) \
double z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = aij ; \
Cx [pC] = log2 (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LOG2 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__log2_fp64_fp64)
(
double *Cx, // Cx and Ax may be aliased
const double *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++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = log2 (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 ;
double aij = Ax [p] ;
double z = aij ;
Cx [p] = log2 (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__log2_fp64_fp64)
(
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
|
for_misc_messages.c | // RUN: %clang_cc1 -fsyntax-only -fopenmp -triple x86_64-unknown-unknown -verify %s
// expected-error@+1 {{unexpected OpenMP directive '#pragma omp for'}}
#pragma omp for
// expected-error@+1 {{unexpected OpenMP directive '#pragma omp for'}}
#pragma omp for foo
void test_no_clause() {
int i;
#pragma omp for
for (i = 0; i < 16; ++i)
;
// expected-error@+2 {{statement after '#pragma omp for' must be a for loop}}
#pragma omp for
++i;
}
void test_branch_protected_scope() {
int i = 0;
L1:
++i;
int x[24];
#pragma omp parallel
#pragma omp for
for (i = 0; i < 16; ++i) {
if (i == 5)
goto L1; // expected-error {{use of undeclared label 'L1'}}
else if (i == 6)
return; // expected-error {{cannot return from OpenMP region}}
else if (i == 7)
goto L2;
else if (i == 8) {
L2:
x[i]++;
}
}
if (x[0] == 0)
goto L2; // expected-error {{use of undeclared label 'L2'}}
else if (x[1] == 1)
goto L1;
}
void test_invalid_clause() {
int i;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for foo bar
for (i = 0; i < 16; ++i)
;
}
void test_non_identifiers() {
int i, x;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for;
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{unexpected OpenMP clause 'linear' in directive '#pragma omp for'}}
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for linear(x);
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for private(x);
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for, private(x);
for (i = 0; i < 16; ++i)
;
}
extern int foo();
void test_collapse() {
int i;
#pragma omp parallel
// expected-error@+1 {{expected '('}}
#pragma omp for collapse
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp for collapse(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for collapse()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp for collapse(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp for collapse(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-warning@+2 {{extra tokens at the end of '#pragma omp for' are ignored}}
// expected-error@+1 {{expected '('}}
#pragma omp for collapse 4)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4,
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4, )
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4 4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4, , 4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
#pragma omp for collapse(4)
for (int i1 = 0; i1 < 16; ++i1)
for (int i2 = 0; i2 < 16; ++i2)
for (int i3 = 0; i3 < 16; ++i3)
for (int i4 = 0; i4 < 16; ++i4)
foo();
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4, 8)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+1 {{expression is not an integer constant expression}}
#pragma omp for collapse(2.5)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expression is not an integer constant expression}}
#pragma omp for collapse(foo())
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp for collapse(-5)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp for collapse(0)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp for collapse(5 - 5)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for collapse(2)
for (i = 0; i < 16; ++i)
// expected-note@+1 {{variable with automatic storage duration is predetermined as private; perhaps you forget to enclose 'omp for' directive into a parallel or another task region?}}
for (int j = 0; j < 16; ++j)
// expected-error@+2 {{private variable cannot be reduction}}
// expected-error@+1 {{region cannot be closely nested inside 'for' region; perhaps you forget to enclose 'omp for' directive into a parallel region?}}
#pragma omp for reduction(+ : i, j)
for (int k = 0; k < 16; ++k)
i += j;
}
void test_private() {
int i;
#pragma omp parallel
// expected-error@+2 {{expected expression}}
// expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp for private(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp for private(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 2 {{expected expression}}
#pragma omp for private(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for private()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for private(int)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected variable name}}
#pragma omp for private(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp parallel
#pragma omp for private(x)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for private(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for private(x, y, z)
for (i = 0; i < 16; ++i) {
x = y * i + z;
}
}
void test_lastprivate() {
int i;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 {{expected expression}}
#pragma omp for lastprivate(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp for lastprivate(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 2 {{expected expression}}
#pragma omp for lastprivate(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for lastprivate()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for lastprivate(int)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected variable name}}
#pragma omp for lastprivate(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp parallel
#pragma omp for lastprivate(x)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for lastprivate(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for lastprivate(x, y, z)
for (i = 0; i < 16; ++i)
;
}
void test_firstprivate() {
int i;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 {{expected expression}}
#pragma omp for firstprivate(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp for firstprivate(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 2 {{expected expression}}
#pragma omp for firstprivate(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for firstprivate()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for firstprivate(int)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected variable name}}
#pragma omp for firstprivate(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp parallel
#pragma omp for lastprivate(x) firstprivate(x)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for lastprivate(x, y) firstprivate(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for lastprivate(x, y, z) firstprivate(x, y, z)
for (i = 0; i < 16; ++i)
;
}
void test_loop_messages() {
float a[100], b[100], c[100];
#pragma omp parallel
// expected-error@+2 {{variable must be of integer or pointer type}}
#pragma omp for
for (float fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
#pragma omp parallel
// expected-error@+2 {{variable must be of integer or pointer type}}
#pragma omp for
for (double fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
// expected-warning@+2 {{OpenMP loop iteration variable cannot have more than 64 bits size and will be narrowed}}
#pragma omp for
for (__int128 ii = 0; ii < 10; ii++) {
c[ii] = a[ii] + b[ii];
}
}
|
actionAngleStaeckel.c | /*
C code for Binney (2012)'s Staeckel approximation code
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_integration.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#define CHUNKSIZE 10
//Potentials
#include <galpy_potentials.h>
#include <actionAngle.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
/*
Structure Declarations
*/
struct JRStaeckelArg{
double E;
double Lz22delta;
double I3U;
double delta;
double u0;
double sinh2u0;
double v0;
double sin2v0;
double potu0v0;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct JzStaeckelArg{
double E;
double Lz22delta;
double I3V;
double delta;
double u0;
double cosh2u0;
double sinh2u0;
double potupi2;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct dJRStaeckelArg{
double E;
double Lz22delta;
double I3U;
double delta;
double u0;
double sinh2u0;
double v0;
double sin2v0;
double potu0v0;
double umin;
double umax;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct dJzStaeckelArg{
double E;
double Lz22delta;
double I3V;
double delta;
double u0;
double cosh2u0;
double sinh2u0;
double potupi2;
double vmin;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct u0EqArg{
double E;
double Lz22delta;
double delta;
int nargs;
struct potentialArg * actionAngleArgs;
};
/*
Function Declarations
*/
void calcu0(int,double *,double *,int,int *,double *,double,double *,int *);
void actionAngleStaeckel_actions(int,double *,double *,double *,double *,
double *,double *,int,int *,double *,double,
double *,double *,int *);
void actionAngleStaeckel_actionsFreqsAngles(int,double *,double *,double *,
double *,double *,double *,
int,int *,double *,
double,double *,double *,double *,
double *,double *,double *,
double *,double *,int *);
void actionAngleStaeckel_actionsFreqs(int,double *,double *,double *,double *,
double *,double *,int,int *,double *,
double,double *,double *,double *,
double *,double *,int *);
void calcAnglesStaeckel(int,double *,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
double *,double,double *,double *,double *,double *,
double *,double *,double *,double *,double *,int,
struct potentialArg *,int);
void calcFreqsFromDerivsStaeckel(int,double *,double *,double *,
double *,double *,double *,
double *,double *,double *,double *);
void calcdI3dJFromDerivsStaeckel(int,double *,double *,double *,double *,
double *,double *,double *,double *);
void calcJRStaeckel(int,double *,double *,double *,double *,double *,double *,
double,double *,double *,double *,double *,double *,int,
struct potentialArg *,int);
void calcJzStaeckel(int,double *,double *,double *,double *,double *,double,
double *,double *,double *,double *,int,
struct potentialArg *,int);
void calcdJRStaeckel(int,double *,double *,double *,double *,double *,
double *,double *,double *,
double,double *,double *,double *,double *,double *,int,
struct potentialArg *,int);
void calcdJzStaeckel(int,double *,double *,double *,double *,double *,
double *,double *,double,double *,double *,double *,
double *,int,
struct potentialArg *,int);
void calcUminUmax(int,double *,double *,double *,double *,double *,double *,
double *,double,double *,double *,double *,double *,double *,
int,struct potentialArg *);
void calcVmin(int,double *,double *,double *,double *,double *,double *,double,
double *,double *,double *,double *,int,struct potentialArg *);
double JRStaeckelIntegrandSquared(double,void *);
double JRStaeckelIntegrand(double,void *);
double JzStaeckelIntegrandSquared(double,void *);
double JzStaeckelIntegrand(double,void *);
double dJRdEStaeckelIntegrand(double,void *);
double dJRdELowStaeckelIntegrand(double,void *);
double dJRdEHighStaeckelIntegrand(double,void *);
double dJRdLzStaeckelIntegrand(double,void *);
double dJRdLzLowStaeckelIntegrand(double,void *);
double dJRdLzHighStaeckelIntegrand(double,void *);
double dJRdI3StaeckelIntegrand(double,void *);
double dJRdI3LowStaeckelIntegrand(double,void *);
double dJRdI3HighStaeckelIntegrand(double,void *);
double dJzdEStaeckelIntegrand(double,void *);
double dJzdELowStaeckelIntegrand(double,void *);
double dJzdEHighStaeckelIntegrand(double,void *);
double dJzdLzStaeckelIntegrand(double,void *);
double dJzdLzLowStaeckelIntegrand(double,void *);
double dJzdLzHighStaeckelIntegrand(double,void *);
double dJzdI3StaeckelIntegrand(double,void *);
double dJzdI3LowStaeckelIntegrand(double,void *);
double dJzdI3HighStaeckelIntegrand(double,void *);
double u0Equation(double,void *);
double evaluatePotentials(double,double,int, struct potentialArg *);
double evaluatePotentialsUV(double,double,double,int,struct potentialArg *);
/*
Actual functions, inlines first
*/
inline void uv_to_Rz(double u, double v, double * R, double *z,double delta){
*R= delta * sinh(u) * sin(v);
*z= delta * cosh(u) * cos(v);
}
inline void Rz_to_uv_vec(int ndata,
double *R,
double *z,
double *u,
double *v,
double delta){
int ii;
double d12, d22, coshu, cosv;
for (ii=0; ii < ndata; ii++) {
d12= (*(z+ii)+delta)*(*(z+ii)+delta)+(*(R+ii))*(*(R+ii));
d22= (*(z+ii)-delta)*(*(z+ii)-delta)+(*(R+ii))*(*(R+ii));
coshu= 0.5/delta*(sqrt(d12)+sqrt(d22));
cosv= 0.5/delta*(sqrt(d12)-sqrt(d22));
*u++= acosh(coshu);
*v++= acos(cosv);
}
u-= ndata;
v-= ndata;
}
inline void calcEL(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *E,
double *Lz,
int nargs,
struct potentialArg * actionAngleArgs){
int ii;
for (ii=0; ii < ndata; ii++){
*(E+ii)= evaluatePotentials(*(R+ii),*(z+ii),
nargs,actionAngleArgs)
+ 0.5 * *(vR+ii) * *(vR+ii)
+ 0.5 * *(vT+ii) * *(vT+ii)
+ 0.5 * *(vz+ii) * *(vz+ii);
*(Lz+ii)= *(R+ii) * *(vT+ii);
}
}
/*
MAIN FUNCTIONS
*/
void calcu0(int ndata,
double *E,
double *Lz,
int npot,
int * pot_type,
double * pot_args,
double delta,
double *u0,
int * err){
int ii;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_actionAngleArgs(npot,actionAngleArgs,pot_type,pot_args);
//setup the function to be minimized
gsl_function u0Eq;
struct u0EqArg * params= (struct u0EqArg *) malloc ( sizeof (struct u0EqArg) );
params->delta= delta;
params->nargs= npot;
params->actionAngleArgs= actionAngleArgs;
//Setup solver
int status;
int iter, max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double u_guess, u_lo, u_hi;
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc (T);
u0Eq.function = &u0Equation;
for (ii=0; ii < ndata; ii++){
//Setup function
params->E= *(E+ii);
params->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta;
u0Eq.params = params;
//Find starting points for minimum
u_guess= 1.;
u_lo= 0.001;
u_hi= 100.;
gsl_set_error_handler_off();
status = gsl_min_fminimizer_set (s, &u0Eq, u_guess, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(u0+ii)= u_hi;
gsl_set_error_handler (NULL);
continue;
}
gsl_set_error_handler (NULL);
iter= 0;
do
{
iter++;
status = gsl_min_fminimizer_iterate (s);
u_guess = gsl_min_fminimizer_x_minimum (s);
u_lo = gsl_min_fminimizer_x_lower (s);
u_hi = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
*(u0+ii)= gsl_min_fminimizer_x_minimum (s);
}
gsl_min_fminimizer_free (s);
free(params);
for (ii=0; ii < npot; ii++) {
if ( (actionAngleArgs+ii)->i2d )
interp_2d_free((actionAngleArgs+ii)->i2d) ;
if ((actionAngleArgs+ii)->accx )
gsl_interp_accel_free ((actionAngleArgs+ii)->accx);
if ((actionAngleArgs+ii)->accy )
gsl_interp_accel_free ((actionAngleArgs+ii)->accy);
free((actionAngleArgs+ii)->args);
}
free(actionAngleArgs);
*err= status;
}
void actionAngleStaeckel_actions(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
double delta,
double *jr,
double *jz,
int * err){
int ii;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_actionAngleArgs(npot,actionAngleArgs,pot_type,pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii)
for (ii=0; ii < ndata; ii++){
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= delta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= delta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),delta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / delta / delta
- 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),delta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,delta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / delta / delta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),delta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
double *umin= (double *) malloc ( ndata * sizeof(double) );
double *umax= (double *) malloc ( ndata * sizeof(double) );
double *vmin= (double *) malloc ( ndata * sizeof(double) );
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Calculate the actions
calcJRStaeckel(ndata,jr,umin,umax,E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,10);
calcJzStaeckel(ndata,jz,vmin,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs,10);
//Free
for (ii=0; ii < npot; ii++) {
if ( (actionAngleArgs+ii)->i2d )
interp_2d_free((actionAngleArgs+ii)->i2d) ;
if ((actionAngleArgs+ii)->accx )
gsl_interp_accel_free ((actionAngleArgs+ii)->accx);
if ((actionAngleArgs+ii)->accy )
gsl_interp_accel_free ((actionAngleArgs+ii)->accy);
free((actionAngleArgs+ii)->args);
}
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
free(umin);
free(umax);
free(vmin);
}
void calcJRStaeckel(int ndata,
double * jr,
double * umin,
double * umax,
double * E,
double * Lz,
double * I3U,
double delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * JRInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JRStaeckelArg * params= (struct JRStaeckelArg *) malloc ( nthreads * sizeof (struct JRStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->delta= delta;
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii) \
shared(jr,umin,umax,JRInt,params,T,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(umin+ii) == -9999.99 || *(umax+ii) == -9999.99 ){
*(jr+ii)= 9999.99;
continue;
}
if ( (*(umax+ii) - *(umin+ii)) / *(umax+ii) < 0.000001 ){//circular
*(jr+ii) = 0.;
continue;
}
//Setup function
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta;
(params+tid)->I3U= *(I3U+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->v0= *(v0+ii);
(params+tid)->sin2v0= *(sin2v0+ii);
(params+tid)->potu0v0= *(potu0v0+ii);
(JRInt+tid)->function = &JRStaeckelIntegrand;
(JRInt+tid)->params = params+tid;
//Integrate
*(jr+ii)= gsl_integration_glfixed (JRInt+tid,*(umin+ii),*(umax+ii),T)
* sqrt(2.) * delta / M_PI;
}
free(JRInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void calcJzStaeckel(int ndata,
double * jz,
double * vmin,
double * E,
double * Lz,
double * I3V,
double delta,
double * u0,
double * cosh2u0,
double * sinh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * JzInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JzStaeckelArg * params= (struct JzStaeckelArg *) malloc ( nthreads * sizeof (struct JzStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->delta= delta;
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii) \
shared(jz,vmin,JzInt,params,T,delta,E,Lz,I3V,u0,cosh2u0,sinh2u0,potupi2)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(vmin+ii) == -9999.99 ){
*(jz+ii)= 9999.99;
continue;
}
if ( (0.5 * M_PI - *(vmin+ii)) / M_PI * 2. < 0.000001 ){//circular
*(jz+ii) = 0.;
continue;
}
//Setup function
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta;
(params+tid)->I3V= *(I3V+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->cosh2u0= *(cosh2u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->potupi2= *(potupi2+ii);
(JzInt+tid)->function = &JzStaeckelIntegrand;
(JzInt+tid)->params = params+tid;
//Integrate
*(jz+ii)= gsl_integration_glfixed (JzInt+tid,*(vmin+ii),M_PI/2.,T)
* 2 * sqrt(2.) * delta / M_PI;
}
free(JzInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void actionAngleStaeckel_actionsFreqs(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
double delta,
double *jr,
double *jz,
double *Omegar,
double *Omegaphi,
double *Omegaz,
int * err){
int ii;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_actionAngleArgs(npot,actionAngleArgs,pot_type,pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii)
for (ii=0; ii < ndata; ii++){
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= delta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= delta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),delta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / delta / delta
- 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),delta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,delta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / delta / delta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),delta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
double *umin= (double *) malloc ( ndata * sizeof(double) );
double *umax= (double *) malloc ( ndata * sizeof(double) );
double *vmin= (double *) malloc ( ndata * sizeof(double) );
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Calculate the actions
calcJRStaeckel(ndata,jr,umin,umax,E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,10);
calcJzStaeckel(ndata,jz,vmin,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs,10);
//Calculate the derivatives of the actions wrt the integrals of motion
double *dJRdE= (double *) malloc ( ndata * sizeof(double) );
double *dJRdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJRdI3= (double *) malloc ( ndata * sizeof(double) );
double *dJzdE= (double *) malloc ( ndata * sizeof(double) );
double *dJzdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJzdI3= (double *) malloc ( ndata * sizeof(double) );
double *detA= (double *) malloc ( ndata * sizeof(double) );
calcdJRStaeckel(ndata,dJRdE,dJRdLz,dJRdI3,
umin,umax,E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,10);
calcdJzStaeckel(ndata,dJzdE,dJzdLz,dJzdI3,
vmin,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,10);
calcFreqsFromDerivsStaeckel(ndata,Omegar,Omegaphi,Omegaz,detA,
dJRdE,dJRdLz,dJRdI3,
dJzdE,dJzdLz,dJzdI3);
//Free
for (ii=0; ii < npot; ii++) {
if ( (actionAngleArgs+ii)->i2d )
interp_2d_free((actionAngleArgs+ii)->i2d) ;
if ((actionAngleArgs+ii)->accx )
gsl_interp_accel_free ((actionAngleArgs+ii)->accx);
if ((actionAngleArgs+ii)->accy )
gsl_interp_accel_free ((actionAngleArgs+ii)->accy);
free((actionAngleArgs+ii)->args);
}
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
free(umin);
free(umax);
free(vmin);
free(dJRdE);
free(dJRdLz);
free(dJRdI3);
free(dJzdE);
free(detA);
free(dJzdLz);
free(dJzdI3);
}
void actionAngleStaeckel_actionsFreqsAngles(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
double delta,
double *jr,
double *jz,
double *Omegar,
double *Omegaphi,
double *Omegaz,
double *Angler,
double *Anglephi,
double *Anglez,
int * err){
int ii;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_actionAngleArgs(npot,actionAngleArgs,pot_type,pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii)
for (ii=0; ii < ndata; ii++){
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= delta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= delta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),delta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / delta / delta
- 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),delta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,delta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / delta / delta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),delta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
double *umin= (double *) malloc ( ndata * sizeof(double) );
double *umax= (double *) malloc ( ndata * sizeof(double) );
double *vmin= (double *) malloc ( ndata * sizeof(double) );
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Calculate the actions
calcJRStaeckel(ndata,jr,umin,umax,E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,10);
calcJzStaeckel(ndata,jz,vmin,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs,10);
//Calculate the derivatives of the actions wrt the integrals of motion
double *dJRdE= (double *) malloc ( ndata * sizeof(double) );
double *dJRdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJRdI3= (double *) malloc ( ndata * sizeof(double) );
double *dJzdE= (double *) malloc ( ndata * sizeof(double) );
double *dJzdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJzdI3= (double *) malloc ( ndata * sizeof(double) );
double *detA= (double *) malloc ( ndata * sizeof(double) );
calcdJRStaeckel(ndata,dJRdE,dJRdLz,dJRdI3,
umin,umax,E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,10);
calcdJzStaeckel(ndata,dJzdE,dJzdLz,dJzdI3,
vmin,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,10);
calcFreqsFromDerivsStaeckel(ndata,Omegar,Omegaphi,Omegaz,detA,
dJRdE,dJRdLz,dJRdI3,
dJzdE,dJzdLz,dJzdI3);
double *dI3dJR= (double *) malloc ( ndata * sizeof(double) );
double *dI3dJz= (double *) malloc ( ndata * sizeof(double) );
double *dI3dLz= (double *) malloc ( ndata * sizeof(double) );
calcdI3dJFromDerivsStaeckel(ndata,dI3dJR,dI3dJz,dI3dLz,detA,
dJRdE,dJzdE,dJRdLz,dJzdLz);
calcAnglesStaeckel(ndata,Angler,Anglephi,Anglez,
Omegar,Omegaphi,Omegaz,dI3dJR,dI3dJz,dI3dLz,
dJRdE,dJRdLz,dJRdI3,
dJzdE,dJzdLz,dJzdI3,
ux,vx,pux,pvx,
umin,umax,E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,
vmin,I3V,cosh2u0,potupi2,
npot,actionAngleArgs,10);
//Free
for (ii=0; ii < npot; ii++) {
if ( (actionAngleArgs+ii)->i2d )
interp_2d_free((actionAngleArgs+ii)->i2d) ;
if ((actionAngleArgs+ii)->accx )
gsl_interp_accel_free ((actionAngleArgs+ii)->accx);
if ((actionAngleArgs+ii)->accy )
gsl_interp_accel_free ((actionAngleArgs+ii)->accy);
free((actionAngleArgs+ii)->args);
}
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
free(umin);
free(umax);
free(vmin);
free(dJRdE);
free(dJRdLz);
free(dJRdI3);
free(dJzdE);
free(dJzdLz);
free(dJzdI3);
free(detA);
free(dI3dJR);
free(dI3dJz);
}
void calcFreqsFromDerivsStaeckel(int ndata,
double * Omegar,
double * Omegaphi,
double * Omegaz,
double * detA,
double * djrdE,
double * djrdLz,
double * djrdI3,
double * djzdE,
double * djzdLz,
double * djzdI3){
int ii;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(ii) \
shared(Omegar,Omegaphi,Omegaz,djrdE,djrdLz,djrdI3,djzdE,djzdLz,djzdI3,detA)
for (ii=0; ii < ndata; ii++){
if ( *(djrdE+ii) == 9999.99 || *(djzdE+ii) == 9999.99 ) {
*(Omegar+ii)= 9999.99;
*(Omegaz+ii)= 9999.99;
*(Omegaphi+ii)= 9999.99;
} else {
//First calculate the determinant of the relevant matrix
*(detA+ii)= *(djrdE+ii) * *(djzdI3+ii) - *(djzdE+ii) * *(djrdI3+ii);
//Then calculate the frequencies
*(Omegar+ii)= *(djzdI3+ii) / *(detA+ii);
*(Omegaz+ii)= - *(djrdI3+ii) / *(detA+ii);
*(Omegaphi+ii)= ( *(djrdI3+ii) * *(djzdLz+ii) - *(djzdI3+ii) * *(djrdLz+ii)) / *(detA+ii);
}
}
}
void calcdI3dJFromDerivsStaeckel(int ndata,
double * dI3dJR,
double * dI3dJz,
double * dI3dLz,
double * detA,
double * djrdE,
double * djzdE,
double * djrdLz,
double * djzdLz){
int ii;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(ii) \
shared(djrdE,djzdE,djrdLz,djzdLz,dI3dJR,dI3dJz,dI3dLz,detA)
for (ii=0; ii < ndata; ii++){
*(dI3dJR+ii)= - *(djzdE+ii) / *(detA+ii);
*(dI3dJz+ii)= *(djrdE+ii) / *(detA+ii);
*(dI3dLz+ii)= -( *(djrdE+ii) * *(djzdLz+ii) - *(djzdE+ii) * *(djrdLz+ii) ) / *(detA+ii);
}
}
void calcdJRStaeckel(int ndata,
double * djrdE,
double * djrdLz,
double * djrdI3,
double * umin,
double * umax,
double * E,
double * Lz,
double * I3U,
double delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
double mid;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * dJRInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) malloc ( nthreads * sizeof (struct dJRStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->delta= delta;
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,mid) \
shared(djrdE,djrdLz,djrdI3,umin,umax,dJRInt,params,T,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(umin+ii) == -9999.99 || *(umax+ii) == -9999.99 ){
*(djrdE+ii)= 9999.99;
*(djrdLz+ii)= 9999.99;
*(djrdI3+ii)= 9999.99;
continue;
}
if ( (*(umax+ii) - *(umin+ii)) / *(umax+ii) < 0.000001 ){//circular
*(djrdE+ii) = 0.;
*(djrdLz+ii) = 0.;
*(djrdI3+ii) = 0.;
continue;
}
//Setup function
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta;
(params+tid)->I3U= *(I3U+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->v0= *(v0+ii);
(params+tid)->sin2v0= *(sin2v0+ii);
(params+tid)->potu0v0= *(potu0v0+ii);
(params+tid)->umin= *(umin+ii);
(params+tid)->umax= *(umax+ii);
(dJRInt+tid)->function = &dJRdELowStaeckelIntegrand;
(dJRInt+tid)->params = params+tid;
mid= sqrt( 0.5 * ( *(umax+ii) - *(umin+ii) ) );
//Integrate to get djrdE
*(djrdE+ii)= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
(dJRInt+tid)->function = &dJRdEHighStaeckelIntegrand;
*(djrdE+ii)+= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
*(djrdE+ii)*= delta / M_PI / sqrt(2.);
//then calculate djrdLz
(dJRInt+tid)->function = &dJRdLzLowStaeckelIntegrand;
*(djrdLz+ii)= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
(dJRInt+tid)->function = &dJRdLzHighStaeckelIntegrand;
*(djrdLz+ii)+= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
*(djrdLz+ii)*= - *(Lz+ii) / M_PI / sqrt(2.) / delta;
//then calculate djrdI3
(dJRInt+tid)->function = &dJRdI3LowStaeckelIntegrand;
*(djrdI3+ii)= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
(dJRInt+tid)->function = &dJRdI3HighStaeckelIntegrand;
*(djrdI3+ii)+= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
*(djrdI3+ii)*= -delta / M_PI / sqrt(2.);
}
free(dJRInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void calcdJzStaeckel(int ndata,
double * djzdE,
double * djzdLz,
double * djzdI3,
double * vmin,
double * E,
double * Lz,
double * I3V,
double delta,
double * u0,
double * cosh2u0,
double * sinh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
double mid;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * dJzInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) malloc ( nthreads * sizeof (struct dJzStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->delta= delta;
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,mid) \
shared(djzdE,djzdLz,djzdI3,vmin,dJzInt,params,T,delta,E,Lz,I3V,u0,cosh2u0,sinh2u0,potupi2)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(vmin+ii) == -9999.99 ){
*(djzdE+ii)= 9999.99;
*(djzdLz+ii)= 9999.99;
*(djzdI3+ii)= 9999.99;
continue;
}
if ( (0.5 * M_PI - *(vmin+ii)) / M_PI * 2. < 0.000001 ){//circular
*(djzdE+ii) = 0.;
*(djzdLz+ii) = 0.;
*(djzdI3+ii) = 0.;
continue;
}
//Setup function
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta;
(params+tid)->I3V= *(I3V+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->cosh2u0= *(cosh2u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->potupi2= *(potupi2+ii);
(params+tid)->vmin= *(vmin+ii);
//First calculate dJzdE
(dJzInt+tid)->function = &dJzdELowStaeckelIntegrand;
(dJzInt+tid)->params = params+tid;
mid= sqrt( 0.5 * (M_PI/2. - *(vmin+ii) ) );
//BOVY: pv does not vanish at pi/2, so no need to break up the integral
//Integrate
*(djzdE+ii)= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
(dJzInt+tid)->function = &dJzdEHighStaeckelIntegrand;
*(djzdE+ii)+= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
*(djzdE+ii)*= sqrt(2.) * delta / M_PI;
//Then calculate dJzdLz
(dJzInt+tid)->function = &dJzdLzLowStaeckelIntegrand;
//Integrate
*(djzdLz+ii)= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
(dJzInt+tid)->function = &dJzdLzHighStaeckelIntegrand;
*(djzdLz+ii)+= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
*(djzdLz+ii)*= - *(Lz+ii) * sqrt(2.) / M_PI / delta;
//Then calculate dJzdI3
(dJzInt+tid)->function = &dJzdI3LowStaeckelIntegrand;
//Integrate
*(djzdI3+ii)= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
(dJzInt+tid)->function = &dJzdI3HighStaeckelIntegrand;
*(djzdI3+ii)+= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
*(djzdI3+ii)*= sqrt(2.) * delta / M_PI;
}
free(dJzInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void calcAnglesStaeckel(int ndata,
double * Angler,
double * Anglephi,
double * Anglez,
double * Omegar,
double * Omegaphi,
double * Omegaz,
double * dI3dJR,
double * dI3dJz,
double * dI3dLz,
double * dJRdE,
double * dJRdLz,
double * dJRdI3,
double * dJzdE,
double * dJzdLz,
double * dJzdI3,
double * ux,
double * vx,
double * pux,
double * pvx,
double * umin,
double * umax,
double * E,
double * Lz,
double * I3U,
double delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
double * vmin,
double * I3V,
double * cosh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
double Or1, Or2, I3r1, I3r2,phitmp;
double mid, midpoint;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * AngleuInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
gsl_function * AnglevInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct dJRStaeckelArg * paramsu= (struct dJRStaeckelArg *) malloc ( nthreads * sizeof (struct dJRStaeckelArg) );
struct dJzStaeckelArg * paramsv= (struct dJzStaeckelArg *) malloc ( nthreads * sizeof (struct dJzStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(paramsu+tid)->delta= delta;
(paramsu+tid)->nargs= nargs;
(paramsu+tid)->actionAngleArgs= actionAngleArgs;
(paramsv+tid)->delta= delta;
(paramsv+tid)->nargs= nargs;
(paramsv+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,mid,midpoint,Or1,Or2,I3r1,I3r2,phitmp) \
shared(Angler,Anglephi,Anglez,Omegar,Omegaz,dI3dJR,dI3dJz,umin,umax,AngleuInt,AnglevInt,paramsu,paramsv,T,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0,vmin,I3V,cosh2u0,potupi2)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(umin+ii) == -9999.99 || *(umax+ii) == -9999.99 ){
*(Angler+ii)= 9999.99;
*(Anglephi+ii)= 9999.99;
*(Anglez+ii)= 9999.99;
continue;
}
if ( (*(umax+ii) - *(umin+ii)) / *(umax+ii) < 0.000001 ){//circular
*(Angler+ii) = 0.;
*(Anglephi+ii) = 0.;
*(Anglez+ii) = 0.;
continue;
}
//Setup u function
(paramsu+tid)->E= *(E+ii);
(paramsu+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta;
(paramsu+tid)->I3U= *(I3U+ii);
(paramsu+tid)->u0= *(u0+ii);
(paramsu+tid)->sinh2u0= *(sinh2u0+ii);
(paramsu+tid)->v0= *(v0+ii);
(paramsu+tid)->sin2v0= *(sin2v0+ii);
(paramsu+tid)->potu0v0= *(potu0v0+ii);
(paramsu+tid)->umin= *(umin+ii);
(paramsu+tid)->umax= *(umax+ii);
(AngleuInt+tid)->params = paramsu+tid;
midpoint= *(umin+ii)+ 0.5 * ( *(umax+ii) - *(umin+ii) );
if ( *(pux+ii) > 0. ) {
if ( *(ux+ii) > midpoint ) {
mid= sqrt( ( *(umax+ii) - *(ux+ii) ) );
(AngleuInt+tid)->function = &dJRdEHighStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdI3HighStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdLzHighStaeckelIntegrand;
*(Anglephi+ii)= M_PI * *(dJRdLz+ii) + *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / delta / sqrt(2.);
Or1*= delta / sqrt(2.);
I3r1*= delta / sqrt(2.);
Or1= M_PI * *(dJRdE+ii) - Or1;
I3r1= M_PI * *(dJRdI3+ii) - I3r1;
}
else {
mid= sqrt( ( *(ux+ii) - *(umin+ii) ) );
(AngleuInt+tid)->function = &dJRdELowStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdI3LowStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdLzLowStaeckelIntegrand;
*(Anglephi+ii)= - *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / delta / sqrt(2.);
Or1*= delta / sqrt(2.);
I3r1*= delta / sqrt(2.);
}
}
else {
if ( *(ux+ii) > midpoint ) {
mid= sqrt( ( *(umax+ii) - *(ux+ii) ) );
(AngleuInt+tid)->function = &dJRdEHighStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
Or1*= delta / sqrt(2.);
Or1= M_PI * *(dJRdE+ii) + Or1;
(AngleuInt+tid)->function = &dJRdI3HighStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
I3r1*= delta / sqrt(2.);
I3r1= M_PI * *(dJRdI3+ii) + I3r1;
(AngleuInt+tid)->function = &dJRdLzHighStaeckelIntegrand;
*(Anglephi+ii)= M_PI * *(dJRdLz+ii) - *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / delta / sqrt(2.);
}
else {
mid= sqrt( ( *(ux+ii) - *(umin+ii) ) );
(AngleuInt+tid)->function = &dJRdELowStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
Or1*= delta / sqrt(2.);
Or1= 2. * M_PI * *(dJRdE+ii) - Or1;
(AngleuInt+tid)->function = &dJRdI3LowStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
I3r1*= delta / sqrt(2.);
I3r1= 2. * M_PI * *(dJRdI3+ii) - I3r1;
(AngleuInt+tid)->function = &dJRdLzLowStaeckelIntegrand;
*(Anglephi+ii)= 2. * M_PI * *(dJRdLz+ii) + *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / delta / sqrt(2.);
}
}
//Setup v function
(paramsv+tid)->E= *(E+ii);
(paramsv+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta;
(paramsv+tid)->I3V= *(I3V+ii);
(paramsv+tid)->u0= *(u0+ii);
(paramsv+tid)->cosh2u0= *(cosh2u0+ii);
(paramsv+tid)->sinh2u0= *(sinh2u0+ii);
(paramsv+tid)->potupi2= *(potupi2+ii);
(paramsv+tid)->vmin= *(vmin+ii);
(AnglevInt+tid)->params = paramsv+tid;
midpoint= *(vmin+ii)+ 0.5 * ( 0.5 * M_PI - *(vmin+ii) );
if ( *(pvx+ii) > 0. ) {
if ( *(vx+ii) < midpoint || *(vx+ii) > (M_PI - midpoint) ) {
mid = ( *(vx+ii) > 0.5 * M_PI ) ? sqrt( (M_PI - *(vx+ii) - *(vmin+ii))): sqrt( *(vx+ii) - *(vmin+ii));
(AnglevInt+tid)->function = &dJzdELowStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= delta / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3LowStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= delta / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzLowStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / delta / sqrt(2.);
if ( *(vx+ii) > 0.5 * M_PI ) {
Or2= M_PI * *(dJzdE+ii) - Or2;
I3r2= M_PI * *(dJzdI3+ii) - I3r2;
phitmp= M_PI * *(dJzdLz+ii) - phitmp;
}
}
else {
mid= sqrt( fabs ( 0.5 * M_PI - *(vx+ii) ) );
(AnglevInt+tid)->function = &dJzdEHighStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= delta / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3HighStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= delta / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzHighStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / delta / sqrt(2.);
if ( *(vx+ii) > 0.5 * M_PI ) {
Or2= 0.5 * M_PI * *(dJzdE+ii) + Or2;
I3r2= 0.5 * M_PI * *(dJzdI3+ii) + I3r2;
phitmp= 0.5 * M_PI * *(dJzdLz+ii) + phitmp;
}
else {
Or2= 0.5 * M_PI * *(dJzdE+ii) - Or2;
I3r2= 0.5 * M_PI * *(dJzdI3+ii) - I3r2;
phitmp= 0.5 * M_PI * *(dJzdLz+ii) - phitmp;
}
}
}
else {
if ( *(vx+ii) < midpoint || *(vx+ii) > (M_PI - midpoint)) {
mid = ( *(vx+ii) > 0.5 * M_PI ) ? sqrt( (M_PI - *(vx+ii) - *(vmin+ii))): sqrt( *(vx+ii) - *(vmin+ii));
(AnglevInt+tid)->function = &dJzdELowStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= delta / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3LowStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= delta / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzLowStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / delta / sqrt(2.);
if ( *(vx+ii) < 0.5 * M_PI ) {
Or2= 2. * M_PI * *(dJzdE+ii) - Or2;
I3r2= 2. * M_PI * *(dJzdI3+ii) - I3r2;
phitmp= 2. * M_PI * *(dJzdLz+ii) - phitmp;
}
else {
Or2= M_PI * *(dJzdE+ii) + Or2;
I3r2= M_PI * *(dJzdI3+ii) + I3r2;
phitmp= M_PI * *(dJzdLz+ii) + phitmp;
}
}
else {
mid= sqrt( fabs ( 0.5 * M_PI - *(vx+ii) ) );
(AnglevInt+tid)->function = &dJzdEHighStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= delta / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3HighStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= delta / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzHighStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / delta / sqrt(2.);
if ( *(vx+ii) < 0.5 * M_PI ) {
Or2= 1.5 * M_PI * *(dJzdE+ii) + Or2;
I3r2= 1.5 * M_PI * *(dJzdI3+ii) + I3r2;
phitmp= 1.5 * M_PI * *(dJzdLz+ii) + phitmp;
}
else {
Or2= 1.5 * M_PI * *(dJzdE+ii) - Or2;
I3r2= 1.5 * M_PI * *(dJzdI3+ii) - I3r2;
phitmp= 1.5 * M_PI * *(dJzdLz+ii) - phitmp;
}
}
}
*(Angler+ii)= *(Omegar+ii) * ( Or1 + Or2 )
+ *(dI3dJR+ii) * ( I3r1 + I3r2 );
// In Binney (2012) Anglez starts at zmax/vmin and v_z < 0 / v_v > 0;
// Put this on the same system as Isochrone and Spherical angles +pi/2
*(Anglez+ii)= *(Omegaz+ii) * ( Or1 + Or2 )
+ *(dI3dJz+ii) * ( I3r1 + I3r2 ) + 0.5 * M_PI;
*(Anglephi+ii)+= phitmp;
*(Anglephi+ii)+= *(Omegaphi+ii) * ( Or1 + Or2 )
+ *(dI3dLz+ii) * ( I3r1 + I3r2 );
*(Angler+ii)= fmod(*(Angler+ii),2. * M_PI);
*(Anglez+ii)= fmod(*(Anglez+ii),2. * M_PI);
while ( *(Angler+ii) < 0. )
*(Angler+ii)+= 2. * M_PI;
while ( *(Anglez+ii) < 0. )
*(Anglez+ii)+= 2. * M_PI;
while ( *(Angler+ii) > 2. * M_PI )
*(Angler+ii)-= 2. * M_PI;
while ( *(Anglez+ii) > 2. * M_PI )
*(Anglez+ii)-= 2. * M_PI;
}
free(AngleuInt);
free(AnglevInt);
free(paramsu);
free(paramsv);
gsl_integration_glfixed_table_free ( T );
}
void calcUminUmax(int ndata,
double * umin,
double * umax,
double * ux,
double * pux,
double * E,
double * Lz,
double * I3U,
double delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
int nargs,
struct potentialArg * actionAngleArgs){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
double peps, meps;
gsl_function * JRRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JRStaeckelArg * params= (struct JRStaeckelArg *) malloc ( nthreads * sizeof (struct JRStaeckelArg) );
//Setup solver
int status;
int iter, max_iter = 100;
const gsl_root_fsolver_type *T;
struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) );;
double u_lo, u_hi;
T = gsl_root_fsolver_brent;
for (tid=0; tid < nthreads; tid++){
(params+tid)->delta= delta;
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
(s+tid)->s= gsl_root_fsolver_alloc (T);
}
UNUSED int chunk= CHUNKSIZE;
gsl_set_error_handler_off();
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,iter,status,u_lo,u_hi,meps,peps) \
shared(umin,umax,JRRoot,params,s,ux,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0,max_iter)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
//Setup function
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta;
(params+tid)->I3U= *(I3U+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->v0= *(v0+ii);
(params+tid)->sin2v0= *(sin2v0+ii);
(params+tid)->potu0v0= *(potu0v0+ii);
(JRRoot+tid)->function = &JRStaeckelIntegrandSquared;
(JRRoot+tid)->params = params+tid;
//Find starting points for minimum
if ( fabs(GSL_FN_EVAL(JRRoot+tid,*(ux+ii))) < 0.0000001){ //we are at umin or umax
peps= GSL_FN_EVAL(JRRoot+tid,*(ux+ii)+0.000001);
meps= GSL_FN_EVAL(JRRoot+tid,*(ux+ii)-0.000001);
if ( fabs(peps) < 0.00000001 && fabs(meps) < 0.00000001 ) {//circular
*(umin+ii) = *(ux+ii);
*(umax+ii) = *(ux+ii);
}
else if ( peps < 0. && meps > 0. ) {//umax
*(umax+ii)= *(ux+ii);
u_lo= 0.9 * (*(ux+ii) - 0.000001);
u_hi= *(ux+ii) - 0.0000001;
while ( GSL_FN_EVAL(JRRoot+tid,u_lo) >= 0. && u_lo > 0.000000001){
u_hi= u_lo; //this makes sure that brent evaluates using previous
u_lo*= 0.9;
}
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = 0.;//Assume zero if below 0.000000001
} else {
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umin+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
}
else if ( peps > 0. && meps < 0. ){//umin
*(umin+ii)= *(ux+ii);
u_lo= *(ux+ii) + 0.000001;
u_hi= 1.1 * (*(ux+ii) + 0.000001);
while ( GSL_FN_EVAL(JRRoot+tid,u_hi) >= 0. && u_hi < asinh(37.5/delta)) {
u_lo= u_hi; //this makes sure that brent evaluates using previous
u_hi*= 1.1;
}
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umax+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
}
else {
u_lo= 0.9 * *(ux+ii);
u_hi= *(ux+ii);
while ( GSL_FN_EVAL(JRRoot+tid,u_lo) >= 0. && u_lo > 0.000000001){
u_hi= u_lo; //this makes sure that brent evaluates using previous
u_lo*= 0.9;
}
u_hi= (u_lo < 0.9 * *(ux+ii)) ? u_lo / 0.9 / 0.9: *(ux+ii);
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = 0.;//Assume zero if below 0.000000001
} else {
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umin+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
//Find starting points for maximum
u_lo= *(ux+ii);
u_hi= 1.1 * *(ux+ii);
while ( GSL_FN_EVAL(JRRoot+tid,u_hi) > 0. && u_hi < asinh(37.5/delta)) {
u_lo= u_hi; //this makes sure that brent evaluates using previous
u_hi*= 1.1;
}
u_lo= (u_hi > 1.1 * *(ux+ii)) ? u_hi / 1.1 / 1.1: *(ux+ii);
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umax+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
}
gsl_set_error_handler (NULL);
for (tid=0; tid < nthreads; tid++)
gsl_root_fsolver_free( (s+tid)->s);
free(s);
free(JRRoot);
free(params);
}
void calcVmin(int ndata,
double * vmin,
double * vx,
double * pvx,
double * E,
double * Lz,
double * I3V,
double delta,
double * u0,
double * cosh2u0,
double * sinh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * JzRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JzStaeckelArg * params= (struct JzStaeckelArg *) malloc ( nthreads * sizeof (struct JzStaeckelArg) );
//Setup solver
int status;
int iter, max_iter = 100;
const gsl_root_fsolver_type *T;
struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) );;
double v_lo, v_hi;
T = gsl_root_fsolver_brent;
for (tid=0; tid < nthreads; tid++){
(params+tid)->delta= delta;
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
(s+tid)->s= gsl_root_fsolver_alloc (T);
}
UNUSED int chunk= CHUNKSIZE;
gsl_set_error_handler_off();
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,iter,status,v_lo,v_hi) \
shared(vmin,JzRoot,params,s,vx,delta,E,Lz,I3V,u0,cosh2u0,sinh2u0,potupi2,max_iter)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
//Setup function
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / delta / delta;
(params+tid)->I3V= *(I3V+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->cosh2u0= *(cosh2u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->potupi2= *(potupi2+ii);
(JzRoot+tid)->function = &JzStaeckelIntegrandSquared;
(JzRoot+tid)->params = params+tid;
//Find starting points for minimum
if ( fabs(GSL_FN_EVAL(JzRoot+tid,*(vx+ii))) < 0.0000001) //we are at vmin
*(vmin+ii)= ( *(vx+ii) > 0.5 * M_PI ) ? M_PI - *(vx+ii): *(vx+ii);
else {
if ( *(vx+ii) > 0.5 * M_PI ){
v_lo= 0.9 * ( M_PI - *(vx+ii) );
v_hi= M_PI - *(vx+ii);
}
else {
v_lo= 0.9 * *(vx+ii);
v_hi= *(vx+ii);
}
while ( GSL_FN_EVAL(JzRoot+tid,v_lo) >= 0. && v_lo > 0.000000001){
v_hi= v_lo; //this makes sure that brent evaluates using previous
v_lo*= 0.9;
}
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JzRoot+tid, v_lo, v_hi);
if (status == GSL_EINVAL) {
*(vmin+ii) = -9999.99;
continue;
}
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
v_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
v_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (v_lo, v_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(vmin+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(vmin+ii) = gsl_root_fsolver_root ((s+tid)->s);
fflush(stdout);
}
}
gsl_set_error_handler (NULL);
for (tid=0; tid < nthreads; tid++)
gsl_root_fsolver_free( (s+tid)->s);
free(s);
free(JzRoot);
free(params);
}
double JRStaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared(u,p);
if ( out <= 0.) return 0.;
else return sqrt(out);
}
double JRStaeckelIntegrandSquared(double u,
void * p){
struct JRStaeckelArg * params= (struct JRStaeckelArg *) p;
double sinh2u= sinh(u) * sinh(u);
double dU= (sinh2u+params->sin2v0)
*evaluatePotentialsUV(u,params->v0,params->delta,
params->nargs,params->actionAngleArgs)
- (params->sinh2u0+params->sin2v0)*params->potu0v0;
return params->E * sinh2u - params->I3U - dU - params->Lz22delta / sinh2u;
}
double JRStaeckelIntegrandSquared4dJR(double u,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double sinh2u= sinh(u) * sinh(u);
double dU= (sinh2u+params->sin2v0)
*evaluatePotentialsUV(u,params->v0,params->delta,
params->nargs,params->actionAngleArgs)
- (params->sinh2u0+params->sin2v0)*params->potu0v0;
return params->E * sinh2u - params->I3U - dU - params->Lz22delta / sinh2u;
}
double JzStaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared(v,p);
if ( out <= 0. ) return 0.;
else return sqrt(out);
}
double JzStaeckelIntegrandSquared(double v,
void * p){
struct JzStaeckelArg * params= (struct JzStaeckelArg *) p;
double sin2v= sin(v) * sin(v);
double dV= params->cosh2u0 * params->potupi2
- (params->sinh2u0+sin2v)
*evaluatePotentialsUV(params->u0,v,params->delta,
params->nargs,params->actionAngleArgs);
return params->E * sin2v + params->I3V + dV - params->Lz22delta / sin2v;
}
double JzStaeckelIntegrandSquared4dJz(double v,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double sin2v= sin(v) * sin(v);
double dV= params->cosh2u0 * params->potupi2
- (params->sinh2u0+sin2v)
*evaluatePotentialsUV(params->u0,v,params->delta,
params->nargs,params->actionAngleArgs);
return params->E * sin2v + params->I3V + dV - params->Lz22delta / sin2v;
}
double dJRdELowStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umin + t * t;
return 2. * t * dJRdEStaeckelIntegrand(u,p);
}
double dJRdEHighStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umax - t * t;
return 2. * t * dJRdEStaeckelIntegrand(u,p);
}
double dJRdEStaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared4dJR(u,p);
if ( out <= 0. ) return 0.;
else return sinh(u)*sinh(u)/sqrt(out);
}
double dJRdLzLowStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umin + t * t;
return 2. * t * dJRdLzStaeckelIntegrand(u,p);
}
double dJRdLzHighStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umax - t * t;
return 2. * t * dJRdLzStaeckelIntegrand(u,p);
}
double dJRdLzStaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared4dJR(u,p);
if ( out <= 0. ) return 0.;
else return 1./sinh(u)/sinh(u)/sqrt(out);
}
double dJRdI3LowStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umin + t * t;
return 2. * t * dJRdI3StaeckelIntegrand(u,p);
}
double dJRdI3HighStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umax - t * t;
return 2. * t * dJRdI3StaeckelIntegrand(u,p);
}
double dJRdI3StaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared4dJR(u,p);
if ( out <= 0. ) return 0.;
else return 1./sqrt(out);
}
double dJzdELowStaeckelIntegrand(double t,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double v= params->vmin + t * t;
return 2. * t * dJzdEStaeckelIntegrand(v,p);
}
double dJzdEHighStaeckelIntegrand(double t,
void * p){
double v= M_PI/2. - t * t;
return 2. * t * dJzdEStaeckelIntegrand(v,p);
}
double dJzdEStaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared4dJz(v,p);
if ( out <= 0. ) return 0.;
else return sin(v)*sin(v)/sqrt(out);
}
double dJzdLzLowStaeckelIntegrand(double t,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double v= params->vmin + t * t;
return 2. * t * dJzdLzStaeckelIntegrand(v,p);
}
double dJzdLzHighStaeckelIntegrand(double t,
void * p){
double v= M_PI/2. - t * t;
return 2. * t * dJzdLzStaeckelIntegrand(v,p);
}
double dJzdLzStaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared4dJz(v,p);
if ( out <= 0. ) return 0.;
else return 1./sin(v)/sin(v)/sqrt(out);
}
double dJzdI3LowStaeckelIntegrand(double t,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double v= params->vmin + t * t;
return 2. * t * dJzdI3StaeckelIntegrand(v,p);
}
double dJzdI3HighStaeckelIntegrand(double t,
void * p){
double v= M_PI/2. - t * t;
return 2. * t * dJzdI3StaeckelIntegrand(v,p);
}
double dJzdI3StaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared4dJz(v,p);
if ( out <= 0. ) return 0.;
else return 1./sqrt(out);
}
double u0Equation(double u, void * p){
struct u0EqArg * params= (struct u0EqArg *) p;
double sinh2u= sinh(u) * sinh(u);
double cosh2u= cosh(u) * cosh(u);
double dU= cosh2u * evaluatePotentialsUV(u,0.5*M_PI,params->delta,
params->nargs,params->actionAngleArgs);
return -(params->E*sinh2u-dU-params->Lz22delta/sinh2u);
}
double evaluatePotentialsUV(double u, double v, double delta,
int nargs,
struct potentialArg * actionAngleArgs){
double R,z;
uv_to_Rz(u,v,&R,&z,delta);
return evaluatePotentials(R,z,nargs,actionAngleArgs);
}
|
globals.h | /*
* globals.h
*
* Created on: Sep 4, 2018
* Author: Zhen Peng
* Modified: 02/24/2019: Add a type name weightiLarge and its INF value WEIGHTILARGE_MAX, which are particularly used for Weighted version PADO.
*/
#ifndef INCLUDES_GLOBALS_H_
#define INCLUDES_GLOBALS_H_
#include <stdint.h>
#include <limits.h>
#include <sys/time.h>
#include <string>
#include <vector>
#include <string.h>
#include <cmath>
#include <omp.h>
using std::string;
//using std::vector;
namespace PADO {
//typedef uint64_t idi; // unsinged long long
typedef uint32_t idi; // unsigned int
//typedef int weighti;
typedef uint8_t weighti;
//typedef int32_t weightiLarge;
typedef int16_t weightiLarge;
typedef uint8_t smalli;
typedef uint32_t inti;
//const int WEIGHTI_MAX = INT_MAX;
const uint8_t WEIGHTI_MAX = UCHAR_MAX;
//const int32_t WEIGHTILARGE_MAX = INT_MAX;
const int16_t WEIGHTILARGE_MAX = SHRT_MAX;
const uint8_t SMALLI_MAX = UCHAR_MAX;
// Parallel Number of Threads
inti NUM_THREADS = 4;
// Utility Functions
// Compare and Swap
template <typename V_T>
inline bool CAS(V_T *ptr, V_T old_val, V_T new_val)
//inline bool CAS(void *ptr, V_T old_val, V_T new_val)
{
// return __atomic_compare_exchange(ptr, &old_val, &new_val, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
if (1 == sizeof(V_T)) {
return __atomic_compare_exchange(reinterpret_cast<uint8_t *>(ptr), reinterpret_cast<uint8_t *>(&old_val),
reinterpret_cast<uint8_t *>(&new_val), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
} else if (2 == sizeof(V_T)) {
return __atomic_compare_exchange(reinterpret_cast<uint16_t *>(ptr), reinterpret_cast<uint16_t *>(&old_val),
reinterpret_cast<uint16_t *>(&new_val), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
} else if (4 == sizeof(V_T)) {
return __atomic_compare_exchange(reinterpret_cast<uint32_t *>(ptr), reinterpret_cast<uint32_t *>(&old_val),
reinterpret_cast<uint32_t *>(&new_val), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
} else if (8 == sizeof(V_T)) {
return __atomic_compare_exchange(reinterpret_cast<uint64_t *>(ptr), reinterpret_cast<uint64_t *>(&old_val),
reinterpret_cast<uint64_t *>(&new_val), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
} else {
printf("CAS cannot support the type.\n");
exit(EXIT_FAILURE);
}
// if (1 == sizeof(V_T)) {
// return __sync_bool_compare_and_swap((uint8_t *) ptr, *((uint8_t *) &old_val), *((uint8_t *) &new_val));
// } else if (2 == sizeof(V_T)) {
// return __sync_bool_compare_and_swap((uint16_t *) ptr, *((uint16_t *) &old_val), *((uint16_t *) &new_val));
// } else if (4 == sizeof(V_T)) {
// return __sync_bool_compare_and_swap((uint32_t *) ptr, *((uint32_t *) &old_val), *((uint32_t *) &new_val));
// } else if (8 == sizeof(V_T)) {
// return __sync_bool_compare_and_swap((uint64_t *) ptr, *((uint64_t *) &old_val), *((uint64_t *) &new_val));
// } else {
// printf("CAS cannot support the type.\n");
// exit(EXIT_FAILURE);
// }
}
// Class for Timer
class WallTimer {
private:
double start = 0.0;
string item;
void construct()
{
timeval t;
gettimeofday(&t, NULL);
start = t.tv_sec + t.tv_usec * 0.000001;
}
public:
WallTimer()
{
construct();
}
explicit WallTimer(const char *n) : item(n)
{
construct();
}
double get_runtime()
{
timeval t;
gettimeofday(&t, NULL);
double now = t.tv_sec + t.tv_usec * 0.000001;
return now - start;
}
void print_runtime()
{
double runtime = get_runtime();
printf("%s: %f\n", item.c_str(), runtime); fflush(stdout);
}
static double get_time_mark()
{
timeval t;
gettimeofday(&t, NULL);
return t.tv_sec + t.tv_usec * 0.000001;
}
};
// End Class WallTimer
// Parallel Prefix Sum
template<typename Int>
inline Int prefix_sum_for_offsets(
std::vector<Int> &offsets)
{
size_t size_offsets = offsets.size();
if (1 == size_offsets) {
Int tmp = offsets[0];
offsets[0] = 0;
return tmp;
} else if (size_offsets < 2048) {
Int offset_sum = 0;
size_t size = size_offsets;
for (size_t i = 0; i < size; ++i) {
Int tmp = offsets[i];
offsets[i] = offset_sum;
offset_sum += tmp;
}
return offset_sum;
} else {
// Parallel Prefix Sum, based on Guy E. Blelloch's Prefix Sums and Their Applications
Int last_element = offsets[size_offsets - 1];
// idi size = 1 << ((idi) log2(size_offsets - 1) + 1);
size_t size = 1 << ((size_t) log2(size_offsets));
// std::vector<idi> nodes(size, 0);
Int tmp_element = offsets[size - 1];
//#pragma omp parallel for
// for (idi i = 0; i < size_offsets; ++i) {
// nodes[i] = offsets[i];
// }
// Up-Sweep (Reduce) Phase
Int log2size = log2(size);
for (Int d = 0; d < log2size; ++d) {
Int by = 1 << (d + 1);
#pragma omp parallel for
for (size_t k = 0; k < size; k += by) {
offsets[k + (1 << (d + 1)) - 1] += offsets[k + (1 << d) - 1];
}
}
// Down-Sweep Phase
offsets[size - 1] = 0;
for (Int d = log2size - 1; d != (Int) -1; --d) {
Int by = 1 << (d + 1);
#pragma omp parallel for
for (size_t k = 0; k < size; k += by) {
Int t = offsets[k + (1 << d) - 1];
offsets[k + (1 << d) - 1] = offsets[k + (1 << (d + 1)) - 1];
offsets[k + (1 << (d + 1)) - 1] += t;
}
}
//#pragma omp parallel for
// for (idi i = 0; i < size_offsets; ++i) {
// offsets[i] = nodes[i];
// }
if (size != size_offsets) {
Int tmp_sum = offsets[size - 1] + tmp_element;
for (size_t i = size; i < size_offsets; ++i) {
Int t = offsets[i];
offsets[i] = tmp_sum;
tmp_sum += t;
}
}
return offsets[size_offsets - 1] + last_element;
}
}
//// Parallel Prefix Sum
//inline idi prefix_sum_for_offsets(
// std::vector<idi> &offsets)
//{
// idi size_offsets = offsets.size();
// if (1 == size_offsets) {
// idi tmp = offsets[0];
// offsets[0] = 0;
// return tmp;
// } else if (size_offsets < 2048) {
// idi offset_sum = 0;
// idi size = size_offsets;
// for (idi i = 0; i < size; ++i) {
// idi tmp = offsets[i];
// offsets[i] = offset_sum;
// offset_sum += tmp;
// }
// return offset_sum;
// } else {
// // Parallel Prefix Sum, based on Guy E. Blelloch's Prefix Sums and Their Applications
// idi last_element = offsets[size_offsets - 1];
// // idi size = 1 << ((idi) log2(size_offsets - 1) + 1);
// idi size = 1 << ((idi) log2(size_offsets));
// // std::vector<idi> nodes(size, 0);
// idi tmp_element = offsets[size - 1];
// //#pragma omp parallel for
// // for (idi i = 0; i < size_offsets; ++i) {
// // nodes[i] = offsets[i];
// // }
//
// // Up-Sweep (Reduce) Phase
// idi log2size = log2(size);
// for (idi d = 0; d < log2size; ++d) {
// idi by = 1 << (d + 1);
//#pragma omp parallel for
// for (idi k = 0; k < size; k += by) {
// offsets[k + (1 << (d + 1)) - 1] += offsets[k + (1 << d) - 1];
// }
// }
//
// // Down-Sweep Phase
// offsets[size - 1] = 0;
// for (idi d = log2(size) - 1; d != (idi) -1; --d) {
// idi by = 1 << (d + 1);
//#pragma omp parallel for
// for (idi k = 0; k < size; k += by) {
// idi t = offsets[k + (1 << d) - 1];
// offsets[k + (1 << d) - 1] = offsets[k + (1 << (d + 1)) - 1];
// offsets[k + (1 << (d + 1)) - 1] += t;
// }
// }
//
// //#pragma omp parallel for
// // for (idi i = 0; i < size_offsets; ++i) {
// // offsets[i] = nodes[i];
// // }
// if (size != size_offsets) {
// idi tmp_sum = offsets[size - 1] + tmp_element;
// for (idi i = size; i < size_offsets; ++i) {
// idi t = offsets[i];
// offsets[i] = tmp_sum;
// tmp_sum += t;
// }
// }
//
// return offsets[size_offsets - 1] + last_element;
// }
//}
// Parallelly collect elements of tmp_queue into the queue.
template<typename T, typename Int>
inline void collect_into_queue(
// std::vector<idi> &tmp_queue,
std::vector<T> &tmp_queue,
std::vector<Int> &offsets_tmp_queue, // the locations for reading tmp_queue
std::vector<Int> &offsets_queue, // the locations for writing queue.
const Int num_elements, // total number of elements which need to be added from tmp_queue to queue
// std::vector<idi> &queue,
std::vector<T> &queue,
Int &end_queue)
{
if (0 == num_elements) {
return;
}
size_t i_bound = offsets_tmp_queue.size();
#pragma omp parallel for
for (size_t i = 0; i < i_bound; ++i) {
Int i_q_start = end_queue + offsets_queue[i];
Int i_q_bound;
if (i_bound - 1 != i) {
i_q_bound = end_queue + offsets_queue[i + 1];
} else {
i_q_bound = end_queue + num_elements;
}
if (i_q_start == i_q_bound) {
// If the group has no elements to be added, then continue to the next group
continue;
}
Int end_tmp = offsets_tmp_queue[i];
for (Int i_q = i_q_start; i_q < i_q_bound; ++i_q) {
queue[i_q] = tmp_queue[end_tmp++];
}
}
end_queue += num_elements;
}
template<typename T, typename Int>
inline void TS_enqueue(
std::vector<T> &queue,
Int &end_queue,
const T &e)
{
volatile Int old_i = end_queue;
volatile Int new_i = old_i + 1;
while (!CAS(&end_queue, old_i, new_i)) {
old_i = end_queue;
new_i = old_i + 1;
}
queue[old_i] = e;
}
} // namespace PADO
#endif /* INCLUDES_GLOBALS_H_ */
|
atkin.c | #include "atkin/atkin.h"
#include "atkin/atkin_q1.h"
#include "atkin/atkin_q2.h"
#include "atkin/atkin_q3.h"
#include <stdlib.h> /* malloc, free */
#include <string.h> /* memset */
#include <math.h> /* ceil, sqrt */
#define CHUNK_WIDTH 22
#include "common/defs.h"
#include "common/enum.h"
#include "common/presieve.h"
#include "common/bitset.h"
static inline int atkin_chunk_sieve_psquares(char* chunk, llong lower, llong upper, const char* sieved)
{
const llong chunk_size = upper - lower;
for (llong p = 7; p * p < upper; ++p)
{
if (sieved[p] == 1)
{
llong p_sqr = p*p;
llong mod = lower % p_sqr;
llong i = p_sqr * (mod != 0) - mod;
for (; i < chunk_size; i += p_sqr)
{
bitset_clear(chunk, i);
}
}
}
return 0;
}
static inline int atkin_chunk(char* chunk, llong lower, llong upper, const char* sieved)
{
memset(chunk, 0, CHUNK_BYTES);
atkin_chunk_q1(chunk, lower, upper);
atkin_chunk_q2(chunk, lower, upper);
atkin_chunk_q3(chunk, lower, upper);
atkin_chunk_sieve_psquares(chunk, lower, upper, sieved);
return 0;
}
static inline void atkin_precomp()
{
atkin_q1_precomp();
atkin_q2_precomp();
atkin_q3_precomp();
}
llong atkin(llong lower, llong upper, int print)
{
llong ret = 0;
llong root = sqrt(upper) + 1;
char* arr = (char*)malloc(root * sizeof(char));
if (arr == NULL)
{
return ret;
}
enumerate_bitset_precomp();
atkin_precomp();
erath_less_than(arr, root);
ret = enumerate(arr + lower, arr + root, lower, print);
char* chunk = (char*)malloc(CHUNK_BYTES);
if (chunk == NULL)
{
free(arr);
return 0;
}
bitset_enum_func enumerator = enumerate_bitset;
if (print != 0)
{
enumerator = enumerate_bitset_print;
}
llong chunk_lower = (root < lower) ? lower : root;
llong chunk_upper = chunk_lower + CHUNK_SIZE ;
for (; chunk_upper < upper; chunk_lower += CHUNK_SIZE, chunk_upper += CHUNK_SIZE)
{
atkin_chunk(chunk, chunk_lower, chunk_upper, arr);
ret += enumerator(chunk, CHUNK_BYTES, chunk_lower);
}
unsigned last_chunk_bytes = ceil((upper - chunk_lower) / 8.0);
atkin_chunk(chunk, chunk_lower, upper, arr);
ret += enumerator(chunk, last_chunk_bytes, chunk_lower);
free(chunk);
free(arr);
return ret;
}
llong atkin_mt(llong lower, llong upper, int print)
{
llong ret = 0;
llong root = sqrt(upper) + 1;
char* arr = (char*)malloc(root * sizeof(char));
if (arr == NULL)
{
return ret;
}
enumerate_bitset_precomp();
atkin_precomp();
erath_less_than(arr, root);
ret = enumerate(arr + lower, arr + root, lower, print);
bitset_enum_func enumerator = enumerate_bitset;
if (print != 0)
{
enumerator = enumerate_bitset_print;
}
llong i, first_chunk_start = (root < lower) ? lower : root;
#pragma omp parallel for ordered, schedule(dynamic)
for (i = first_chunk_start; i < upper; i += CHUNK_SIZE)
{
char* chunk = malloc(CHUNK_BYTES);
llong chunk_size = CHUNK_SIZE;
if ((i + chunk_size) > upper)
{
chunk_size = upper - i;
}
atkin_chunk(chunk, i, i + chunk_size, arr);
#pragma omp ordered
ret += enumerator(chunk, CHUNK_BYTES, i);
free(chunk);
}
free(arr);
return ret;
}
|
Example_acquire_release.2.c | /*
* @@name: acquire_release.2.c
* @@type: C
* @@compilable: yes
* @@linkable: yes
* @@expect: success
* @@version: omp_5.0
*/
#include <stdio.h>
#include <omp.h>
int main()
{
int x = 0, y = 0;
#pragma omp parallel num_threads(2)
{
int thrd = omp_get_thread_num();
if (thrd == 0) {
x = 10;
#pragma omp atomic write release // or seq_cst
y = 1;
} else {
int tmp = 0;
while (tmp == 0) {
#pragma omp atomic read acquire // or seq_cst
tmp = y;
}
printf("x = %d\n", x); // always "x = 10"
}
}
return 0;
}
|
generator_gemm_common.c | /******************************************************************************
* Copyright (c) Intel Corporation - All rights reserved. *
* This file is part of the LIBXSMM library. *
* *
* For information on the license, see the LICENSE file. *
* Further information: https://github.com/libxsmm/libxsmm/ *
* SPDX-License-Identifier: BSD-3-Clause *
******************************************************************************/
/* Alexander Heinecke, Evangelos Georganas (Intel Corp.)
******************************************************************************/
#include "generator_gemm_common.h"
#include "generator_common.h"
#include "generator_x86_instructions.h"
#include "libxsmm_main.h"
#include "generator_common_x86.h"
#include "generator_mateltwise_sse_avx_avx512.h"
#include "generator_mateltwise_transform_avx512.h"
#include "generator_mateltwise_transform_avx.h"
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_vnni_store_C_from_scratch( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc) {
libxsmm_descriptor_blob blob;
const libxsmm_meltw_descriptor *const trans_desc = libxsmm_meltw_descriptor_init2(&blob,
LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_UNSUPPORTED, LIBXSMM_DATATYPE_UNSUPPORTED, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, i_xgemm_desc->m, i_xgemm_desc->n,
i_xgemm_desc->ldc, i_xgemm_desc->ldc, 0, 0,
(unsigned short)LIBXSMM_MELTW_FLAG_UNARY_NONE, (unsigned short)LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_VNNI2, LIBXSMM_MELTW_OPERATION_UNARY);
libxsmm_mateltwise_kernel_config l_trans_config;
unsigned int l_gp_reg_in = i_gp_reg_mapping->gp_reg_help_2;
libxsmm_generator_mateltwise_init_micro_kernel_config_fullvector( io_generated_code, &l_trans_config, trans_desc);
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_TRANS_EXT_BUF_C, i_gp_reg_mapping->gp_reg_c );
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_GEMM_SCRATCH_PTR, l_gp_reg_in );
libxsmm_x86_instruction_alu_imm_i64( io_generated_code, LIBXSMM_X86_INSTR_MOVQ, i_gp_reg_mapping->gp_reg_help_1, 32*64 );
libxsmm_x86_instruction_alu_reg( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_1, l_gp_reg_in);
if (io_generated_code->arch >= LIBXSMM_X86_AVX512){
libxsmm_generator_transform_norm_to_vnni2_16bit_avx512_microkernel( io_generated_code, io_loop_label_tracker,
l_gp_reg_in, i_gp_reg_mapping->gp_reg_c, i_gp_reg_mapping->gp_reg_mloop, i_gp_reg_mapping->gp_reg_nloop,
i_gp_reg_mapping->gp_reg_help_1, 1, 2,
&l_trans_config, trans_desc, 0 );
} else {
libxsmm_generator_transform_norm_to_vnni2_16bit_avx_microkernel( io_generated_code, io_loop_label_tracker,
l_gp_reg_in, i_gp_reg_mapping->gp_reg_c, i_gp_reg_mapping->gp_reg_mloop, i_gp_reg_mapping->gp_reg_nloop,
&l_trans_config, trans_desc, 0 );
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_apply_relu_to_vreg( libxsmm_generated_code* io_generated_code,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int zero_vreg,
const unsigned int inout_vreg,
const unsigned int store_bitmask,
const unsigned int gpr_bitmask,
const unsigned int store_bitmask_offset,
const unsigned int is_32_bit_relu,
const unsigned int aux_gpr,
const unsigned int aux_vreg) {
if (io_generated_code->arch < LIBXSMM_X86_AVX512) {
if (is_32_bit_relu == 1) {
if (store_bitmask == 1) {
libxsmm_x86_instruction_vec_compute_3reg_imm8( io_generated_code, LIBXSMM_X86_INSTR_VCMPPS, i_micro_kernel_config->vector_name, zero_vreg, inout_vreg, aux_vreg, 6 );
libxsmm_x86_instruction_vec_compute_3reg_imm8( io_generated_code, LIBXSMM_X86_INSTR_VMOVMSKPS, i_micro_kernel_config->vector_name, aux_vreg, LIBXSMM_X86_VEC_REG_UNDEF, aux_gpr, 0 );
libxsmm_x86_instruction_alu_mem( io_generated_code, LIBXSMM_X86_INSTR_MOVB, gpr_bitmask, LIBXSMM_X86_GP_REG_UNDEF, 0, store_bitmask_offset, aux_gpr, 1);
}
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code, LIBXSMM_X86_INSTR_VMAXPS, i_micro_kernel_config->vector_name, inout_vreg, zero_vreg, inout_vreg );
} else {
/* shouldn't happen */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_UNSUP_DATATYPE );
return;
}
} else {
if (store_bitmask == 0) {
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
(is_32_bit_relu == 1) ? LIBXSMM_X86_INSTR_VMAXPS : LIBXSMM_X86_INSTR_VPMAXSW,
i_micro_kernel_config->vector_name,
inout_vreg,
zero_vreg,
inout_vreg);
} else {
unsigned int current_mask_reg = 7;
libxsmm_x86_instruction_vec_compute_3reg_imm8( io_generated_code,
(is_32_bit_relu == 1) ? LIBXSMM_X86_INSTR_VCMPPS : LIBXSMM_X86_INSTR_VPCMPW,
i_micro_kernel_config->vector_name,
zero_vreg,
inout_vreg,
current_mask_reg, 6 );
/* Blend output result with zero reg based on relu mask */
libxsmm_x86_instruction_vec_compute_3reg_mask( io_generated_code,
(is_32_bit_relu == 1) ? LIBXSMM_X86_INSTR_VPBLENDMD : LIBXSMM_X86_INSTR_VPBLENDMW,
i_micro_kernel_config->vector_name,
inout_vreg,
zero_vreg,
inout_vreg,
current_mask_reg,
0 );
/* Store bitmask */
libxsmm_x86_instruction_mask_move_mem( io_generated_code,
(is_32_bit_relu == 1) ? LIBXSMM_X86_INSTR_KMOVW_ST : LIBXSMM_X86_INSTR_KMOVD_ST,
gpr_bitmask,
LIBXSMM_X86_GP_REG_UNDEF,
0,
store_bitmask_offset,
current_mask_reg );
}
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_apply_sigmoid_to_vreg_from_scratch( libxsmm_generated_code* io_generated_code,
libxsmm_micro_kernel_config* i_micro_kernel_config_mod,
const unsigned int scratch_gpr,
const unsigned int in_vreg,
const unsigned int out_vreg ) {
/* Load accumulator from scratch */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config_mod->instruction_set,
LIBXSMM_X86_INSTR_VMOVUPS,
scratch_gpr,
LIBXSMM_X86_GP_REG_UNDEF, 0,
in_vreg * 64,
i_micro_kernel_config_mod->vector_name,
out_vreg, 0, 1, 0 );
/* Apply sigmoid */
if (io_generated_code->arch >= LIBXSMM_X86_AVX512_VL256) {
const char i_vname = (io_generated_code->arch < LIBXSMM_X86_AVX512) ? 'y' : 'z';
libxsmm_generator_sigmoid_ps_rational_78_avx512( io_generated_code, out_vreg, i_micro_kernel_config_mod->vec_x2,
i_micro_kernel_config_mod->vec_nom, i_micro_kernel_config_mod->vec_denom,
i_micro_kernel_config_mod->mask_hi, i_micro_kernel_config_mod->mask_lo,
i_micro_kernel_config_mod->vec_c0, i_micro_kernel_config_mod->vec_c1, i_micro_kernel_config_mod->vec_c2, i_micro_kernel_config_mod->vec_c3,
i_micro_kernel_config_mod->vec_c1_d, i_micro_kernel_config_mod->vec_c2_d, i_micro_kernel_config_mod->vec_c3_d,
i_micro_kernel_config_mod->vec_hi_bound, i_micro_kernel_config_mod->vec_lo_bound, i_micro_kernel_config_mod->vec_ones,
i_micro_kernel_config_mod->vec_neg_ones, i_micro_kernel_config_mod->vec_halves, i_vname );
} else {
libxsmm_generator_sigmoid_ps_rational_78_avx( io_generated_code, out_vreg, i_micro_kernel_config_mod->vec_x2,
i_micro_kernel_config_mod->vec_nom, i_micro_kernel_config_mod->vec_denom,
i_micro_kernel_config_mod->vec_c0, i_micro_kernel_config_mod->vec_c1, i_micro_kernel_config_mod->vec_c2, i_micro_kernel_config_mod->vec_c3,
i_micro_kernel_config_mod->vec_c1_d, i_micro_kernel_config_mod->vec_c2_d, i_micro_kernel_config_mod->vec_c3_d,
i_micro_kernel_config_mod->vec_hi_bound, i_micro_kernel_config_mod->vec_lo_bound, i_micro_kernel_config_mod->vec_ones,
i_micro_kernel_config_mod->vec_neg_ones );
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_restore_2D_regblock_from_scratch( libxsmm_generated_code* io_generated_code,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int scratch_gpr,
const unsigned int l_vec_reg_acc_start,
const unsigned int l_m_blocking,
const unsigned int i_n_blocking) {
unsigned int l_n, l_m;
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVUPS,
scratch_gpr,
LIBXSMM_X86_GP_REG_UNDEF, 0,
(l_vec_reg_acc_start + l_m + (l_m_blocking * l_n)) * 64,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), 0, 0, 0 );
}
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_store_2D_regblock_to_scratch( libxsmm_generated_code* io_generated_code,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int scratch_gpr,
const unsigned int l_vec_reg_acc_start,
const unsigned int l_m_blocking,
const unsigned int i_n_blocking) {
unsigned int l_n, l_m;
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVUPS,
scratch_gpr,
LIBXSMM_X86_GP_REG_UNDEF, 0,
(l_vec_reg_acc_start + l_m + (l_m_blocking * l_n)) * 64,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), 0, 0, 1 );
}
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_dump_2D_block_and_prepare_sigmoid_fusion( libxsmm_generated_code* io_generated_code,
libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int l_vec_reg_acc_start,
const unsigned int l_m_blocking,
const unsigned int i_n_blocking,
const unsigned int scratch_gpr,
const unsigned int aux_gpr) {
unsigned int n_avail_vregs = (io_generated_code->arch >= LIBXSMM_X86_AVX512) ? 32 : 16;
unsigned int n_avail_masks = (io_generated_code->arch >= LIBXSMM_X86_AVX512) ? 8 : 16;
/* First dump the accumulators to scratch and then setup sigmoid coeffcients to be reused */
libxsmm_x86_instruction_push_reg( io_generated_code, scratch_gpr);
libxsmm_x86_instruction_push_reg( io_generated_code, aux_gpr );
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_GEMM_SCRATCH_PTR, scratch_gpr);
libxsmm_generator_gemm_store_2D_regblock_to_scratch( io_generated_code, i_micro_kernel_config,
scratch_gpr, l_vec_reg_acc_start, l_m_blocking, i_n_blocking);
libxsmm_generator_gemm_prepare_coeffs_sigmoid_ps_rational_78_avx_avx512( io_generated_code, i_micro_kernel_config, n_avail_vregs, n_avail_masks, aux_gpr );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_prepare_relu_fusion( libxsmm_generated_code* io_generated_code,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int zero_vreg,
const unsigned int store_bitmask,
const unsigned int bitmask_gpr,
const unsigned int aux_gpr) {
/* Zero out register 0 to perform relu */
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
i_micro_kernel_config->vxor_instruction,
i_micro_kernel_config->vector_name,
zero_vreg, zero_vreg, zero_vreg);
if (store_bitmask == 1) {
libxsmm_x86_instruction_push_reg( io_generated_code, bitmask_gpr );
if (io_generated_code->arch < LIBXSMM_X86_AVX512) {
libxsmm_x86_instruction_push_reg( io_generated_code, aux_gpr );
}
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, bitmask_gpr );
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_cleanup_relu_fusion( libxsmm_generated_code* io_generated_code,
const unsigned int store_bitmask,
const unsigned int bitmask_gpr,
const unsigned int aux_gpr) {
if (store_bitmask == 1) {
if (io_generated_code->arch < LIBXSMM_X86_AVX512) {
libxsmm_x86_instruction_pop_reg( io_generated_code, aux_gpr );
}
libxsmm_x86_instruction_pop_reg( io_generated_code, bitmask_gpr);
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_cleanup_sigmoid_fusion( libxsmm_generated_code* io_generated_code,
const unsigned int scratch_gpr,
const unsigned int aux_gpr ) {
libxsmm_x86_instruction_pop_reg( io_generated_code, aux_gpr );
libxsmm_x86_instruction_pop_reg( io_generated_code, scratch_gpr );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_load_colbias_to_2D_block( libxsmm_generated_code* io_generated_code,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
libxsmm_datatype colbias_precision,
const unsigned int l_vec_reg_acc_start,
const unsigned int l_m_blocking,
const unsigned int i_n_blocking ) {
unsigned int l_n = 0, l_m = 0;
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_2 );
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
if (colbias_precision == LIBXSMM_DATATYPE_BF16) {
if (l_n == 0) {
/* Load bias vector */
/* load 16 bit values into xmm portion of the register */
if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU16,
i_gp_reg_mapping->gp_reg_help_2,
LIBXSMM_X86_GP_REG_UNDEF, 0,
(l_m * (i_micro_kernel_config->vector_length)) * 2,
( ( i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ) ) ? 'y' : 'z',
l_vec_reg_acc_start + l_m, 2, 1, 0 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_help_2,
LIBXSMM_X86_GP_REG_UNDEF, 0,
(l_m * (i_micro_kernel_config->vector_length)) * 2,
( ( i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ) ) ? 'x' : 'y',
l_vec_reg_acc_start + l_m, 0, 1, 0 );
}
/* convert 16 bit values into 32 bit (integer convert) */
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VPMOVSXWD,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m, l_vec_reg_acc_start + l_m );
/* shift 16 bits to the left to generate valid FP32 numbers */
libxsmm_x86_instruction_vec_compute_2reg_imm8(io_generated_code,
LIBXSMM_X86_INSTR_VPSLLD_I,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m,
l_vec_reg_acc_start + l_m,
16);
} else {
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code, LIBXSMM_X86_INSTR_VMOVUPS,
( ( i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ) ) ? 'y' : 'z',
l_vec_reg_acc_start + l_m, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
}
} else if (colbias_precision == LIBXSMM_DATATYPE_F32) {
if (l_n == 0) {
/* Load bias vector */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_help_2,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_m * (i_micro_kernel_config->vector_length))) * 4,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m, ( l_m == (l_m_blocking - 1) ) ? i_micro_kernel_config->use_masking_a_c : 0, 1, 0 );
} else {
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code, LIBXSMM_X86_INSTR_VMOVUPS, i_micro_kernel_config->vector_name, l_vec_reg_acc_start + l_m, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
}
} else {
/* shouldn't happen */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_UNSUP_DATATYPE );
return;
}
}
}
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_add_colbias_to_2D_block( libxsmm_generated_code* io_generated_code,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
libxsmm_datatype colbias_precision,
const unsigned int l_vec_reg_acc_start,
const unsigned int l_m_blocking,
const unsigned int i_n_blocking ) {
unsigned int l_n = 0, l_m = 0;
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_2 );
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
/* Load bias vector */
if (colbias_precision == LIBXSMM_DATATYPE_BF16) {
/* load 16 bit values into xmm portion of the register */
if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU16,
i_gp_reg_mapping->gp_reg_help_2,
LIBXSMM_X86_GP_REG_UNDEF, 0,
(l_m * (i_micro_kernel_config->vector_length)) * 2,
( ( i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ) ) ? 'y' : 'z',
0, 2, 1, 0 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_help_2,
LIBXSMM_X86_GP_REG_UNDEF, 0,
(l_m * (i_micro_kernel_config->vector_length)) * 2,
( ( i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ) ) ? 'x' : 'y',
0, 0, 1, 0 );
}
/* convert 16 bit values into 32 bit (integer convert) */
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VPMOVSXWD,
i_micro_kernel_config->vector_name,
0, 0 );
/* shift 16 bits to the left to generate valid FP32 numbers */
libxsmm_x86_instruction_vec_compute_2reg_imm8(io_generated_code,
LIBXSMM_X86_INSTR_VPSLLD_I,
i_micro_kernel_config->vector_name,
0,
0,
16);
} else if (colbias_precision == LIBXSMM_DATATYPE_F32) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_help_2,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_m * (i_micro_kernel_config->vector_length))) * 4,
i_micro_kernel_config->vector_name,
0, ( l_m == (l_m_blocking - 1) ) ? i_micro_kernel_config->use_masking_a_c : 0, 1, 0 );
} else {
/* shouldn't happen */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_UNSUP_DATATYPE );
return;
}
/* Add colbias */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code, LIBXSMM_X86_INSTR_VADDPS, i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), 0, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
}
}
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_prepare_coeffs_sigmoid_ps_rational_78_avx_avx512( libxsmm_generated_code* io_generated_code,
libxsmm_micro_kernel_config* i_micro_kernel_config,
unsigned int reserved_zmms,
unsigned int reserved_mask_regs,
unsigned int temp_reg ) {
float pade78_sigm_array[16] = { 2027025.0f, 270270.0f, 6930.0f, 36.0f, 945945.0f, 51975.0f, 630.0f, 4.97f, -4.97f, 1.0f, -1.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f };
i_micro_kernel_config->vec_x2 = reserved_zmms - 1;
i_micro_kernel_config->vec_nom = reserved_zmms - 2;
i_micro_kernel_config->vec_denom = reserved_zmms - 3;
i_micro_kernel_config->vec_c0 = reserved_zmms - 4;
i_micro_kernel_config->vec_c1 = reserved_zmms - 5;
i_micro_kernel_config->vec_c2 = reserved_zmms - 6;
i_micro_kernel_config->vec_c3 = reserved_zmms - 7;
i_micro_kernel_config->vec_c1_d = reserved_zmms - 8;
i_micro_kernel_config->vec_c2_d = reserved_zmms - 9;
i_micro_kernel_config->vec_c3_d = reserved_zmms - 10;
i_micro_kernel_config->vec_hi_bound = reserved_zmms - 11;
i_micro_kernel_config->vec_lo_bound = reserved_zmms - 12;
i_micro_kernel_config->vec_ones = reserved_zmms - 13;
i_micro_kernel_config->vec_neg_ones = reserved_zmms - 14;
i_micro_kernel_config->vec_halves = reserved_zmms - 15;
libxsmm_x86_instruction_full_vec_load_of_constants ( io_generated_code, (const unsigned char *) pade78_sigm_array, "pade78_sigm_array_", i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_c0);
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_GEMM_SCRATCH_PTR, temp_reg );
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVUPS,
temp_reg,
LIBXSMM_X86_GP_REG_UNDEF, 0, 0,
i_micro_kernel_config->vector_name,
i_micro_kernel_config->vec_c0, 0, 1, 1 );
if (io_generated_code->arch < LIBXSMM_X86_AVX512) {
libxsmm_x86_instruction_full_vec_load_of_constants ( io_generated_code, (const unsigned char *) &pade78_sigm_array[8], "pade78_sigm_array2_", i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_c0);
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVUPS,
temp_reg,
LIBXSMM_X86_GP_REG_UNDEF, 0, 32,
i_micro_kernel_config->vector_name,
i_micro_kernel_config->vec_c0, 0, 1, 1 );
}
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
0, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_c0, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
4, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_c1, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
8, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_c2, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
12, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_c3, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
16, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_c1_d, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
20, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_c2_d, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
24, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_c3_d, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
28, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_hi_bound, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
32, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_lo_bound, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
36, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_ones, 0, 1, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
40, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_neg_ones, 0, 1, 0 );
if (io_generated_code->arch >= LIBXSMM_X86_AVX512) {
libxsmm_x86_instruction_vec_move( io_generated_code, i_micro_kernel_config->instruction_set, LIBXSMM_X86_INSTR_VBROADCASTSS, temp_reg, LIBXSMM_X86_GP_REG_UNDEF, 0,
44, i_micro_kernel_config->vector_name, i_micro_kernel_config->vec_halves, 0, 1, 0 );
}
i_micro_kernel_config->mask_hi = reserved_mask_regs - 1;
i_micro_kernel_config->mask_lo = reserved_mask_regs - 2;
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_setup_stack_frame_fill_stack_vars_v2( libxsmm_generated_code* io_generated_code,
const libxsmm_gemm_descriptor* i_xgemm_desc,
libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping ) {
int is_stride_brgemm = ((i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_STRIDE) > 0) ? 1 : 0;
int is_offset_brgemm = ((i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_OFFSET) > 0) ? 1 : 0;
int is_address_brgemm = ((i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) > 0) ? 1 : 0;
int is_brgemm = ((is_stride_brgemm == 1) || (is_offset_brgemm == 1) || (is_address_brgemm == 1)) ? 1 : 0;
int has_scf = ((LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) && (LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ))) ? 1 : 0;
int has_A_pf_ptr = (i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2_AHEAD || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD) ? 1 : 0;
int has_B_pf_ptr = (i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C || i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C || i_xgemm_desc->prefetch == LIBXSMM_PREFETCH_AL2CL2BL2_VIA_C ) ? 1 : 0;
unsigned int temp_reg = LIBXSMM_X86_GP_REG_R10;
if (has_scf == 1) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 112, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_INT8_SCF, temp_reg );
}
if (has_A_pf_ptr == 1) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 56, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_PFA_PTR, temp_reg );
}
if (has_B_pf_ptr == 1) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 88, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_PFB_PTR, temp_reg );
}
if ((is_brgemm == 1) && ( i_micro_kernel_config->decompress_A == 1)) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_reduce_count, LIBXSMM_X86_GP_REG_UNDEF, 0, 0, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_BRCOUNT, temp_reg );
}
if (is_offset_brgemm == 1) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 40, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_A_OFFS_BRGEMM_PTR, temp_reg );
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 72, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_B_OFFS_BRGEMM_PTR, temp_reg );
}
if (i_micro_kernel_config->fused_eltwise == 1) {
if (i_micro_kernel_config->has_colbias_act_fused == 1) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 128, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, temp_reg );
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 104, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, temp_reg );
}
if (i_micro_kernel_config->decompress_A == 1) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 48, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BITMAP_PTR, temp_reg );
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 160, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_DECOMPRESS_BUF, temp_reg );
}
if (i_micro_kernel_config->vnni_cvt_output_ext_buf == 1) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 104, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, temp_reg );
}
if (i_micro_kernel_config->fused_relu_bwd == 1) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 104, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_RELU_BITMASK_PTR, temp_reg );
}
if (i_micro_kernel_config->norm_to_normT_B_ext_buf == 1) {
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_help_1, LIBXSMM_X86_GP_REG_UNDEF, 0, 192, temp_reg, 0 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_TRANS_EXT_BUF_B, temp_reg );
}
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_setup_stack_frame_allocate_scratch( libxsmm_generated_code* io_generated_code,
const libxsmm_gemm_descriptor* i_xgemm_desc,
libxsmm_micro_kernel_config* i_micro_kernel_config ) {
unsigned int gemm_scratch_size = 0;
unsigned int scratch_pad_size = 0;
unsigned int transpose_scratch_size = 0;
unsigned int transpose_pad_size = 0;
int l_emu_amx = 0;
const char *const l_env_emu_amx = getenv("EMULATE_AMX");
if ( 0 == l_env_emu_amx ) {
} else {
l_emu_amx = atoi(l_env_emu_amx);
}
if (l_emu_amx > 0) {
int expand_scratch_factor = (i_micro_kernel_config->n_tiles == 1) ? 2 : 1;
i_micro_kernel_config->emulation_scratch_offset = expand_scratch_factor * i_xgemm_desc->n * i_xgemm_desc->ldc * 4 /*i_micro_kernel_config->datatype_size*/;
gemm_scratch_size = expand_scratch_factor * i_xgemm_desc->n * i_xgemm_desc->ldc * 4 /*i_micro_kernel_config->datatype_size*/ + 8 * 32 * 32 + 32 * 64 ;
if (LIBXSMM_DATATYPE_F32 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype )) {
i_micro_kernel_config->emulation_scratch_offset = 0;
gemm_scratch_size = 8 * 32 * 32 + 32 * 64 ;
}
} else {
if ((io_generated_code->arch >= LIBXSMM_X86_AVX512_SPR)) {
int expand_scratch_factor = (i_micro_kernel_config->n_tiles == 1) ? 2 : 1;
gemm_scratch_size = LIBXSMM_MAX(32*64, expand_scratch_factor * i_xgemm_desc->n * i_xgemm_desc->ldc * 4/*i_micro_kernel_config->datatype_size*/);
} else {
/* Allocate scratch for stashing 32 zmms */
if ( ((LIBXSMM_GEMM_FLAG_USE_XGEMM_EXT_ABI & i_xgemm_desc->flags) == LIBXSMM_GEMM_FLAG_USE_XGEMM_EXT_ABI) ) {
gemm_scratch_size = 32 * 64;
}
if (i_micro_kernel_config->vnni_format_C > 0) {
gemm_scratch_size = 32 * 64 + i_xgemm_desc->n * i_xgemm_desc->ldc * 4;
}
}
}
scratch_pad_size = (gemm_scratch_size % 64 == 0) ? 0 : ((gemm_scratch_size + 63)/64) * 64 - gemm_scratch_size;
gemm_scratch_size += scratch_pad_size;
if ( (LIBXSMM_GEMM_FLAG_TRANS_A & i_xgemm_desc->flags) > 0 ) {
transpose_scratch_size = i_xgemm_desc->m * i_xgemm_desc->k * LIBXSMM_TYPESIZE(LIBXSMM_GETENUM_OUT(i_xgemm_desc->datatype));
transpose_pad_size = (transpose_scratch_size % 64 == 0) ? 0 : ((transpose_scratch_size + 63)/64) * 64 - transpose_scratch_size;
transpose_scratch_size += transpose_pad_size;
}
if (gemm_scratch_size > 0) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, LIBXSMM_X86_GP_REG_RSP, gemm_scratch_size );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_GEMM_SCRATCH_PTR, LIBXSMM_X86_GP_REG_RSP );
}
/* Allocate scratch for the A transpose */
if (transpose_scratch_size > 0) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, LIBXSMM_X86_GP_REG_RSP, transpose_scratch_size );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_TRANSPOSE_PTR, LIBXSMM_X86_GP_REG_RSP );
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_setup_stack_frame( libxsmm_generated_code* io_generated_code,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
libxsmm_micro_kernel_config* i_micro_kernel_config ) {
unsigned int temp_reg = LIBXSMM_X86_GP_REG_R10;
libxsmm_x86_instruction_push_reg( io_generated_code, LIBXSMM_X86_GP_REG_RBP );
libxsmm_x86_instruction_alu_reg( io_generated_code, i_micro_kernel_config->alu_mov_instruction, LIBXSMM_X86_GP_REG_RSP, LIBXSMM_X86_GP_REG_RBP);
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, LIBXSMM_X86_GP_REG_RSP, 96 );
libxsmm_generator_gemm_setup_stack_frame_fill_stack_vars_v2( io_generated_code, i_xgemm_desc, i_micro_kernel_config, i_gp_reg_mapping );
/* The stack now looks like this:
* 10th param (if applicable) <-- RBP+80
* 9th param (if applicable) <-- RBP+72
* 8th param (if applicable) <-- RBP+64
* 7th param (if applicable) <-- RBP+56
* Return address <-- RBP+48
* Calle SAVED-regs <-- RBP[+8,+16,+24,+32,+40]
* Entry/saved RBP <-- RBP
* prefetch A ptr <-- RBP-8
* prefetch B ptr <-- RBP-16
* Offset A array ptr <-- RBP-24
* Offset B array ptr <-- RBP-32
* Int8 scaling factor <-- RBP-40
* GEMM_scratch ptr in stack (to be filled) <-- RBP-48
* Eltwise bias ptr <-- RBP-56
* Eltwise output_ptr <-- RBP-64
* Eltwise buf1_ptr <-- RBP-72
* Eltwise buf2_ptr <-- RBP-80
* Batch-reduce count <-- RBP-88,
* Transpose A ptr <-- RBP-96, RSP
*
*/
/* Now align RSP to 64 byte boundary */
libxsmm_x86_instruction_alu_imm_i64( io_generated_code, i_micro_kernel_config->alu_mov_instruction, temp_reg, 0xFFFFFFFFFFFFFFC0 );
libxsmm_x86_instruction_alu_reg( io_generated_code, LIBXSMM_X86_INSTR_ANDQ, temp_reg, LIBXSMM_X86_GP_REG_RSP);
/* Now alllocate in stack required GEMM scratch if necessary*/
libxsmm_generator_gemm_setup_stack_frame_allocate_scratch( io_generated_code, i_xgemm_desc, i_micro_kernel_config );
/* The stack at exit of setup looks like this:
*
* 10th param (if applicable) <-- RBP+80
* 9th param (if applicable) <-- RBP+72
* 8th param (if applicable) <-- RBP+64
* 7th param (if applicable) <-- RBP+56
* Return address <-- RBP+48
* Calle SAVED-regs <-- RBP[+8,+16,+24,+32,+40]
* Entry/saved RBP <-- RBP
* prefetch A ptr <-- RBP-8
* prefetch B ptr <-- RBP-16
* Offset A array ptr <-- RBP-24
* Offset B array ptr <-- RBP-32
* Int8 scaling factor <-- RBP-40
* GEMM_scratch ptr in stack <-- RBP-48
* Eltwise bias ptr <-- RBP-56
* Eltwise output_ptr <-- RBP-64
* Eltwise buf1_ptr <-- RBP-72
* Eltwise buf2_ptr <-- RBP-80
* Batch-reduce count <-- RBP-88
* Transpose A ptr <-- RBP-96, RSP
* [ Potentianl pad for 64b align ]
* GEMM scratch, 64b aligned <-- (RBP-48) contains this address
*
*/
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_destroy_stack_frame( libxsmm_generated_code* io_generated_code,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config ) {
LIBXSMM_UNUSED(i_xgemm_desc);
LIBXSMM_UNUSED(i_gp_reg_mapping);
libxsmm_x86_instruction_alu_reg( io_generated_code, i_micro_kernel_config->alu_mov_instruction, LIBXSMM_X86_GP_REG_RBP, LIBXSMM_X86_GP_REG_RSP);
libxsmm_x86_instruction_pop_reg( io_generated_code, LIBXSMM_X86_GP_REG_RBP );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_setup_fusion_microkernel_properties_v2(const libxsmm_gemm_descriptor* i_xgemm_desc,
libxsmm_micro_kernel_config* i_micro_kernel_config ) {
i_micro_kernel_config->fused_bcolbias = 0;
i_micro_kernel_config->fused_scolbias = 0;
i_micro_kernel_config->fused_relu = 0;
i_micro_kernel_config->fused_relu_nobitmask = 0;
i_micro_kernel_config->fused_relu_bwd = 0;
i_micro_kernel_config->fused_sigmoid = 0;
i_micro_kernel_config->overwrite_C = 1;
i_micro_kernel_config->vnni_format_C = 0;
i_micro_kernel_config->decompress_A = 0;
i_micro_kernel_config->sparsity_factor_A = 1;
i_micro_kernel_config->vnni_cvt_output_ext_buf = 0;
i_micro_kernel_config->norm_to_normT_B_ext_buf = 0;
i_micro_kernel_config->stride_b_trans = 0;
i_micro_kernel_config->fused_eltwise = 0;
i_micro_kernel_config->has_colbias_act_fused = 0;
i_micro_kernel_config->vnni_format_C = ((i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_VNNI_C) > 0) ? 1 : 0;
if ( ((LIBXSMM_GEMM_FLAG_USE_XGEMM_EXT_ABI & i_xgemm_desc->flags) == LIBXSMM_GEMM_FLAG_USE_XGEMM_EXT_ABI) ) {
i_micro_kernel_config->overwrite_C = ((i_xgemm_desc->internal_flags_2 & 0x4) > 0) ? 0 : 1;
if (i_xgemm_desc->eltw_cp_op == LIBXSMM_MELTW_OPERATION_UNARY) {
if (i_xgemm_desc->eltw_cp_param == LIBXSMM_MELTW_TYPE_UNARY_RELU) {
i_micro_kernel_config->has_colbias_act_fused = 1;
if ((i_xgemm_desc->eltw_cp_flags & LIBXSMM_MELTW_FLAG_UNARY_BITMASK_2BYTEMULT) > 0){
i_micro_kernel_config->fused_relu = 1;
} else {
i_micro_kernel_config->fused_relu_nobitmask = 1;
}
}
if (i_xgemm_desc->eltw_cp_param == LIBXSMM_MELTW_TYPE_UNARY_SIGMOID) {
i_micro_kernel_config->has_colbias_act_fused = 1;
i_micro_kernel_config->fused_sigmoid = 1;
}
if (i_xgemm_desc->eltw_cp_param == LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_VNNI2) {
i_micro_kernel_config->vnni_format_C = 1;
if (i_micro_kernel_config->overwrite_C == 0) {
i_micro_kernel_config->vnni_cvt_output_ext_buf = 1;
}
}
if (i_xgemm_desc->eltw_cp_param == LIBXSMM_MELTW_TYPE_UNARY_RELU_INV) {
i_micro_kernel_config->has_colbias_act_fused = 1;
i_micro_kernel_config->fused_relu_bwd = 1;
}
}
if (i_xgemm_desc->meltw_operation == LIBXSMM_MELTW_OPERATION_BINARY) {
if (i_xgemm_desc->meltw_param == LIBXSMM_MELTW_TYPE_BINARY_ADD) {
if (((i_xgemm_desc->meltw_flags & LIBXSMM_MELTW_FLAG_BINARY_BCAST_COL_IN_0) > 0 ) ||
((i_xgemm_desc->meltw_flags & LIBXSMM_MELTW_FLAG_BINARY_BCAST_COL_IN_1) > 0 )) {
i_micro_kernel_config->has_colbias_act_fused = 1;
if (i_xgemm_desc->meltw_datatype_aux == LIBXSMM_DATATYPE_BF16) {
i_micro_kernel_config->fused_bcolbias = 1;
}
if (i_xgemm_desc->meltw_datatype_aux == LIBXSMM_DATATYPE_F32) {
i_micro_kernel_config->fused_scolbias = 1;
}
}
}
}
if (i_xgemm_desc->eltw_ap_op == LIBXSMM_MELTW_OPERATION_UNARY) {
if ((i_xgemm_desc->internal_flags_2 & 0x1) > 0){
if (i_xgemm_desc->eltw_ap_param == LIBXSMM_MELTW_TYPE_UNARY_DECOMPRESS_SPARSE_FACTOR_1) {
i_micro_kernel_config->decompress_A = 1;
i_micro_kernel_config->sparsity_factor_A = 1;
}
if (i_xgemm_desc->eltw_ap_param == LIBXSMM_MELTW_TYPE_UNARY_DECOMPRESS_SPARSE_FACTOR_2) {
i_micro_kernel_config->decompress_A = 1;
i_micro_kernel_config->sparsity_factor_A = 2;
}
if (i_xgemm_desc->eltw_ap_param == LIBXSMM_MELTW_TYPE_UNARY_DECOMPRESS_SPARSE_FACTOR_4) {
i_micro_kernel_config->decompress_A = 1;
i_micro_kernel_config->sparsity_factor_A = 4;
}
if (i_xgemm_desc->eltw_ap_param == LIBXSMM_MELTW_TYPE_UNARY_DECOMPRESS_SPARSE_FACTOR_8) {
i_micro_kernel_config->decompress_A = 1;
i_micro_kernel_config->sparsity_factor_A = 8;
}
if (i_xgemm_desc->eltw_ap_param == LIBXSMM_MELTW_TYPE_UNARY_DECOMPRESS_SPARSE_FACTOR_16) {
i_micro_kernel_config->decompress_A = 1;
i_micro_kernel_config->sparsity_factor_A = 16;
}
if (i_xgemm_desc->eltw_ap_param == LIBXSMM_MELTW_TYPE_UNARY_DECOMPRESS_SPARSE_FACTOR_32) {
i_micro_kernel_config->decompress_A = 1;
i_micro_kernel_config->sparsity_factor_A = 32;
}
}
}
if (i_xgemm_desc->eltw_bp_op == LIBXSMM_MELTW_OPERATION_UNARY) {
if (i_xgemm_desc->eltw_bp_param == LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT) {
if ((i_xgemm_desc->internal_flags_2 & 0x2) > 0){
i_micro_kernel_config->norm_to_normT_B_ext_buf = 1;
i_micro_kernel_config->stride_b_trans = i_xgemm_desc->ldbp;
}
}
}
i_micro_kernel_config->fused_eltwise = (i_micro_kernel_config->has_colbias_act_fused == 1) ? 1: 0;
if (i_micro_kernel_config->decompress_A == 1) {
i_micro_kernel_config->fused_eltwise = 1;
}
if (i_micro_kernel_config->vnni_cvt_output_ext_buf == 1) {
i_micro_kernel_config->fused_eltwise = 1;
}
if (i_micro_kernel_config->norm_to_normT_B_ext_buf == 1) {
i_micro_kernel_config->fused_eltwise = 1;
}
if (i_micro_kernel_config->fused_relu_bwd == 1) {
i_micro_kernel_config->fused_eltwise = 1;
}
}
}
LIBXSMM_API_INTERN
int libxsmm_generator_gemm_get_rbp_relative_offset( libxsmm_gemm_stack_var stack_var ) {
/* The stack at exit of setup looks like this:
*
* 10th param (if applicable) <-- RBP+40
* 9th param (if applicable) <-- RBP+32
* 8th param (if applicable) <-- RBP+24
* 7th param (if applicable) <-- RBP+16
* Return address <-- RBP+8
* Entry/saved RBP <-- RBP
* prefetch A ptr <-- RBP-8
* prefetch B ptr <-- RBP-16
* Offset A array ptr <-- RBP-24
* Offset B array ptr <-- RBP-32
* Int8 scaling factor <-- RBP-40
* GEMM_scratch ptr in stack (to be filled) <-- RBP-48
* Eltwise bias ptr <-- RBP-56
* Eltwise output_ptr <-- RBP-64
* Eltwise buf1_ptr <-- RBP-72
* Eltwise buf2_ptr <-- RBP-80
* Batch-reduce count <-- RBP-88
* Transpose A ptr <-- RBP-96
* */
switch ( stack_var ) {
case LIBXSMM_GEMM_STACK_VAR_NONE:
return 0;
case LIBXSMM_GEMM_STACK_VAR_PFA_PTR:
return -8;
case LIBXSMM_GEMM_STACK_VAR_PFB_PTR:
return -16;
case LIBXSMM_GEMM_STACK_VAR_A_OFFS_BRGEMM_PTR:
return -24;
case LIBXSMM_GEMM_STACK_VAR_B_OFFS_BRGEMM_PTR:
return -32;
case LIBXSMM_GEMM_STACK_VAR_INT8_SCF:
return -40;
case LIBXSMM_GEMM_STACK_VAR_GEMM_SCRATCH_PTR:
return -48;
case LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR:
return -56;
case LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR:
return -64;
case LIBXSMM_GEMM_STACK_VAR_ELT_RELU_BITMASK_PTR:
return -72;
case LIBXSMM_GEMM_STACK_VAR_ELT_BUF1:
return -72;
case LIBXSMM_GEMM_STACK_VAR_ELT_BUF2:
return -80;
case LIBXSMM_GEMM_STACK_VAR_BRCOUNT:
return -88;
case LIBXSMM_GEMM_STACK_VAR_TRANS_EXT_BUF_B:
return -72;
case LIBXSMM_GEMM_STACK_VAR_TRANS_EXT_BUF_C:
return -80;
case LIBXSMM_GEMM_STACK_VAR_ELT_BITMAP_PTR:
return -72;
case LIBXSMM_GEMM_STACK_VAR_ELT_DECOMPRESS_BUF:
return -80;
case LIBXSMM_GEMM_STACK_VAR_ARG_7:
return 56;
case LIBXSMM_GEMM_STACK_VAR_ARG_8:
return 64;
case LIBXSMM_GEMM_STACK_VAR_ARG_9:
return 72;
case LIBXSMM_GEMM_STACK_VAR_ARG_10:
return 80;
case LIBXSMM_GEMM_STACK_VAR_TRANSPOSE_PTR:
return -96;
default:
return 0;
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_getval_stack_var( libxsmm_generated_code* io_generated_code,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
libxsmm_gemm_stack_var stack_var,
unsigned int i_gp_reg ) {
int offset = libxsmm_generator_gemm_get_rbp_relative_offset(stack_var);
/* make sure we requested a legal stack var */
if (offset == 0) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_GENERAL );
return;
}
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, LIBXSMM_X86_GP_REG_RBP, LIBXSMM_X86_GP_REG_UNDEF, 0, offset, i_gp_reg, 0 );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_setval_stack_var( libxsmm_generated_code* io_generated_code,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
libxsmm_gemm_stack_var stack_var,
unsigned int i_gp_reg ) {
int offset = libxsmm_generator_gemm_get_rbp_relative_offset(stack_var);
/* make sure we requested to set a legal stack var */
if (offset >= 0) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_GENERAL );
return;
}
libxsmm_x86_instruction_alu_mem( io_generated_code, i_micro_kernel_config->alu_mov_instruction, LIBXSMM_X86_GP_REG_RBP, LIBXSMM_X86_GP_REG_UNDEF, 0, offset, i_gp_reg, 1 );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_init_micro_kernel_config_fullvector( libxsmm_micro_kernel_config* io_micro_kernel_config,
const unsigned int i_arch,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_use_masking_a_c ) {
memset(io_micro_kernel_config, 0, sizeof(*io_micro_kernel_config)); /* avoid warning "maybe used uninitialized" */
libxsmm_generator_gemm_setup_fusion_microkernel_properties_v2(i_xgemm_desc, io_micro_kernel_config);
if ( (i_arch <= LIBXSMM_TARGET_ARCH_GENERIC) || (i_arch > LIBXSMM_X86_ALLFEAT) ) {
io_micro_kernel_config->instruction_set = LIBXSMM_TARGET_ARCH_GENERIC;
io_micro_kernel_config->vector_reg_count = 0;
io_micro_kernel_config->use_masking_a_c = 0;
io_micro_kernel_config->vector_name = 'a';
io_micro_kernel_config->vector_length = 0;
io_micro_kernel_config->datatype_size_in = 0;
io_micro_kernel_config->datatype_size_out = 0;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
} else if ( i_arch <= LIBXSMM_X86_SSE42 ) {
io_micro_kernel_config->instruction_set = i_arch;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'x';
if ( LIBXSMM_DATATYPE_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 2;
io_micro_kernel_config->datatype_size_in = 8;
io_micro_kernel_config->datatype_size_out = 8;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPD;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPD;
}
if ( i_arch == LIBXSMM_X86_GENERIC ) {
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_SHUFPD;
} else {
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVDDUP;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVAPD;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVUPD;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULPD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDPD;
} else {
io_micro_kernel_config->vector_length = 4;
io_micro_kernel_config->datatype_size_in = 4;
io_micro_kernel_config->datatype_size_out = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_SHUFPS;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVAPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVAPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPS;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULPS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDPS;
}
} else if ( i_arch <= LIBXSMM_X86_AVX2 ) {
io_micro_kernel_config->instruction_set = i_arch;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'y';
if ( LIBXSMM_DATATYPE_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 4;
io_micro_kernel_config->datatype_size_in = 8;
io_micro_kernel_config->datatype_size_out = 8;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPD;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD;
}
} else {
io_micro_kernel_config->vector_length = 8;
io_micro_kernel_config->datatype_size_in = 4;
io_micro_kernel_config->datatype_size_out = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPS;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
}
}
} else if ( i_arch < LIBXSMM_X86_AVX512) {
io_micro_kernel_config->instruction_set = i_arch;
io_micro_kernel_config->vector_reg_count = 32;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'y';
if ( LIBXSMM_DATATYPE_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 4;
io_micro_kernel_config->datatype_size_in = 8;
io_micro_kernel_config->datatype_size_out = 8;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD;
} else {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD;
} else if ( LIBXSMM_DATATYPE_F32 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 8;
io_micro_kernel_config->datatype_size_in = 4;
io_micro_kernel_config->datatype_size_out = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else if ( LIBXSMM_DATATYPE_I16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 8;
io_micro_kernel_config->datatype_size_in = 4;
if ( LIBXSMM_DATATYPE_I16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->datatype_size_out = 2;
} else {
io_micro_kernel_config->datatype_size_out = 4;
}
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VPDPWSSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VPADDD;
} else if ( LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 8;
io_micro_kernel_config->datatype_size_in = 4;
if ( LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->datatype_size_out = 1;
} else {
io_micro_kernel_config->datatype_size_out = 4;
}
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VPDPBUSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VPADDD;
} else if ( (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) &&
((i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_VNNI_A) > 0) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 8;
io_micro_kernel_config->datatype_size_in = 4;
if ( LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->datatype_size_out = 2;
} else {
io_micro_kernel_config->datatype_size_out = 4;
}
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VDPBF16PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else if ( (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) &&
((i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_VNNI_A) == 0) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 8;
io_micro_kernel_config->datatype_size_in = 2;
if ( LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->datatype_size_out = 2;
} else {
io_micro_kernel_config->datatype_size_out = 4;
}
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTW;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else {
/* shouldn't happen as we caught this case earlier */
io_micro_kernel_config->instruction_set = LIBXSMM_TARGET_ARCH_GENERIC;
io_micro_kernel_config->vector_reg_count = 0;
io_micro_kernel_config->use_masking_a_c = 0;
io_micro_kernel_config->vector_name = 'a';
io_micro_kernel_config->vector_length = 0;
io_micro_kernel_config->datatype_size_in = 0;
io_micro_kernel_config->datatype_size_out = 0;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
} else if ( i_arch <= LIBXSMM_X86_ALLFEAT ) {
io_micro_kernel_config->instruction_set = i_arch;
io_micro_kernel_config->vector_reg_count = 32;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'z';
if ( LIBXSMM_DATATYPE_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 8;
io_micro_kernel_config->datatype_size_in = 8;
io_micro_kernel_config->datatype_size_out = 8;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD;
} else {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD;
} else if ( LIBXSMM_DATATYPE_F32 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 16;
io_micro_kernel_config->datatype_size_in = 4;
io_micro_kernel_config->datatype_size_out = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else if ( LIBXSMM_DATATYPE_I16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 16;
io_micro_kernel_config->datatype_size_in = 4;
if ( LIBXSMM_DATATYPE_I16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->datatype_size_out = 2;
} else {
io_micro_kernel_config->datatype_size_out = 4;
}
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VPDPWSSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VPADDD;
} else if ( LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 16;
io_micro_kernel_config->datatype_size_in = 4;
if ( LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->datatype_size_out = 1;
} else {
io_micro_kernel_config->datatype_size_out = 4;
}
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VPDPBUSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VPADDD;
} else if ( (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) &&
((i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_VNNI_A) > 0) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 16;
io_micro_kernel_config->datatype_size_in = 4;
if ( LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->datatype_size_out = 2;
} else {
io_micro_kernel_config->datatype_size_out = 4;
}
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VDPBF16PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else if ( (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype )) &&
((i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_VNNI_A) == 0) ) {
/* C is 32bit, so we treat all 3 matrices as 32bit element arrays */
io_micro_kernel_config->vector_length = 16;
io_micro_kernel_config->datatype_size_in = 2;
if ( LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->datatype_size_out = 2;
} else {
io_micro_kernel_config->datatype_size_out = 4;
}
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VPBROADCASTW;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
if ( (i_use_masking_a_c == 0) ) {
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
}
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VPXORD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else {
/* shouldn't happen as we caught this case earlier */
io_micro_kernel_config->instruction_set = LIBXSMM_TARGET_ARCH_GENERIC;
io_micro_kernel_config->vector_reg_count = 0;
io_micro_kernel_config->use_masking_a_c = 0;
io_micro_kernel_config->vector_name = 'a';
io_micro_kernel_config->vector_length = 0;
io_micro_kernel_config->datatype_size_in = 0;
io_micro_kernel_config->datatype_size_out = 0;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
} else {
/* that should no happen */
}
io_micro_kernel_config->prefetch_instruction = LIBXSMM_X86_INSTR_PREFETCHT1;
io_micro_kernel_config->alu_add_instruction = LIBXSMM_X86_INSTR_ADDQ;
io_micro_kernel_config->alu_sub_instruction = LIBXSMM_X86_INSTR_SUBQ;
io_micro_kernel_config->alu_cmp_instruction = LIBXSMM_X86_INSTR_CMPQ;
io_micro_kernel_config->alu_jmp_instruction = LIBXSMM_X86_INSTR_JL;
io_micro_kernel_config->alu_mov_instruction = LIBXSMM_X86_INSTR_MOVQ;
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_init_micro_kernel_config_halfvector( libxsmm_micro_kernel_config* io_micro_kernel_config,
const unsigned int i_arch,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_use_masking_a_c ) {
libxsmm_generator_gemm_setup_fusion_microkernel_properties_v2(i_xgemm_desc, io_micro_kernel_config);
if ( (i_arch <= LIBXSMM_TARGET_ARCH_GENERIC) || (i_arch > LIBXSMM_X86_ALLFEAT) ) {
io_micro_kernel_config->instruction_set = LIBXSMM_TARGET_ARCH_GENERIC;
io_micro_kernel_config->vector_reg_count = 0;
io_micro_kernel_config->use_masking_a_c = 0;
io_micro_kernel_config->vector_name = 'a';
io_micro_kernel_config->vector_length = 0;
io_micro_kernel_config->datatype_size_in = 0;
io_micro_kernel_config->datatype_size_out = 0;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
} else if ( i_arch <= LIBXSMM_X86_SSE42 ) {
#if !defined(NDEBUG)
fprintf(stderr, "LIBXSMM WARNING, libxsmm_generator_gemm_init_micro_kernel_config_halfvector, redirecting to scalar, please fix the generation code!!!\n");
#endif
libxsmm_generator_gemm_init_micro_kernel_config_scalar( io_micro_kernel_config, i_arch, i_xgemm_desc, i_use_masking_a_c );
} else if ( i_arch <= LIBXSMM_X86_AVX2 ) {
io_micro_kernel_config->instruction_set = LIBXSMM_X86_AVX;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'x';
if ( LIBXSMM_DATATYPE_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 2;
io_micro_kernel_config->datatype_size_in = 8;
io_micro_kernel_config->datatype_size_out = 8;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VMOVDDUP;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPD;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPD;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPD;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPD;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
} else {
io_micro_kernel_config->vector_length = 4;
io_micro_kernel_config->datatype_size_in = 4;
io_micro_kernel_config->datatype_size_out = 4;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
} else {
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VBROADCASTSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
if ( (LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0 ) {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVAPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVNTPS;
} else {
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVUPS;
}
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPS;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULPS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDPS;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231PS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
}
} else if ( i_arch <= LIBXSMM_X86_ALLFEAT ) {
#if !defined(NDEBUG)
fprintf(stderr, "LIBXSMM WARNING, libxsmm_generator_gemm_init_micro_kernel_config_halfvector, AVX512 redirecting to fullvector!\n");
#endif
libxsmm_generator_gemm_init_micro_kernel_config_fullvector( io_micro_kernel_config, i_arch, i_xgemm_desc, i_use_masking_a_c );
} else {
/* should not happen */
}
io_micro_kernel_config->prefetch_instruction = LIBXSMM_X86_INSTR_PREFETCHT1;
io_micro_kernel_config->alu_add_instruction = LIBXSMM_X86_INSTR_ADDQ;
io_micro_kernel_config->alu_sub_instruction = LIBXSMM_X86_INSTR_SUBQ;
io_micro_kernel_config->alu_cmp_instruction = LIBXSMM_X86_INSTR_CMPQ;
io_micro_kernel_config->alu_jmp_instruction = LIBXSMM_X86_INSTR_JL;
io_micro_kernel_config->alu_mov_instruction = LIBXSMM_X86_INSTR_MOVQ;
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_init_micro_kernel_config_scalar( libxsmm_micro_kernel_config* io_micro_kernel_config,
const unsigned int i_arch,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_use_masking_a_c ) {
libxsmm_generator_gemm_setup_fusion_microkernel_properties_v2(i_xgemm_desc, io_micro_kernel_config);
if ( ( i_arch <= LIBXSMM_TARGET_ARCH_GENERIC ) || ( i_arch > LIBXSMM_X86_ALLFEAT ) ) {
io_micro_kernel_config->instruction_set = LIBXSMM_TARGET_ARCH_GENERIC;
io_micro_kernel_config->vector_reg_count = 0;
io_micro_kernel_config->use_masking_a_c = 0;
io_micro_kernel_config->vector_name = 'a';
io_micro_kernel_config->vector_length = 0;
io_micro_kernel_config->datatype_size_in = 0;
io_micro_kernel_config->datatype_size_out = 0;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
} else if ( i_arch <= LIBXSMM_X86_SSE42 ) {
io_micro_kernel_config->instruction_set = i_arch;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'x';
if ( LIBXSMM_DATATYPE_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 1;
io_micro_kernel_config->datatype_size_in = 8;
io_micro_kernel_config->datatype_size_out = 8;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVSD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVSD;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPD;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDSD;
} else {
io_micro_kernel_config->vector_length = 1;
io_micro_kernel_config->datatype_size_in = 4;
io_micro_kernel_config->datatype_size_out = 4;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_MOVSS;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_XORPS;
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_MULSS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_ADDSS;
}
} else if ( i_arch <= LIBXSMM_X86_ALLFEAT ) {
io_micro_kernel_config->instruction_set = i_arch;
io_micro_kernel_config->vector_reg_count = 16;
io_micro_kernel_config->use_masking_a_c = i_use_masking_a_c;
io_micro_kernel_config->vector_name = 'x';
if ( LIBXSMM_DATATYPE_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
io_micro_kernel_config->vector_length = 1;
io_micro_kernel_config->datatype_size_in = 8;
io_micro_kernel_config->datatype_size_out = 8;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSD;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSD;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSD;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVSD;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPD;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULSD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDSD;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231SD;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
} else {
io_micro_kernel_config->vector_length = 1;
io_micro_kernel_config->datatype_size_in = 4;
io_micro_kernel_config->datatype_size_out = 4;
io_micro_kernel_config->a_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSS;
io_micro_kernel_config->b_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSS;
io_micro_kernel_config->b_shuff_instruction = LIBXSMM_X86_INSTR_UNDEF;
io_micro_kernel_config->c_vmove_instruction = LIBXSMM_X86_INSTR_VMOVSS;
io_micro_kernel_config->c_vmove_nts_instruction = LIBXSMM_X86_INSTR_VMOVSS;
io_micro_kernel_config->vxor_instruction = LIBXSMM_X86_INSTR_VXORPS;
if ( i_arch == LIBXSMM_X86_AVX ) {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VMULSS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_VADDSS;
} else {
io_micro_kernel_config->vmul_instruction = LIBXSMM_X86_INSTR_VFMADD231SS;
io_micro_kernel_config->vadd_instruction = LIBXSMM_X86_INSTR_UNDEF;
}
}
} else {
/* should not happen */
}
io_micro_kernel_config->prefetch_instruction = LIBXSMM_X86_INSTR_PREFETCHT1;
io_micro_kernel_config->alu_add_instruction = LIBXSMM_X86_INSTR_ADDQ;
io_micro_kernel_config->alu_sub_instruction = LIBXSMM_X86_INSTR_SUBQ;
io_micro_kernel_config->alu_cmp_instruction = LIBXSMM_X86_INSTR_CMPQ;
io_micro_kernel_config->alu_jmp_instruction = LIBXSMM_X86_INSTR_JL;
io_micro_kernel_config->alu_mov_instruction = LIBXSMM_X86_INSTR_MOVQ;
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_add_flop_counter( libxsmm_generated_code* io_generated_code,
const libxsmm_gemm_descriptor* i_xgemm_desc ) {
if ( io_generated_code->code_type == 0 ) {
char l_new_code[512];
const unsigned int l_max_code_length = sizeof(l_new_code) - 1;
int l_code_length = 0;
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#ifndef NDEBUG\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#ifdef _OPENMP\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#pragma omp atomic\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#endif\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "libxsmm_num_total_flops += %u;\n", 2u * i_xgemm_desc->m * i_xgemm_desc->n * i_xgemm_desc->k);
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF( l_new_code, l_max_code_length, "#endif\n" );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_header_kloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int i_m_blocking,
const unsigned int i_k_blocking ) {
LIBXSMM_UNUSED(i_m_blocking);
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_kloop, 0);
libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_kloop, i_k_blocking);
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_footer_kloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_m_blocking,
const unsigned int i_max_blocked_k,
const unsigned int i_kloop_complete ) {
LIBXSMM_UNUSED(i_m_blocking);
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_kloop, i_max_blocked_k );
libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker );
if ( i_kloop_complete != 0 ) {
int l_b_offset = 0;
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) > 0 ) {
l_b_offset = i_xgemm_desc->ldb * i_xgemm_desc->k * i_micro_kernel_config->datatype_size_in;
} else {
l_b_offset = i_xgemm_desc->k * i_micro_kernel_config->datatype_size_in;
}
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_b, l_b_offset );
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_header_reduceloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_reduce_loop, 0);
libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_footer_reduceloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc) {
LIBXSMM_UNUSED(i_xgemm_desc);
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_reduce_loop, 1);
libxsmm_x86_instruction_alu_reg( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_reduce_count, i_gp_reg_mapping->gp_reg_reduce_loop);
libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_header_nloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int i_n_init,
const unsigned int i_n_blocking) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_nloop, i_n_init );
libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_nloop, i_n_blocking );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_footer_nloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_n_blocking,
const unsigned int i_n_done ) {
if ( LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
#if 0
if (i_micro_kernel_config->vnni_format_C == 0) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c,
(i_n_blocking*(i_xgemm_desc->ldc)*2 /*(i_micro_kernel_config->datatype_size/2)*/) - ((i_xgemm_desc->m) * 2 /*(i_micro_kernel_config->datatype_size/2)*/) );
} else {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c,
(i_n_blocking*(i_xgemm_desc->ldc)*2 /*(i_micro_kernel_config->datatype_size/2)*/) - ((i_xgemm_desc->m) * 2 * 2 /*(i_micro_kernel_config->datatype_size/2)*/) );
}
#else
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c,
(i_n_blocking*(i_xgemm_desc->ldc)*2 /*(i_micro_kernel_config->datatype_size/2)*/) - ((i_xgemm_desc->m) * 2 /*(i_micro_kernel_config->datatype_size/2)*/) );
#endif
} else if ( LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c,
(i_n_blocking*(i_xgemm_desc->ldc)/**(i_micro_kernel_config->datatype_size/4)*/) - ((i_xgemm_desc->m) /** (i_micro_kernel_config->datatype_size/4)*/) );
} else {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c,
(i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size_out)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size_out)) );
}
/* Also adjust eltwise pointers */
if ((i_micro_kernel_config->fused_relu == 1) || (i_micro_kernel_config->vnni_cvt_output_ext_buf == 1) || (i_micro_kernel_config->fused_relu_bwd == 1) || (i_micro_kernel_config->fused_bcolbias == 1) || (i_micro_kernel_config->fused_scolbias == 1) || (i_micro_kernel_config->overwrite_C == 0)) {
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
}
if ((i_micro_kernel_config->fused_relu == 1) && (i_micro_kernel_config->overwrite_C == 1) ) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, (i_n_blocking*i_xgemm_desc->ldc)/8 - ((i_xgemm_desc->m/8) ) );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if (i_micro_kernel_config->vnni_cvt_output_ext_buf == 1) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, (i_n_blocking*(i_xgemm_desc->ldc)*2/*(i_micro_kernel_config->datatype_size/2)*/) - ((i_xgemm_desc->m) * 2 * 2 /*(i_micro_kernel_config->datatype_size/2)*/) );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if (i_micro_kernel_config->fused_relu_bwd == 1) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_RELU_BITMASK_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, (i_n_blocking*i_xgemm_desc->ldc)/8 - ((i_xgemm_desc->m/8) ) );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_RELU_BITMASK_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
/* In this case also advance the output ptr */
if (i_micro_kernel_config->overwrite_C == 0) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, (i_n_blocking*(i_xgemm_desc->ldc)*2/*(i_micro_kernel_config->datatype_size/2)*/) - ((i_xgemm_desc->m) * 2 /*(i_micro_kernel_config->datatype_size/2)*/) );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if (i_micro_kernel_config->fused_bcolbias == 1) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0, ( i_xgemm_desc->m * 2/*(i_micro_kernel_config->datatype_size/2)*/) );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if (i_micro_kernel_config->fused_scolbias == 1) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0, ( i_xgemm_desc->m * 4/*i_micro_kernel_config->datatype_size*/) );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if ((i_micro_kernel_config->fused_relu == 1) || (i_micro_kernel_config->vnni_cvt_output_ext_buf == 1) || (i_micro_kernel_config->fused_relu_bwd == 1) || (i_micro_kernel_config->fused_bcolbias == 1) || (i_micro_kernel_config->fused_scolbias == 1) || (i_micro_kernel_config->overwrite_C == 0)) {
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
}
/* B prefetch */
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ) {
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) == 0 ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_b_prefetch,
(i_n_blocking*(i_xgemm_desc->ldc)*i_micro_kernel_config->datatype_size_in) - ((i_xgemm_desc->m)*i_micro_kernel_config->datatype_size_in) );
}
}
#if 0
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_c_prefetch,
(i_n_blocking*(i_xgemm_desc->ldc)*(i_micro_kernel_config->datatype_size_out)) - ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size_out)) );
}
#endif
if (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) {
/* handle trans B */
int l_b_offset = 0;
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) > 0 ) {
l_b_offset = i_n_blocking * i_micro_kernel_config->datatype_size_in;
} else {
l_b_offset = i_n_blocking * i_xgemm_desc->ldb * i_micro_kernel_config->datatype_size_in;
}
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_generator_gemm_header_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_help_0, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size_in)) );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_b,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_help_0, l_b_offset );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_b,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ) {
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_help_0, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size_in)) );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
}
libxsmm_generator_gemm_footer_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config, i_xgemm_desc);
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
} else {
/* handle trans B */
int l_b_offset = 0;
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) > 0 ) {
l_b_offset = i_n_blocking * i_micro_kernel_config->datatype_size_in;
} else {
l_b_offset = i_n_blocking * i_xgemm_desc->ldb * i_micro_kernel_config->datatype_size_in;
}
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_b, l_b_offset );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_a, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size_in)) );
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch, ((i_xgemm_desc->m)*(i_micro_kernel_config->datatype_size_in)) );
}
}
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_nloop, i_n_done );
libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_header_mloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const unsigned int i_m_init,
const unsigned int i_m_blocking ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_mov_instruction, i_gp_reg_mapping->gp_reg_mloop, i_m_init );
libxsmm_x86_instruction_register_jump_back_label( io_generated_code, io_loop_label_tracker );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_mloop, i_m_blocking );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_footer_mloop( libxsmm_generated_code* io_generated_code,
libxsmm_loop_label_tracker* io_loop_label_tracker,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_m_blocking,
const unsigned int i_m_done ) {
/* advance C pointer */
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_c, i_m_blocking*(i_micro_kernel_config->datatype_size_out) );
/* Also adjust eltwise pointers */
if ((i_micro_kernel_config->fused_relu == 1) || (i_micro_kernel_config->vnni_cvt_output_ext_buf == 1) || (i_micro_kernel_config->fused_relu_bwd == 1) || (i_micro_kernel_config->fused_bcolbias == 1) || (i_micro_kernel_config->fused_scolbias == 1) || (i_micro_kernel_config->overwrite_C == 0)) {
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
}
if ((i_micro_kernel_config->fused_relu == 1) && (i_micro_kernel_config->overwrite_C == 1) ) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, i_m_blocking/8 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if (i_micro_kernel_config->vnni_cvt_output_ext_buf == 1) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, i_m_blocking*2*2/*(i_micro_kernel_config->datatype_size/2)*/ );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if (i_micro_kernel_config->fused_relu_bwd == 1) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_RELU_BITMASK_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, i_m_blocking/8 );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_RELU_BITMASK_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if (i_micro_kernel_config->overwrite_C == 0) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, i_m_blocking*2/*(i_micro_kernel_config->datatype_size/2)*/ );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_OUTPUT_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if (i_micro_kernel_config->fused_bcolbias == 1) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, i_m_blocking * 2/*(i_micro_kernel_config->datatype_size/2)*/ );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if (i_micro_kernel_config->fused_scolbias == 1) {
libxsmm_generator_gemm_getval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction, i_gp_reg_mapping->gp_reg_help_0, i_m_blocking * 4 /*i_micro_kernel_config->datatype_size*/ );
libxsmm_generator_gemm_setval_stack_var( io_generated_code, i_micro_kernel_config, LIBXSMM_GEMM_STACK_VAR_ELT_BIAS_PTR, i_gp_reg_mapping->gp_reg_help_0 );
}
if ((i_micro_kernel_config->fused_relu == 1) || (i_micro_kernel_config->vnni_cvt_output_ext_buf == 1) || (i_micro_kernel_config->fused_relu_bwd == 1) || (i_micro_kernel_config->fused_bcolbias == 1) || (i_micro_kernel_config->fused_scolbias == 1) || (i_micro_kernel_config->overwrite_C == 0)) {
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
}
/* C prefetch */
#if 0
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_c_prefetch, i_m_blocking*(i_micro_kernel_config->datatype_size_out) );
}
#endif
/* B prefetch */
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ) {
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) == 0 ) {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_add_instruction,
i_gp_reg_mapping->gp_reg_b_prefetch, i_m_blocking*i_micro_kernel_config->datatype_size_in );
}
}
/* A prefetch */
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C) {
if (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) {
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2 ) {
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_generator_gemm_header_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0,
((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size_in) * (i_xgemm_desc->lda) ) -
(i_m_blocking * (i_micro_kernel_config->datatype_size_in)) );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a_prefetch,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
libxsmm_generator_gemm_footer_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config, i_xgemm_desc);
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
}
} else {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_a_prefetch,
((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size_in) * (i_xgemm_desc->lda) ) -
(i_m_blocking * (i_micro_kernel_config->datatype_size_in)) );
}
}
/* advance A pointer */
if (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_ADDRESS) {
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
libxsmm_x86_instruction_push_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_generator_gemm_header_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
0 );
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_help_0,
((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size_in) * (i_xgemm_desc->lda) ) - (i_m_blocking * (i_micro_kernel_config->datatype_size_in)) );
libxsmm_x86_instruction_alu_mem( io_generated_code,
i_micro_kernel_config->alu_mov_instruction,
i_gp_reg_mapping->gp_reg_a,
i_gp_reg_mapping->gp_reg_reduce_loop, 8,
0,
i_gp_reg_mapping->gp_reg_help_0,
1 );
libxsmm_generator_gemm_footer_reduceloop( io_generated_code, io_loop_label_tracker, i_gp_reg_mapping, i_micro_kernel_config, i_xgemm_desc);
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_reduce_loop );
libxsmm_x86_instruction_pop_reg( io_generated_code, i_gp_reg_mapping->gp_reg_help_0 );
} else {
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_sub_instruction, i_gp_reg_mapping->gp_reg_a,
((i_xgemm_desc->k) * (i_micro_kernel_config->datatype_size_in) * (i_xgemm_desc->lda) ) - (i_m_blocking * (i_micro_kernel_config->datatype_size_in)) );
}
/* loop handling */
libxsmm_x86_instruction_alu_imm( io_generated_code, i_micro_kernel_config->alu_cmp_instruction, i_gp_reg_mapping->gp_reg_mloop, i_m_done );
libxsmm_x86_instruction_jump_back_to_label( io_generated_code, i_micro_kernel_config->alu_jmp_instruction, io_loop_label_tracker );
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_load_C( libxsmm_generated_code* io_generated_code,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_m_blocking,
const unsigned int i_n_blocking ) {
unsigned int l_m_blocking, l_vec_reg_acc_start;
/* register blocking counter in n */
unsigned int l_n = 0;
/* register blocking counter in m */
unsigned int l_m = 0;
assert(0 < i_micro_kernel_config->vector_length);
/* deriving register blocking from kernel config */
l_m_blocking = ( i_m_blocking % i_micro_kernel_config->vector_length == 0 ) ? i_m_blocking/i_micro_kernel_config->vector_length : (i_m_blocking/i_micro_kernel_config->vector_length)+1;
/* start register of accumulator */
l_vec_reg_acc_start = i_micro_kernel_config->vector_reg_count - (i_n_blocking * l_m_blocking);
#if !defined(NDEBUG)
/* Do some test if it is possible to generate the requested code.
This is not done in release mode and therefore bad
things might happen.... HUAAH */
if (i_micro_kernel_config->instruction_set == LIBXSMM_X86_GENERIC ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_SSE3 ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_SSE42 ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX2 ) {
if ( (i_n_blocking > 3) || (i_n_blocking < 1) || (i_m_blocking < 1) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256 ||i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CLX
||i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CPX) {
if ( (i_n_blocking > 28) || (i_n_blocking < 1) || (l_m_blocking < 1) || (l_m_blocking > 8) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512_CORE ) {
if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (l_m_blocking != 1) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE ) {
if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (l_m_blocking < 1) || (l_m_blocking > 6) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else {}
#if 0
if ( i_m_blocking % i_micro_kernel_config->vector_length != 0 ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_M_BLOCK );
return;
}
#endif
#endif /*!defined(NDEBUG)*/
/* load C accumulator */
if (0 == (LIBXSMM_GEMM_FLAG_BETA_0 & i_xgemm_desc->flags)) { /* Beta=1 */
/* pure BF16 kernel */
if ( ( ((i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE) && (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT)) ||
((i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ))
) && ( (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) {
/* we add when scaling during conversion to FP32 */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
/* load 16 bit values into xmm portion of the register */
if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU16,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
( ( i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ) ) ? 'y' : 'z',
0, 2, 1, 0 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
( ( i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ) ) ? 'x' : 'y',
0, 0, 1, 0 );
}
/* convert 16 bit values into 32 bit (integer convert) */
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VPMOVSXWD,
i_micro_kernel_config->vector_name,
0, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
/* shift 16 bits to the left to generate valid FP32 numbers */
libxsmm_x86_instruction_vec_compute_2reg_imm8(io_generated_code,
LIBXSMM_X86_INSTR_VPSLLD_I,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n),
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n),
16);
}
}
/* Check if we have to add bias */
if (i_micro_kernel_config->fused_bcolbias == 1) {
libxsmm_generator_gemm_add_colbias_to_2D_block( io_generated_code, i_gp_reg_mapping, i_micro_kernel_config,
LIBXSMM_DATATYPE_BF16, l_vec_reg_acc_start, l_m_blocking, i_n_blocking );
}
/* pure int8 kernel */
} else if ( ( ((i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CORE) && (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT)) ||
((i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ) )
) &&
( (LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) {
/* we need to up convert int8 to int32 */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
/* load 16 bit values into xmm portion of the register*/
if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU8,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
( ( i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX2) && ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512 ) ) ? 'y' : 'z',
0, 2, 1, 0 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
'x',
0, 0, 1, 0 );
}
/* convert 8 bit values into 32 bit (integer convert) */
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_C_UNSIGNED) != 0 ) {
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VPMOVZXBD,
i_micro_kernel_config->vector_name,
0, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
} else {
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VPMOVSXBD,
i_micro_kernel_config->vector_name,
0, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
}
}
}
} else {
/* adding to C, so let's load C */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
/* we only mask the last m-blocked load */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
i_micro_kernel_config->c_vmove_instruction,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), ( l_m == (l_m_blocking - 1) ) ? i_micro_kernel_config->use_masking_a_c : 0, 1, 0 );
}
#if 0
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) {
for (l_m = 0; l_m < l_m_blocking; l_m += l_m++ ) {
libxsmm_x86_instruction_prefetch( io_generated_code,
i_micro_kernel_config->prefetch_instruction,
i_gp_reg_mapping->gp_reg_c_prefetch,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out));
}
}
#endif
}
/* Check if we have to add bias */
if (i_micro_kernel_config->fused_scolbias == 1) {
libxsmm_generator_gemm_add_colbias_to_2D_block( io_generated_code, i_gp_reg_mapping, i_micro_kernel_config,
LIBXSMM_DATATYPE_F32, l_vec_reg_acc_start, l_m_blocking, i_n_blocking );
}
}
} else {
if (i_micro_kernel_config->fused_scolbias == 1) {
libxsmm_generator_gemm_load_colbias_to_2D_block( io_generated_code, i_gp_reg_mapping, i_micro_kernel_config,
LIBXSMM_DATATYPE_F32, l_vec_reg_acc_start, l_m_blocking, i_n_blocking );
} else if (i_micro_kernel_config->fused_bcolbias == 1) {
libxsmm_generator_gemm_load_colbias_to_2D_block( io_generated_code, i_gp_reg_mapping, i_micro_kernel_config,
LIBXSMM_DATATYPE_BF16, l_vec_reg_acc_start, l_m_blocking, i_n_blocking );
} else {
/* overwriting C, so let's xout accumulator */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
if ( io_generated_code->arch >= LIBXSMM_X86_AVX ) {
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
i_micro_kernel_config->vxor_instruction,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n),
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n),
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
} else {
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
i_micro_kernel_config->vxor_instruction,
i_micro_kernel_config->vector_name,
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n),
l_vec_reg_acc_start + l_m + (l_m_blocking * l_n) );
}
}
#if 0
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_CL2 ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2CL2BL2_VIA_C ) {
for (l_m = 0; l_m < l_m_blocking; l_m += l_m++ ) {
libxsmm_x86_instruction_prefetch( io_generated_code,
i_micro_kernel_config->prefetch_instruction,
i_gp_reg_mapping->gp_reg_c_prefetch,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out));
}
}
#endif
}
}
}
}
LIBXSMM_API_INTERN
void libxsmm_generator_gemm_store_C( libxsmm_generated_code* io_generated_code,
const libxsmm_gp_reg_mapping* i_gp_reg_mapping,
const libxsmm_micro_kernel_config* i_micro_kernel_config,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const unsigned int i_m_blocking,
const unsigned int i_n_blocking )
{
/* deriving register blocking from kernel config */
unsigned int l_m_blocking = ( i_m_blocking % i_micro_kernel_config->vector_length == 0 ) ? i_m_blocking/i_micro_kernel_config->vector_length : (i_m_blocking/i_micro_kernel_config->vector_length)+1;
/* register blocking counter in n */
unsigned int l_n = 0;
/* register blocking counter in m */
unsigned int l_m = 0;
/* start register of accumulator */
unsigned int l_vec_reg_acc_start = i_micro_kernel_config->vector_reg_count - (i_n_blocking * l_m_blocking);
/* select store instruction */
unsigned int l_vstore = (LIBXSMM_GEMM_FLAG_ALIGN_C_NTS_HINT == (LIBXSMM_GEMM_FLAG_ALIGN_C_NTS_HINT & i_xgemm_desc->flags)) ? i_micro_kernel_config->c_vmove_nts_instruction : i_micro_kernel_config->c_vmove_instruction;
libxsmm_micro_kernel_config l_micro_kernel_config_mod;
libxsmm_micro_kernel_config *i_micro_kernel_config_mod = (libxsmm_micro_kernel_config*) &l_micro_kernel_config_mod;
memcpy(i_micro_kernel_config_mod, i_micro_kernel_config, sizeof(libxsmm_micro_kernel_config));
/* @TODO fix this test */
#if !defined(NDEBUG)
if (i_micro_kernel_config->instruction_set == LIBXSMM_X86_GENERIC ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_SSE3 ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_SSE42 ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX ||
i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX2 ) {
if ( (i_n_blocking > 3) || (i_n_blocking < 1) || (i_m_blocking < 1) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256 || i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CLX
|| i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CPX) {
if ( (i_n_blocking > 28) || (i_n_blocking < 1) || (l_m_blocking < 1) || (l_m_blocking > 8) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set > LIBXSMM_X86_AVX512_VL256 ) {
if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (l_m_blocking < 1) || (l_m_blocking > 6) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else if ( i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512_VL256 ) {
if ( (i_n_blocking > 30) || (i_n_blocking < 1) || (i_m_blocking != i_micro_kernel_config->vector_length) ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_REG_BLOCK );
return;
}
} else {}
#if 0
if ( i_m_blocking % i_micro_kernel_config->vector_length != 0 ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_M_BLOCK );
return;
}
#endif
#endif
if ( ( (i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_CORE) || (i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_CLX) ||
(i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CLX) || (i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256) ) &&
( (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) {
const unsigned int relu_bitmask_gpr = i_gp_reg_mapping->gp_reg_help_2;
const unsigned int scratch_gpr = i_gp_reg_mapping->gp_reg_help_2;
const unsigned int aux_gpr = i_gp_reg_mapping->gp_reg_help_1;
const unsigned int aux_vreg = 1;
const unsigned int zero_vreg = 0;
/* Check out if fusion has to be applied */
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
libxsmm_generator_gemm_prepare_relu_fusion( io_generated_code, i_micro_kernel_config,
zero_vreg, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, aux_gpr);
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
libxsmm_generator_gemm_dump_2D_block_and_prepare_sigmoid_fusion( io_generated_code, i_micro_kernel_config_mod,
l_vec_reg_acc_start, l_m_blocking, i_n_blocking, scratch_gpr, aux_gpr);
}
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
unsigned int bitmask_offset = (io_generated_code->arch < LIBXSMM_X86_AVX512) ? ((l_n * i_xgemm_desc->ldc) + (l_m * 8))/8 : ((l_n * i_xgemm_desc->ldc) + (l_m * 16))/8;
libxsmm_generator_gemm_apply_relu_to_vreg( io_generated_code, i_micro_kernel_config,
zero_vreg, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), i_micro_kernel_config->fused_relu, relu_bitmask_gpr, bitmask_offset, 1, aux_gpr, aux_vreg);
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
unsigned int tmp_vreg = 0;
libxsmm_generator_gemm_apply_sigmoid_to_vreg_from_scratch( io_generated_code, i_micro_kernel_config_mod,
scratch_gpr, l_vec_reg_acc_start + l_m + (l_m_blocking * l_n), tmp_vreg );
/* Store vreg back to scratch */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVUPS,
scratch_gpr,
LIBXSMM_X86_GP_REG_UNDEF, 0,
(l_vec_reg_acc_start + l_m + (l_m_blocking * l_n)) * 64,
i_micro_kernel_config->vector_name,
tmp_vreg, 0, 0, 1 );
}
}
}
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
libxsmm_generator_gemm_cleanup_relu_fusion( io_generated_code, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, aux_gpr);
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
/* Restore accumulators from scratch */
libxsmm_generator_gemm_restore_2D_regblock_from_scratch( io_generated_code, i_micro_kernel_config,
scratch_gpr, l_vec_reg_acc_start, l_m_blocking, i_n_blocking);
libxsmm_generator_gemm_cleanup_sigmoid_fusion( io_generated_code, scratch_gpr, aux_gpr );
}
libxsmm_generator_vcvtneps2bf16_avx512_prep_stack( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
/* storing downconverted and rounded C accumulator */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
libxsmm_generator_vcvtneps2bf16_avx512_preppedstack( io_generated_code,
( ( i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_VL256) && (i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512) ) ? 'y' : 'z',
reg_X, 0, 1, 2, 6, 7 );
/* store 16 bit values into xmm portion of the register */
if ( (i_micro_kernel_config->use_masking_a_c != 0) && ( l_m == (l_m_blocking - 1) ) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU16,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
( ( i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_VL256) && (i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512) ) ? 'y' : 'z',
0, 2, 0, 1 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
( ( i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_VL256) && (i_micro_kernel_config->instruction_set < LIBXSMM_X86_AVX512) ) ? 'x' : 'y',
0, 0, 0, 1 );
}
}
}
libxsmm_generator_vcvtneps2bf16_avx512_clean_stack( io_generated_code, i_gp_reg_mapping->gp_reg_help_2 );
} else if ( ( (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT)
&& ((i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_CPX) || (i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CPX))
) &&
( (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_DATATYPE_BF16 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) )
) {
const unsigned int relu_bitmask_gpr = i_gp_reg_mapping->gp_reg_help_2;
const unsigned int scratch_gpr = i_gp_reg_mapping->gp_reg_help_2;
const unsigned int aux_gpr = i_gp_reg_mapping->gp_reg_help_1;
const unsigned int zero_vreg = 1;
const unsigned int aux_vreg = 2;
/* storing downconverted and rounded C accumulator */
/* Check out if fusion has to be applied */
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
libxsmm_generator_gemm_prepare_relu_fusion( io_generated_code, i_micro_kernel_config,
zero_vreg, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, aux_gpr);
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
/* First dump the accumulators to scratch and then setup sigmoid coeffcients to be reused */
libxsmm_generator_gemm_dump_2D_block_and_prepare_sigmoid_fusion( io_generated_code, i_micro_kernel_config_mod,
l_vec_reg_acc_start, l_m_blocking, i_n_blocking, scratch_gpr, aux_gpr);
}
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
unsigned int l_m_2_blocking = (l_m_blocking/2)*2;
l_m = 0;
if ( i_micro_kernel_config->use_masking_a_c != 0 ) {
for ( l_m = 0 ; l_m < l_m_blocking; l_m++ ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
unsigned int bitmask_offset = (io_generated_code->arch < LIBXSMM_X86_AVX512) ? ((l_n * i_xgemm_desc->ldc) + (l_m * 8))/8 : ((l_n * i_xgemm_desc->ldc) + (l_m * 16))/8;
libxsmm_generator_gemm_apply_relu_to_vreg( io_generated_code, i_micro_kernel_config,
zero_vreg, reg_X, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, bitmask_offset, 1, aux_gpr, aux_vreg);
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
unsigned int tmp_vreg = 0;
libxsmm_generator_gemm_apply_sigmoid_to_vreg_from_scratch( io_generated_code, i_micro_kernel_config_mod,
scratch_gpr, reg_X, tmp_vreg );
reg_X = tmp_vreg;
}
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VCVTNEPS2BF16,
i_micro_kernel_config->vector_name,
reg_X, 0 );
/* store 16 bit values into ymm portion of the register bfloat mask fix can lead to errors x should not be masked */
if ( l_m == (l_m_blocking - 1) ) {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VMOVDQU16,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
( i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CPX ) ? 'y' : 'z',
0, 2, 0, 1 );
} else {
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
( i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CPX ) ? 'x' : 'y',
0, 0, 0, 1 );
}
}
} else {
for (; l_m < l_m_2_blocking; l_m+=2 ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
unsigned int reg_X2 = l_vec_reg_acc_start + l_m+1 + (l_m_blocking * l_n);
if (i_micro_kernel_config->fused_sigmoid == 1) {
unsigned int tmp_vreg = 0;
unsigned int tmp_vreg2 = 1;
libxsmm_generator_gemm_apply_sigmoid_to_vreg_from_scratch( io_generated_code, i_micro_kernel_config_mod,
scratch_gpr, reg_X, tmp_vreg );
libxsmm_generator_gemm_apply_sigmoid_to_vreg_from_scratch( io_generated_code, i_micro_kernel_config_mod,
scratch_gpr, reg_X2, tmp_vreg2 );
reg_X = tmp_vreg;
reg_X2 = tmp_vreg2;
}
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
LIBXSMM_X86_INSTR_VCVTNE2PS2BF16,
i_micro_kernel_config->vector_name,
reg_X, reg_X2, 0 );
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
unsigned int bitmask_offset = (io_generated_code->arch < LIBXSMM_X86_AVX512) ? ((l_n * i_xgemm_desc->ldc) + (l_m * 8))/8 : ((l_n * i_xgemm_desc->ldc) + (l_m * 16))/8;
libxsmm_generator_gemm_apply_relu_to_vreg( io_generated_code, i_micro_kernel_config,
zero_vreg, 0, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, bitmask_offset, 0, aux_gpr, aux_vreg);
}
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
( i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CPX ) ? 'y' : 'z',
0, 0, 0, 1 );
}
for (; l_m < l_m_blocking; l_m++ ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
unsigned int bitmask_offset = (io_generated_code->arch < LIBXSMM_X86_AVX512) ? ((l_n * i_xgemm_desc->ldc) + (l_m * 8))/8 : ((l_n * i_xgemm_desc->ldc) + (l_m * 16))/8;
libxsmm_generator_gemm_apply_relu_to_vreg( io_generated_code, i_micro_kernel_config,
zero_vreg, reg_X, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, bitmask_offset, 1, aux_gpr, aux_vreg);
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
unsigned int tmp_vreg = 0;
libxsmm_generator_gemm_apply_sigmoid_to_vreg_from_scratch( io_generated_code, i_micro_kernel_config_mod,
scratch_gpr, reg_X, tmp_vreg );
reg_X = tmp_vreg;
}
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VCVTNEPS2BF16,
i_micro_kernel_config->vector_name,
reg_X, 0 );
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
( i_micro_kernel_config->instruction_set == LIBXSMM_X86_AVX512_VL256_CPX ) ? 'x' : 'y',
0, 0, 0, 1 );
}
}
}
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
libxsmm_generator_gemm_cleanup_relu_fusion( io_generated_code, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, aux_gpr);
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
libxsmm_generator_gemm_cleanup_sigmoid_fusion( io_generated_code, scratch_gpr, aux_gpr );
}
} else if ( ( (i_micro_kernel_config->instruction_set <= LIBXSMM_X86_ALLFEAT) && (i_micro_kernel_config->instruction_set >= LIBXSMM_X86_AVX512_VL256) ) &&
( (LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) && (LIBXSMM_DATATYPE_I8 == LIBXSMM_GETENUM_OUT( i_xgemm_desc->datatype ) ) ) ) {
/* pick the right instrucitons */
unsigned int inst_f32_i32 = ( ( i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_C_UNSIGNED ) != 0 ) ? LIBXSMM_X86_INSTR_VCVTPS2UDQ : LIBXSMM_X86_INSTR_VCVTPS2DQ;
unsigned int inst_i32_i8 = ( ( i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_C_UNSIGNED ) != 0 ) ? LIBXSMM_X86_INSTR_VPMOVUSDB : LIBXSMM_X86_INSTR_VPMOVSDB;
/* there are case where we need to load the scaling factor's address from the stack argument list */
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_BATCH_REDUCE_OFFSET) != 0 ) {
libxsmm_x86_instruction_load_arg_to_reg( io_generated_code, 0, i_gp_reg_mapping->gp_reg_scf );
}
/* loading scf into register 3 */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
LIBXSMM_X86_INSTR_VBROADCASTSS,
i_gp_reg_mapping->gp_reg_scf,
LIBXSMM_X86_GP_REG_UNDEF, 0, 0,
i_micro_kernel_config->vector_name,
3, 0, 1, 0 );
/* Zero out register 0 to perform relu */
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
i_micro_kernel_config->vxor_instruction,
i_micro_kernel_config->vector_name,
0,
0,
0);
/* storing downconverted and rounded C accumulator */
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
/* Convert result to F32 */
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
LIBXSMM_X86_INSTR_VCVTDQ2PS,
i_micro_kernel_config->vector_name,
reg_X,
reg_X );
/* Multiply with scaling factor */
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
LIBXSMM_X86_INSTR_VMULPS,
i_micro_kernel_config->vector_name,
reg_X,
3,
reg_X );
/* Perform RELU */
libxsmm_x86_instruction_vec_compute_3reg( io_generated_code,
LIBXSMM_X86_INSTR_VMAXPS,
i_micro_kernel_config->vector_name,
reg_X,
0,
reg_X);
/* Round result to int32 */
libxsmm_x86_instruction_vec_compute_2reg( io_generated_code,
inst_f32_i32,
i_micro_kernel_config->vector_name,
reg_X, reg_X );
/* down-convert to int8 */
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
inst_i32_i8,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
i_micro_kernel_config->vector_name,
reg_X, ( ( l_m == (l_m_blocking - 1)) && ( i_micro_kernel_config->use_masking_a_c != 0 ) ) ? 2 : 0, 0, 1 );
}
}
} else {
/* storing C accumulator */
const unsigned int relu_bitmask_gpr = i_gp_reg_mapping->gp_reg_help_2;
const unsigned int scratch_gpr = i_gp_reg_mapping->gp_reg_help_2;
const unsigned int aux_gpr = i_gp_reg_mapping->gp_reg_help_1;
const unsigned int zero_vreg = 0;
const unsigned int aux_vreg = 1;
/* Check out if fusion has to be applied */
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
libxsmm_generator_gemm_prepare_relu_fusion( io_generated_code, i_micro_kernel_config,
zero_vreg, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, aux_gpr);
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
libxsmm_generator_gemm_dump_2D_block_and_prepare_sigmoid_fusion( io_generated_code, i_micro_kernel_config_mod,
l_vec_reg_acc_start, l_m_blocking, i_n_blocking, scratch_gpr, aux_gpr);
}
for ( l_n = 0; l_n < i_n_blocking; l_n++ ) {
for ( l_m = 0; l_m < l_m_blocking; l_m++ ) {
unsigned int reg_X = l_vec_reg_acc_start + l_m + (l_m_blocking * l_n);
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
unsigned int bitmask_offset = (io_generated_code->arch < LIBXSMM_X86_AVX512) ? ((l_n * i_xgemm_desc->ldc) + (l_m * 8))/8 : ((l_n * i_xgemm_desc->ldc) + (l_m * 16))/8;
libxsmm_generator_gemm_apply_relu_to_vreg( io_generated_code, i_micro_kernel_config,
zero_vreg, reg_X, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, bitmask_offset, 1, aux_gpr, aux_vreg);
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
unsigned int tmp_vreg = 0;
libxsmm_generator_gemm_apply_sigmoid_to_vreg_from_scratch( io_generated_code, i_micro_kernel_config_mod,
scratch_gpr, reg_X, tmp_vreg );
reg_X = tmp_vreg;
}
libxsmm_x86_instruction_vec_move( io_generated_code,
i_micro_kernel_config->instruction_set,
l_vstore,
i_gp_reg_mapping->gp_reg_c,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out),
i_micro_kernel_config->vector_name,
reg_X, ( l_m == (l_m_blocking - 1) ) ? i_micro_kernel_config->use_masking_a_c : 0, 0, 1 );
}
if ( i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C ||
i_xgemm_desc->prefetch == LIBXSMM_GEMM_PREFETCH_AL2BL2_VIA_C_AHEAD ) {
if ( (i_xgemm_desc->flags & LIBXSMM_GEMM_FLAG_TRANS_B) == 0 ) {
/* determining how many prefetches we need in M direction as we just need one prefetch per cache line */
unsigned int l_m_advance = 64 / ((i_micro_kernel_config->vector_length) * (i_micro_kernel_config->datatype_size_out)); /* 64: hardcoded cache line length */
for (l_m = 0; l_m < l_m_blocking; l_m += l_m_advance ) {
libxsmm_x86_instruction_prefetch( io_generated_code,
i_micro_kernel_config->prefetch_instruction,
i_gp_reg_mapping->gp_reg_b_prefetch,
LIBXSMM_X86_GP_REG_UNDEF, 0,
((l_n * i_xgemm_desc->ldc) + (l_m * (i_micro_kernel_config->vector_length))) * (i_micro_kernel_config->datatype_size_out));
}
}
}
}
if ((i_micro_kernel_config->fused_relu_nobitmask == 1) || (i_micro_kernel_config->fused_relu == 1)) {
libxsmm_generator_gemm_cleanup_relu_fusion( io_generated_code, i_micro_kernel_config->fused_relu, relu_bitmask_gpr, aux_gpr );
} else if (i_micro_kernel_config->fused_sigmoid == 1) {
libxsmm_generator_gemm_cleanup_sigmoid_fusion( io_generated_code, scratch_gpr, aux_gpr );
}
}
}
|
GB_binop__max_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 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__max_uint32)
// A.*B function (eWiseMult): GB (_AemultB_08__max_uint32)
// A.*B function (eWiseMult): GB (_AemultB_02__max_uint32)
// A.*B function (eWiseMult): GB (_AemultB_04__max_uint32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__max_uint32)
// A*D function (colscale): GB (_AxD__max_uint32)
// D*A function (rowscale): GB (_DxB__max_uint32)
// C+=B function (dense accum): GB (_Cdense_accumB__max_uint32)
// C+=b function (dense accum): GB (_Cdense_accumb__max_uint32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__max_uint32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__max_uint32)
// C=scalar+B GB (_bind1st__max_uint32)
// C=scalar+B' GB (_bind1st_tran__max_uint32)
// C=A+scalar GB (_bind2nd__max_uint32)
// C=A'+scalar GB (_bind2nd_tran__max_uint32)
// C type: uint32_t
// A type: uint32_t
// B,b type: uint32_t
// BinaryOp: cij = GB_IMAX (aij, bij)
#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,A_iso) \
uint32_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint32_t bij = GBX (Bx, pB, B_iso)
// 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,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_IMAX (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_MAX || GxB_NO_UINT32 || GxB_NO_MAX_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__max_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__max_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__max_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__max_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__max_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_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__max_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_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__max_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, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__max_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_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__max_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_04__max_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_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__max_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__max_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 bnz,
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 < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_IMAX (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__max_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 = GBX (Ax, p, false) ;
Cx [p] = GB_IMAX (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) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IMAX (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__max_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 = GBX (Ax, pA, false) ; \
Cx [pC] = GB_IMAX (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__max_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
|
Jacobi.tfm.c | //===--- Jacobi.c --------- Jacobi Iterative Method ---------------*- C -*-===//
//
// This file implements Jacobi iterative method which is an iterative method
// used to solve partial differential equations.
//
//===----------------------------------------------------------------------===//
#include <math.h>
#include <stdio.h>
#define Max(A, B) ((A) > (B) ? (A) : (B))
#define L 8
#define ITMAX 10
#define MAXEPS 0.5
double A[L][L];
double B[L][L];
int main() {
#pragma omp parallel
{
#pragma omp for default(shared)
for (int I = 0; I < L; ++I)
for (int J = 0; J < L; ++J) {
A[I][J] = 0;
if (I == 0 || J == 0 || I == L - 1 || J == L - 1)
B[I][J] = 0;
else
B[I][J] = 3 + I + J;
}
}
for (int It = 1; It <= ITMAX; ++It) {
double Eps = 0;
#pragma omp parallel
{
#pragma omp for default(shared) reduction(max : Eps)
for (int I = 1; I < L - 1; ++I)
for (int J = 1; J < L - 1; ++J) {
double Tmp = fabs(B[I][J] - A[I][J]);
Eps = Max(Tmp, Eps);
A[I][J] = B[I][J];
}
#pragma omp for default(shared)
for (int I = 1; I < L - 1; ++I)
for (int J = 1; J < L - 1; ++J)
B[I][J] =
(A[I - 1][J] + A[I][J - 1] + A[I][J + 1] + A[I + 1][J]) / 4.0;
}
printf("It=%4i Eps=%e\n", It, Eps);
if (Eps < MAXEPS)
break;
}
return 0;
}
|
O4Indirect3D.c | #include <mpi.h>
#include "grid.h"
extern struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_temp;
extern struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_ind3Dvar;
struct {
char *name;
int loc;
int dim;
union {
int *restrict * restrict p2;
int *restrict * restrict * restrict p3;
} data_pointer;
} *t3DBlk;
struct {
char *name;
int loc;
int dim;
union {
int *restrict * restrict p2;
int *restrict * restrict * restrict p3;
} data_pointer;
} *t3DIdx;
void O4Indirect3D(GRID * g)
{
{
size_t min_block = g->mpi_rank == (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : 0;
size_t max_block = g->mpi_rank < (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) || g->mpi_rank > (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 : g->mpi_rank == (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
#pragma omp parallel for
for (size_t block_index = (min_block); block_index < (max_block); block_index++) {
for (size_t height_index = (0); height_index < (g->height); height_index++) {
for (size_t edge_index = (0); edge_index < (g->blkSize); edge_index++) {
gv_ind3Dvar->data_pointer.p3[(block_index)][(height_index)][(edge_index)] = 0;
}
}
}
}
}
|
nbnxn_kernel_simd_2xnn.c | /*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2012,2013, by the GROMACS development team, led by
* David van der Spoel, Berk Hess, Erik Lindahl, and including many
* others, as listed in the AUTHORS file in the top-level source
* directory and at http://www.gromacs.org.
*
* GROMACS 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.
*
* GROMACS 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 GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*
* Note: this file was generated by the Verlet kernel generator for
* kernel type 2xnn.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "typedefs.h"
#ifdef GMX_NBNXN_SIMD_2XNN
/* Include the full-width SIMD macros */
#include "gmx_simd_macros.h"
#include "gmx_simd_vec.h"
#if !(GMX_SIMD_WIDTH_HERE == 8 || GMX_SIMD_WIDTH_HERE == 16)
#error "unsupported SIMD width"
#endif
#define GMX_SIMD_J_UNROLL_SIZE 2
#include "nbnxn_kernel_simd_2xnn.h"
#include "../nbnxn_kernel_common.h"
#include "gmx_omp_nthreads.h"
#include "types/force_flags.h"
/*! \brief Kinds of electrostatic treatments in SIMD Verlet kernels
*/
enum {
coultRF, coultTAB, coultTAB_TWIN, coultEWALD, coultEWALD_TWIN, coultNR
};
/* Declare and define the kernel function pointer lookup tables. */
static p_nbk_func_ener p_nbk_ener[coultNR][ljcrNR] =
{
{
nbnxn_kernel_simd_2xnn_rf_comb_geom_ener,
nbnxn_kernel_simd_2xnn_rf_comb_lb_ener,
nbnxn_kernel_simd_2xnn_rf_comb_none_ener,
},
{
nbnxn_kernel_simd_2xnn_tab_comb_geom_ener,
nbnxn_kernel_simd_2xnn_tab_comb_lb_ener,
nbnxn_kernel_simd_2xnn_tab_comb_none_ener,
},
{
nbnxn_kernel_simd_2xnn_tab_twin_comb_geom_ener,
nbnxn_kernel_simd_2xnn_tab_twin_comb_lb_ener,
nbnxn_kernel_simd_2xnn_tab_twin_comb_none_ener,
},
{
nbnxn_kernel_simd_2xnn_ewald_comb_geom_ener,
nbnxn_kernel_simd_2xnn_ewald_comb_lb_ener,
nbnxn_kernel_simd_2xnn_ewald_comb_none_ener,
},
{
nbnxn_kernel_simd_2xnn_ewald_twin_comb_geom_ener,
nbnxn_kernel_simd_2xnn_ewald_twin_comb_lb_ener,
nbnxn_kernel_simd_2xnn_ewald_twin_comb_none_ener,
},
};
static p_nbk_func_ener p_nbk_energrp[coultNR][ljcrNR] =
{
{
nbnxn_kernel_simd_2xnn_rf_comb_geom_energrp,
nbnxn_kernel_simd_2xnn_rf_comb_lb_energrp,
nbnxn_kernel_simd_2xnn_rf_comb_none_energrp,
},
{
nbnxn_kernel_simd_2xnn_tab_comb_geom_energrp,
nbnxn_kernel_simd_2xnn_tab_comb_lb_energrp,
nbnxn_kernel_simd_2xnn_tab_comb_none_energrp,
},
{
nbnxn_kernel_simd_2xnn_tab_twin_comb_geom_energrp,
nbnxn_kernel_simd_2xnn_tab_twin_comb_lb_energrp,
nbnxn_kernel_simd_2xnn_tab_twin_comb_none_energrp,
},
{
nbnxn_kernel_simd_2xnn_ewald_comb_geom_energrp,
nbnxn_kernel_simd_2xnn_ewald_comb_lb_energrp,
nbnxn_kernel_simd_2xnn_ewald_comb_none_energrp,
},
{
nbnxn_kernel_simd_2xnn_ewald_twin_comb_geom_energrp,
nbnxn_kernel_simd_2xnn_ewald_twin_comb_lb_energrp,
nbnxn_kernel_simd_2xnn_ewald_twin_comb_none_energrp,
},
};
static p_nbk_func_noener p_nbk_noener[coultNR][ljcrNR] =
{
{
nbnxn_kernel_simd_2xnn_rf_comb_geom_noener,
nbnxn_kernel_simd_2xnn_rf_comb_lb_noener,
nbnxn_kernel_simd_2xnn_rf_comb_none_noener,
},
{
nbnxn_kernel_simd_2xnn_tab_comb_geom_noener,
nbnxn_kernel_simd_2xnn_tab_comb_lb_noener,
nbnxn_kernel_simd_2xnn_tab_comb_none_noener,
},
{
nbnxn_kernel_simd_2xnn_tab_twin_comb_geom_noener,
nbnxn_kernel_simd_2xnn_tab_twin_comb_lb_noener,
nbnxn_kernel_simd_2xnn_tab_twin_comb_none_noener,
},
{
nbnxn_kernel_simd_2xnn_ewald_comb_geom_noener,
nbnxn_kernel_simd_2xnn_ewald_comb_lb_noener,
nbnxn_kernel_simd_2xnn_ewald_comb_none_noener,
},
{
nbnxn_kernel_simd_2xnn_ewald_twin_comb_geom_noener,
nbnxn_kernel_simd_2xnn_ewald_twin_comb_lb_noener,
nbnxn_kernel_simd_2xnn_ewald_twin_comb_none_noener,
},
};
static void
reduce_group_energies(int ng, int ng_2log,
const real *VSvdw, const real *VSc,
real *Vvdw, real *Vc)
{
const int unrollj = GMX_SIMD_WIDTH_HERE/GMX_SIMD_J_UNROLL_SIZE;
const int unrollj_half = unrollj/2;
int ng_p2, i, j, j0, j1, c, s;
ng_p2 = (1<<ng_2log);
/* The size of the x86 SIMD energy group buffer array is:
* ng*ng*ng_p2*unrollj_half*simd_width
*/
for (i = 0; i < ng; i++)
{
for (j = 0; j < ng; j++)
{
Vvdw[i*ng+j] = 0;
Vc[i*ng+j] = 0;
}
for (j1 = 0; j1 < ng; j1++)
{
for (j0 = 0; j0 < ng; j0++)
{
c = ((i*ng + j1)*ng_p2 + j0)*unrollj_half*unrollj;
for (s = 0; s < unrollj_half; s++)
{
Vvdw[i*ng+j0] += VSvdw[c+0];
Vvdw[i*ng+j1] += VSvdw[c+1];
Vc [i*ng+j0] += VSc [c+0];
Vc [i*ng+j1] += VSc [c+1];
c += unrollj + 2;
}
}
}
}
}
#else /* GMX_NBNXN_SIMD_2XNN */
#include "gmx_fatal.h"
#endif /* GMX_NBNXN_SIMD_2XNN */
void
nbnxn_kernel_simd_2xnn(nbnxn_pairlist_set_t *nbl_list,
const nbnxn_atomdata_t *nbat,
const interaction_const_t *ic,
int ewald_excl,
rvec *shift_vec,
int force_flags,
int clearF,
real *fshift,
real *Vc,
real *Vvdw)
#ifdef GMX_NBNXN_SIMD_2XNN
{
int nnbl;
nbnxn_pairlist_t **nbl;
int coult;
int nb;
nnbl = nbl_list->nnbl;
nbl = nbl_list->nbl;
if (EEL_RF(ic->eeltype) || ic->eeltype == eelCUT)
{
coult = coultRF;
}
else
{
if (ewald_excl == ewaldexclTable)
{
if (ic->rcoulomb == ic->rvdw)
{
coult = coultTAB;
}
else
{
coult = coultTAB_TWIN;
}
}
else
{
if (ic->rcoulomb == ic->rvdw)
{
coult = coultEWALD;
}
else
{
coult = coultEWALD_TWIN;
}
}
}
#pragma omp parallel for schedule(static) num_threads(gmx_omp_nthreads_get(emntNonbonded))
for (nb = 0; nb < nnbl; nb++)
{
nbnxn_atomdata_output_t *out;
real *fshift_p;
out = &nbat->out[nb];
if (clearF == enbvClearFYes)
{
clear_f(nbat, nb, out->f);
}
if ((force_flags & GMX_FORCE_VIRIAL) && nnbl == 1)
{
fshift_p = fshift;
}
else
{
fshift_p = out->fshift;
if (clearF == enbvClearFYes)
{
clear_fshift(fshift_p);
}
}
if (!(force_flags & GMX_FORCE_ENERGY))
{
/* Don't calculate energies */
p_nbk_noener[coult][nbat->comb_rule](nbl[nb], nbat,
ic,
shift_vec,
out->f,
fshift_p);
}
else if (out->nV == 1)
{
/* No energy groups */
out->Vvdw[0] = 0;
out->Vc[0] = 0;
p_nbk_ener[coult][nbat->comb_rule](nbl[nb], nbat,
ic,
shift_vec,
out->f,
fshift_p,
out->Vvdw,
out->Vc);
}
else
{
/* Calculate energy group contributions */
int i;
for (i = 0; i < out->nVS; i++)
{
out->VSvdw[i] = 0;
}
for (i = 0; i < out->nVS; i++)
{
out->VSc[i] = 0;
}
p_nbk_energrp[coult][nbat->comb_rule](nbl[nb], nbat,
ic,
shift_vec,
out->f,
fshift_p,
out->VSvdw,
out->VSc);
reduce_group_energies(nbat->nenergrp, nbat->neg_2log,
out->VSvdw, out->VSc,
out->Vvdw, out->Vc);
}
}
if (force_flags & GMX_FORCE_ENERGY)
{
reduce_energies_over_lists(nbat, nnbl, Vvdw, Vc);
}
}
#else
{
gmx_incons("nbnxn_kernel_simd_2xnn called when such kernels "
" are not enabled.");
}
#endif
#undef GMX_SIMD_J_UNROLL_SIZE
|
GB_binop__le_fp64.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 GBCUDA_DEV
#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__le_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__le_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__le_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__le_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__le_fp64)
// A*D function (colscale): GB (_AxD__le_fp64)
// D*A function (rowscale): GB (_DxB__le_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__le_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__le_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__le_fp64)
// C=scalar+B GB (_bind1st__le_fp64)
// C=scalar+B' GB (_bind1st_tran__le_fp64)
// C=A+scalar GB (_bind2nd__le_fp64)
// C=A'+scalar GB (_bind2nd_tran__le_fp64)
// C type: bool
// A type: double
// A pattern? 0
// B type: double
// B pattern? 0
// BinaryOp: cij = (aij <= bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#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,A_iso) \
double 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) \
double 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_LE || GxB_NO_FP64 || GxB_NO_LE_FP64)
//------------------------------------------------------------------------------
// 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__le_fp64)
(
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__le_fp64)
(
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
#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__le_fp64)
(
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 double
double bwork = (*((double *) 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__le_fp64)
(
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__le_fp64)
(
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__le_fp64)
(
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) ;
double alpha_scalar ;
double beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((double *) alpha_scalar_in)) ;
beta_scalar = (*((double *) 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__le_fp64)
(
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__le_fp64)
(
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__le_fp64)
(
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__le_fp64)
(
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__le_fp64)
(
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 ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) 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 ;
double 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__le_fp64)
(
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 ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
double 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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x <= aij) ; \
}
GrB_Info GB (_bind1st_tran__le_fp64)
(
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 \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// 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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij <= y) ; \
}
GrB_Info GB (_bind2nd_tran__le_fp64)
(
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
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
DRB009-lastprivatemissing-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.
*/
/*
This loop has loop-carried output-dependence due to x=... at line 59.
The problem can be solved by using lastprivate(x).
Data race pair: x@59 vs. x@59
*/
#include <stdio.h>
int main(int argc, char* argv[])
{
int i,x;
int len = 10000;
#pragma omp parallel for private (i)
for (i=0;i<len;i++)
x=i;
printf("x=%d",x);
return 0;
}
|
trilinos_residual_criteria.h | // KRATOS _____ _ _ _
// |_ _| __(_) (_)_ __ ___ ___
// | || '__| | | | '_ \ / _ \/ __|
// | || | | | | | | | | (_) \__
// |_||_| |_|_|_|_| |_|\___/|___/ APPLICATION
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Jordi Cotela
//
#if !defined(KRATOS_TRILINOS_RESIDUAL_CRITERIA_H_INCLUDED)
#define KRATOS_TRILINOS_RESIDUAL_CRITERIA_H_INCLUDED
// System includes
// External includes
// Project includes
#include "includes/define.h"
#include "solving_strategies/convergencecriterias/residual_criteria.h"
namespace Kratos
{
///@addtogroup TrilinosApplication
///@{
///@name Kratos Classes
///@{
/// MPI version of the ResidualCriteria.
/** Implements a convergence criteria based on the norm of the (free rows of) the RHS vector.
* @see ResidualCriteria
*/
template< class TSparseSpace, class TDenseSpace >
class TrilinosResidualCriteria : public ResidualCriteria< TSparseSpace, TDenseSpace >
{
public:
///@name Type Definitions
///@{
/// Pointer definition of TrilinosResidualCriteria
KRATOS_CLASS_POINTER_DEFINITION(TrilinosResidualCriteria);
typedef ResidualCriteria< TSparseSpace, TDenseSpace > BaseType;
typedef typename BaseType::TDataType TDataType;
///@}
///@name Life Cycle
///@{
/// Constructor
explicit TrilinosResidualCriteria(TDataType NewRatioTolerance,TDataType AlwaysConvergedNorm):
ResidualCriteria<TSparseSpace,TDenseSpace>(NewRatioTolerance, AlwaysConvergedNorm)
{}
/// Copy constructor
explicit TrilinosResidualCriteria(const TrilinosResidualCriteria& rOther):
ResidualCriteria<TSparseSpace,TDenseSpace>(rOther)
{}
/// Destructor.
~TrilinosResidualCriteria() override {}
///@}
///@name Operators
///@{
/// Deleted assignment operator.
TrilinosResidualCriteria& operator=(TrilinosResidualCriteria const& rOther) = delete;
///@}
protected:
///@name Protected Operations
///@{
/**
* @brief This method computes the norm of the residual
* @details It checks if the dof is fixed
* @param rModelPart Reference to the ModelPart containing the problem.
* @param rResidualSolutionNorm The norm of the residual
* @param rDofNum The number of DoFs
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param b RHS vector (residual + reactions)
*/
void CalculateResidualNorm(
ModelPart& rModelPart,
TDataType& rResidualSolutionNorm,
typename BaseType::SizeType& rDofNum,
typename BaseType::DofsArrayType& rDofSet,
const typename BaseType::TSystemVectorType& rB) override
{
// Initialize
TDataType residual_solution_norm = TDataType();
long int local_dof_num = 0;
const double rank = rB.Comm().MyPID(); // To compare with PARTITION_INDEX, which is a double variable
// Loop over Dofs
#pragma omp parallel for reduction(+:residual_solution_norm,local_dof_num)
for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) {
auto it_dof = rDofSet.begin() + i;
typename BaseType::IndexType dof_id;
TDataType residual_dof_value;
if (it_dof->IsFree() && (it_dof->GetSolutionStepValue(PARTITION_INDEX) == rank)) {
dof_id = it_dof->EquationId();
residual_dof_value = TSparseSpace::GetValue(rB,dof_id);
residual_solution_norm += residual_dof_value * residual_dof_value;
local_dof_num++;
}
}
// Combine local contributions
// Note that I'm not merging the two calls because one adds doubles and the other ints (JC)
rB.Comm().SumAll(&residual_solution_norm,&rResidualSolutionNorm,1);
// SizeType is long unsigned int in linux, but EpetraComm does not support unsigned types
long int global_dof_num = 0;
rB.Comm().SumAll(&local_dof_num,&global_dof_num,1);
rDofNum = static_cast<typename BaseType::SizeType>(global_dof_num);
rResidualSolutionNorm = std::sqrt(rResidualSolutionNorm);
}
///@}
private:
///@name Member Variables
///@{
///@}
///@name Private Operations
///@{
///@}
}; // Class TrilinosResidualCriteria
///@}
///@} addtogroup block
} // namespace Kratos.
#endif // KRATOS_TRILINOS_RESIDUAL_CRITERIA_H_INCLUDED defined
|
GB_unop__exp2_fp64_fp64.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__exp2_fp64_fp64)
// op(A') function: GB (_unop_tran__exp2_fp64_fp64)
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = exp2 (aij)
#define GB_ATYPE \
double
#define GB_CTYPE \
double
// 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 = exp2 (x) ;
// casting
#define GB_CAST(z, aij) \
double z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = aij ; \
Cx [pC] = exp2 (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_EXP2 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__exp2_fp64_fp64)
(
double *Cx, // Cx and Ax may be aliased
const double *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++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = exp2 (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 ;
double aij = Ax [p] ;
double z = aij ;
Cx [p] = exp2 (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__exp2_fp64_fp64)
(
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
|
core_dsyrk.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_zsyrk.c, normal z -> d, Fri Sep 28 17:38:23 2018
*
**/
#include <plasma_core_blas.h>
#include "plasma_types.h"
#include "core_lapack.h"
/***************************************************************************//**
*
* @ingroup core_syrk
*
* Performs one of the symmetric rank k operations
*
* \f[ C = \alpha A \times A^T + \beta C, \f]
* or
* \f[ C = \alpha A^T \times A + \beta C, \f]
*
* where alpha and beta are scalars, C is an n-by-n symmetric
* matrix, and A is an n-by-k matrix in the first case and a k-by-n
* matrix in the second case.
*
*******************************************************************************
*
* @param[in] uplo
* - PlasmaUpper: Upper triangle of C is stored;
* - PlasmaLower: Lower triangle of C is stored.
*
* @param[in] trans
* - PlasmaNoTrans: \f[ C = \alpha A \times A^T + \beta C; \f]
* - PlasmaTrans: \f[ C = \alpha A^T \times A + \beta C. \f]
*
* @param[in] n
* The order of the matrix C. n >= 0.
*
* @param[in] k
* If trans = PlasmaNoTrans, number of columns of the A matrix;
* if trans = PlasmaTrans, number of rows of the A matrix.
*
* @param[in] alpha
* The scalar alpha.
*
* @param[in] A
* A is an lda-by-ka matrix.
* If trans = PlasmaNoTrans, ka = k;
* if trans = PlasmaTrans, ka = n.
*
* @param[in] lda
* The leading dimension of the array A.
* If trans = PlasmaNoTrans, lda >= max(1, n);
* if trans = PlasmaTrans, lda >= max(1, k).
*
* @param[in] beta
* The scalar beta.
*
* @param[in,out] C
* C is an ldc-by-n matrix.
* On exit, the uplo part of the matrix is overwritten
* by the uplo part of the updated matrix.
*
* @param[in] ldc
* The leading dimension of the array C. ldc >= max(1, n).
*
******************************************************************************/
__attribute__((weak))
void plasma_core_dsyrk(plasma_enum_t uplo, plasma_enum_t trans,
int n, int k,
double alpha, const double *A, int lda,
double beta, double *C, int ldc)
{
cblas_dsyrk(CblasColMajor,
(CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)trans,
n, k,
(alpha), A, lda,
(beta), C, ldc);
}
/******************************************************************************/
void plasma_core_omp_dsyrk(
plasma_enum_t uplo, plasma_enum_t trans,
int n, int k,
double alpha, const double *A, int lda,
double beta, double *C, int ldc,
plasma_sequence_t *sequence, plasma_request_t *request)
{
int ak;
if (trans == PlasmaNoTrans)
ak = k;
else
ak = n;
#pragma omp task depend(in:A[0:lda*ak]) \
depend(inout:C[0:ldc*n])
{
if (sequence->status == PlasmaSuccess)
plasma_core_dsyrk(uplo, trans,
n, k,
alpha, A, lda,
beta, C, ldc);
}
}
|
stream.c | /*-----------------------------------------------------------------------*/
/* Program: STREAM */
/* Revision: $Id: stream.c,v 5.10 2013/01/17 16:01:06 mccalpin Exp mccalpin $ */
/* Original code developed by John D. McCalpin */
/* Programmers: John D. McCalpin */
/* Joe R. Zagar */
/* */
/* This program measures memory transfer rates in MB/s for simple */
/* computational kernels coded in C. */
/*-----------------------------------------------------------------------*/
/* Copyright 1991-2013: John D. McCalpin */
/*-----------------------------------------------------------------------*/
/* License: */
/* 1. You are free to use this program and/or to redistribute */
/* this program. */
/* 2. You are free to modify this program for your own use, */
/* including commercial use, subject to the publication */
/* restrictions in item 3. */
/* 3. You are free to publish results obtained from running this */
/* program, or from works that you derive from this program, */
/* with the following limitations: */
/* 3a. In order to be referred to as "STREAM benchmark results", */
/* published results must be in conformance to the STREAM */
/* Run Rules, (briefly reviewed below) published at */
/* http://www.cs.virginia.edu/stream/ref.html */
/* and incorporated herein by reference. */
/* As the copyright holder, John McCalpin retains the */
/* right to determine conformity with the Run Rules. */
/* 3b. Results based on modified source code or on runs not in */
/* accordance with the STREAM Run Rules must be clearly */
/* labelled whenever they are published. Examples of */
/* proper labelling include: */
/* "tuned STREAM benchmark results" */
/* "based on a variant of the STREAM benchmark code" */
/* Other comparable, clear, and reasonable labelling is */
/* acceptable. */
/* 3c. Submission of results to the STREAM benchmark web site */
/* is encouraged, but not required. */
/* 4. Use of this program or creation of derived works based on this */
/* program constitutes acceptance of these licensing restrictions. */
/* 5. Absolutely no warranty is expressed or implied. */
/*-----------------------------------------------------------------------*/
# include <stdio.h>
# include <unistd.h>
# include <math.h>
# include <float.h>
# include <limits.h>
# include <sys/time.h>
/*-----------------------------------------------------------------------
* INSTRUCTIONS:
*
* 1) STREAM requires different amounts of memory to run on different
* systems, depending on both the system cache size(s) and the
* granularity of the system timer.
* You should adjust the value of 'STREAM_ARRAY_SIZE' (below)
* to meet *both* of the following criteria:
* (a) Each array must be at least 4 times the size of the
* available cache memory. I don't worry about the difference
* between 10^6 and 2^20, so in practice the minimum array size
* is about 3.8 times the cache size.
* Example 1: One Xeon E3 with 8 MB L3 cache
* STREAM_ARRAY_SIZE should be >= 4 million, giving
* an array size of 30.5 MB and a total memory requirement
* of 91.5 MB.
* Example 2: Two Xeon E5's with 20 MB L3 cache each (using OpenMP)
* STREAM_ARRAY_SIZE should be >= 20 million, giving
* an array size of 153 MB and a total memory requirement
* of 458 MB.
* (b) The size should be large enough so that the 'timing calibration'
* output by the program is at least 20 clock-ticks.
* Example: most versions of Windows have a 10 millisecond timer
* granularity. 20 "ticks" at 10 ms/tic is 200 milliseconds.
* If the chip is capable of 10 GB/s, it moves 2 GB in 200 msec.
* This means the each array must be at least 1 GB, or 128M elements.
*
* Version 5.10 increases the default array size from 2 million
* elements to 10 million elements in response to the increasing
* size of L3 caches. The new default size is large enough for caches
* up to 20 MB.
* Version 5.10 changes the loop index variables from "register int"
* to "ssize_t", which allows array indices >2^32 (4 billion)
* on properly configured 64-bit systems. Additional compiler options
* (such as "-mcmodel=medium") may be required for large memory runs.
*
* Array size can be set at compile time without modifying the source
* code for the (many) compilers that support preprocessor definitions
* on the compile line. E.g.,
* gcc -O -DSTREAM_ARRAY_SIZE=100000000 stream.c -o stream.100M
* will override the default size of 10M with a new size of 100M elements
* per array.
*/
#ifndef STREAM_ARRAY_SIZE
# define STREAM_ARRAY_SIZE 10000000
#endif
/* 2) STREAM runs each kernel "NTIMES" times and reports the *best* result
* for any iteration after the first, therefore the minimum value
* for NTIMES is 2.
* There are no rules on maximum allowable values for NTIMES, but
* values larger than the default are unlikely to noticeably
* increase the reported performance.
* NTIMES can also be set on the compile line without changing the source
* code using, for example, "-DNTIMES=7".
*/
#ifdef NTIMES
#if NTIMES<=1
# define NTIMES 10
#endif
#endif
#ifndef NTIMES
# define NTIMES 10
#endif
/* Users are allowed to modify the "OFFSET" variable, which *may* change the
* relative alignment of the arrays (though compilers may change the
* effective offset by making the arrays non-contiguous on some systems).
* Use of non-zero values for OFFSET can be especially helpful if the
* STREAM_ARRAY_SIZE is set to a value close to a large power of 2.
* OFFSET can also be set on the compile line without changing the source
* code using, for example, "-DOFFSET=56".
*/
#ifndef OFFSET
# define OFFSET 0
#endif
/*
* 3) Compile the code with optimization. Many compilers generate
* unreasonably bad code before the optimizer tightens things up.
* If the results are unreasonably good, on the other hand, the
* optimizer might be too smart for me!
*
* For a simple single-core version, try compiling with:
* cc -O stream.c -o stream
* This is known to work on many, many systems....
*
* To use multiple cores, you need to tell the compiler to obey the OpenMP
* directives in the code. This varies by compiler, but a common example is
* gcc -O -fopenmp stream.c -o stream_omp
* The environment variable OMP_NUM_THREADS allows runtime control of the
* number of threads/cores used when the resulting "stream_omp" program
* is executed.
*
* To run with single-precision variables and arithmetic, simply add
* -DSTREAM_TYPE=float
* to the compile line.
* Note that this changes the minimum array sizes required --- see (1) above.
*
* The preprocessor directive "TUNED" does not do much -- it simply causes the
* code to call separate functions to execute each kernel. Trivial versions
* of these functions are provided, but they are *not* tuned -- they just
* provide predefined interfaces to be replaced with tuned code.
*
*
* 4) Optional: Mail the results to mccalpin@cs.virginia.edu
* Be sure to include info that will help me understand:
* a) the computer hardware configuration (e.g., processor model, memory type)
* b) the compiler name/version and compilation flags
* c) any run-time information (such as OMP_NUM_THREADS)
* d) all of the output from the test case.
*
* Thanks!
*
*-----------------------------------------------------------------------*/
# define HLINE "-------------------------------------------------------------\n"
# ifndef MIN
# define MIN(x,y) ((x)<(y)?(x):(y))
# endif
# ifndef MAX
# define MAX(x,y) ((x)>(y)?(x):(y))
# endif
#ifndef STREAM_TYPE
#define STREAM_TYPE double
#endif
static STREAM_TYPE a[STREAM_ARRAY_SIZE+OFFSET],
b[STREAM_ARRAY_SIZE+OFFSET],
c[STREAM_ARRAY_SIZE+OFFSET];
static double avgtime[4] = {0}, maxtime[4] = {0},
mintime[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX};
static char *label[4] = {"Copy: ", "Scale: ",
"Add: ", "Triad: "};
static double bytes[4] = {
2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE
};
extern double mysecond();
extern void checkSTREAMresults();
#ifdef TUNED
extern void tuned_STREAM_Copy();
extern void tuned_STREAM_Scale(STREAM_TYPE scalar);
extern void tuned_STREAM_Add();
extern void tuned_STREAM_Triad(STREAM_TYPE scalar);
#endif
#ifdef _OPENMP
extern int omp_get_num_threads();
#endif
int
main()
{
int quantum, checktick();
int BytesPerWord;
int k;
ssize_t j;
STREAM_TYPE scalar;
double t, times[4][NTIMES];
/* --- SETUP --- determine precision and check timing --- */
printf(HLINE);
printf("STREAM version $Revision: 5.10 $\n");
printf(HLINE);
BytesPerWord = sizeof(STREAM_TYPE);
printf("This system uses %d bytes per array element.\n",
BytesPerWord);
printf(HLINE);
#ifdef N
printf("***** WARNING: ******\n");
printf(" It appears that you set the preprocessor variable N when compiling this code.\n");
printf(" This version of the code uses the preprocesor variable STREAM_ARRAY_SIZE to control the array size\n");
printf(" Reverting to default value of STREAM_ARRAY_SIZE=%llu\n",(unsigned long long) STREAM_ARRAY_SIZE);
printf("***** WARNING: ******\n");
#endif
printf("Array size = %llu (elements), Offset = %d (elements)\n" , (unsigned long long) STREAM_ARRAY_SIZE, OFFSET);
printf("Memory per array = %.1f MiB (= %.1f GiB).\n",
BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0),
BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0/1024.0));
printf("Total memory required = %.1f MiB (= %.1f GiB).\n",
(3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.),
(3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024./1024.));
printf("Each kernel will be executed %d times.\n", NTIMES);
printf(" The *best* time for each kernel (excluding the first iteration)\n");
printf(" will be used to compute the reported bandwidth.\n");
#ifdef _OPENMP
printf(HLINE);
#pragma omp parallel
{
#pragma omp master
{
k = omp_get_num_threads();
printf ("Number of Threads requested = %i\n",k);
}
}
#endif
#ifdef _OPENMP
k = 0;
#pragma omp parallel
#pragma omp atomic
k++;
printf ("Number of Threads counted = %i\n",k);
#endif
/* Get initial value for system clock. */
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
a[j] = 1.0;
b[j] = 2.0;
c[j] = 0.0;
}
printf(HLINE);
if ( (quantum = checktick()) >= 1)
printf("Your clock granularity/precision appears to be "
"%d microseconds.\n", quantum);
else {
printf("Your clock granularity appears to be "
"less than one microsecond.\n");
quantum = 1;
}
t = mysecond();
#pragma omp parallel for
for (j = 0; j < STREAM_ARRAY_SIZE; j++)
a[j] = 2.0E0 * a[j];
t = 1.0E6 * (mysecond() - t);
printf("Each test below will take on the order"
" of %d microseconds.\n", (int) t );
printf(" (= %d clock ticks)\n", (int) (t/quantum) );
printf("Increase the size of the arrays if this shows that\n");
printf("you are not getting at least 20 clock ticks per test.\n");
printf(HLINE);
printf("WARNING -- The above is only a rough guideline.\n");
printf("For best results, please be sure you know the\n");
printf("precision of your system timer.\n");
printf(HLINE);
/* --- MAIN LOOP --- repeat test cases NTIMES times --- */
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
times[0][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Copy();
#else
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j];
#endif
times[0][k] = mysecond() - times[0][k];
times[1][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Scale(scalar);
#else
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
b[j] = scalar*c[j];
#endif
times[1][k] = mysecond() - times[1][k];
times[2][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Add();
#else
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j]+b[j];
#endif
times[2][k] = mysecond() - times[2][k];
times[3][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Triad(scalar);
#else
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
a[j] = b[j]+scalar*c[j];
#endif
times[3][k] = mysecond() - times[3][k];
}
/* --- SUMMARY --- */
for (k=1; k<NTIMES; k++) /* note -- skip first iteration */
{
for (j=0; j<4; j++)
{
avgtime[j] = avgtime[j] + times[j][k];
mintime[j] = MIN(mintime[j], times[j][k]);
maxtime[j] = MAX(maxtime[j], times[j][k]);
}
}
printf("Function Best Rate MB/s Avg time Min time Max time\n");
for (j=0; j<4; j++) {
avgtime[j] = avgtime[j]/(double)(NTIMES-1);
printf("%s%12.1f %11.6f %11.6f %11.6f\n", label[j],
1.0E-06 * bytes[j]/mintime[j],
avgtime[j],
mintime[j],
maxtime[j]);
}
printf(HLINE);
/* --- Check Results --- */
checkSTREAMresults();
printf(HLINE"\n\n\n\n\n");
return 0;
}
# define M 20
int
checktick()
{
int i, minDelta, Delta;
double t1, t2, timesfound[M];
/* Collect a sequence of M unique time values from the system. */
for (i = 0; i < M; i++) {
t1 = mysecond();
while( ((t2=mysecond()) - t1) < 1.0E-6 )
;
timesfound[i] = t1 = t2;
}
/*
* Determine the minimum difference between these M values.
* This result will be our estimate (in microseconds) for the
* clock granularity.
*/
minDelta = 1000000;
for (i = 1; i < M; i++) {
Delta = (int)( 1.0E6 * (timesfound[i]-timesfound[i-1]));
minDelta = MIN(minDelta, MAX(Delta,0));
}
return(minDelta);
}
/* A gettimeofday routine to give access to the wall
clock timer on most UNIX-like systems. */
#include <sys/time.h>
double mysecond()
{
struct timeval tp;
struct timezone tzp;
int i;
i = gettimeofday(&tp,&tzp);
return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 );
}
#ifndef abs
#define abs(a) ((a) >= 0 ? (a) : -(a))
#endif
void checkSTREAMresults ()
{
STREAM_TYPE aj,bj,cj,scalar;
STREAM_TYPE aSumErr,bSumErr,cSumErr;
STREAM_TYPE aAvgErr,bAvgErr,cAvgErr;
double epsilon;
ssize_t j;
int k,ierr,err;
/* reproduce initialization */
aj = 1.0;
bj = 2.0;
cj = 0.0;
/* a[] is modified during timing check */
aj = 2.0E0 * aj;
/* now execute timing loop */
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
cj = aj;
bj = scalar*cj;
cj = aj+bj;
aj = bj+scalar*cj;
}
/* accumulate deltas between observed and expected results */
aSumErr = 0.0;
bSumErr = 0.0;
cSumErr = 0.0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
aSumErr += abs(a[j] - aj);
bSumErr += abs(b[j] - bj);
cSumErr += abs(c[j] - cj);
// if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN
}
aAvgErr = aSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
bAvgErr = bSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
cAvgErr = cSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
if (sizeof(STREAM_TYPE) == 4) {
epsilon = 1.e-6;
}
else if (sizeof(STREAM_TYPE) == 8) {
epsilon = 1.e-13;
}
else {
printf("WEIRD: sizeof(STREAM_TYPE) = %lu\n",sizeof(STREAM_TYPE));
epsilon = 1.e-6;
}
err = 0;
if (abs(aAvgErr/aj) > epsilon) {
err++;
printf ("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n",epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",aj,aAvgErr,abs(aAvgErr)/aj);
ierr = 0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
if (abs(a[j]/aj-1.0) > epsilon) {
ierr++;
#ifdef VERBOSE
if (ierr < 10) {
printf(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j,aj,a[j],abs((aj-a[j])/aAvgErr));
}
#endif
}
}
printf(" For array a[], %d errors were found.\n",ierr);
}
if (abs(bAvgErr/bj) > epsilon) {
err++;
printf ("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n",epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",bj,bAvgErr,abs(bAvgErr)/bj);
printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon);
ierr = 0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
if (abs(b[j]/bj-1.0) > epsilon) {
ierr++;
#ifdef VERBOSE
if (ierr < 10) {
printf(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j,bj,b[j],abs((bj-b[j])/bAvgErr));
}
#endif
}
}
printf(" For array b[], %d errors were found.\n",ierr);
}
if (abs(cAvgErr/cj) > epsilon) {
err++;
printf ("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n",epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",cj,cAvgErr,abs(cAvgErr)/cj);
printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon);
ierr = 0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
if (abs(c[j]/cj-1.0) > epsilon) {
ierr++;
#ifdef VERBOSE
if (ierr < 10) {
printf(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j,cj,c[j],abs((cj-c[j])/cAvgErr));
}
#endif
}
}
printf(" For array c[], %d errors were found.\n",ierr);
}
if (err == 0) {
printf ("Solution Validates: avg error less than %e on all three arrays\n",epsilon);
}
#ifdef VERBOSE
printf ("Results Validation Verbose Results: \n");
printf (" Expected a(1), b(1), c(1): %f %f %f \n",aj,bj,cj);
printf (" Observed a(1), b(1), c(1): %f %f %f \n",a[1],b[1],c[1]);
printf (" Rel Errors on a, b, c: %e %e %e \n",abs(aAvgErr/aj),abs(bAvgErr/bj),abs(cAvgErr/cj));
#endif
}
#ifdef TUNED
/* stubs for "tuned" versions of the kernels */
void tuned_STREAM_Copy()
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j];
}
void tuned_STREAM_Scale(STREAM_TYPE scalar)
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
b[j] = scalar*c[j];
}
void tuned_STREAM_Add()
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j]+b[j];
}
void tuned_STREAM_Triad(STREAM_TYPE scalar)
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
a[j] = b[j]+scalar*c[j];
}
/* end of stubs for the "tuned" versions of the kernels */
#endif
|
convolution_sgemm.h | // BUG1989 is pleased to support the open source community by supporting ncnn available.
//
// Copyright (C) 2019 BUG1989. 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 __AVX__
static void conv_im2col_sgemm_transform_kernel_sse(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size)
{
const float* kernel = _kernel;
// kernel memory packed 8 x 8
kernel_tm.create(8 * kernel_size, inch, outch / 8 + (outch % 8) / 4 + outch % 4);
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 8;
const float* k0 = kernel + (p + 0) * inch * kernel_size;
const float* k1 = kernel + (p + 1) * inch * kernel_size;
const float* k2 = kernel + (p + 2) * inch * kernel_size;
const float* k3 = kernel + (p + 3) * inch * kernel_size;
const float* k4 = kernel + (p + 4) * inch * kernel_size;
const float* k5 = kernel + (p + 5) * inch * kernel_size;
const float* k6 = kernel + (p + 6) * inch * kernel_size;
const float* k7 = kernel + (p + 7) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 8);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp[4] = k4[0];
ktmp[5] = k5[0];
ktmp[6] = k6[0];
ktmp[7] = k7[0];
ktmp += 8;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
k4 += 1;
k5 += 1;
k6 += 1;
k7 += 1;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
const float* k0 = kernel + (p + 0) * inch * kernel_size;
const float* k1 = kernel + (p + 1) * inch * kernel_size;
const float* k2 = kernel + (p + 2) * inch * kernel_size;
const float* k3 = kernel + (p + 3) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp += 4;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
}
}
remain_outch_start += nn_outch << 2;
for (int p = remain_outch_start; p < outch; p++)
{
const float* k0 = kernel + (p + 0) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp++;
k0++;
}
}
}
static void conv_im2col_sgemm_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias,
const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
// im2col
Mat bottom_im2col(outw * outh, kernel_h * kernel_w * inch, elemsize, opt.workspace_allocator);
{
const int stride = kernel_h * kernel_w * outw * outh;
float* ret = (float*)bottom_im2col;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const float* input = bottom_blob.channel(p);
int retID = stride * p;
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
int row = u + i * stride_h;
int col = v + j * stride_w;
int index = row * w + col;
ret[retID] = input[index];
retID++;
}
}
}
}
}
}
int kernel_size = kernel_w * kernel_h;
int out_size = outw * outh;
// bottom_im2col memory packed 8 x 8
Mat bottom_tm(8 * kernel_size, inch, out_size / 8 + out_size % 8, elemsize, opt.workspace_allocator);
{
int nn_size = out_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_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 8);
for (int q = 0; q < inch * kernel_size; q++)
{
#if __AVX__
_mm256_storeu_ps(tmpptr, _mm256_loadu_ps(img0));
#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];
#endif // __SSE__
tmpptr += 8;
img0 += out_size;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < out_size; i++)
{
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 8 + i % 8);
for (int q = 0; q < inch * kernel_size; q++)
{
tmpptr[0] = img0[0];
tmpptr += 1;
img0 += out_size;
}
}
}
// sgemm(int M, int N, int L, float* A, float* B, float* C)
{
//int M = outch; // outch
int N = outw * outh; // outsize or out stride
int L = kernel_w * kernel_h * inch; // ksize * inch
int nn_outch = 0;
int remain_outch_start = 0;
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 i = pp * 8;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i + 1);
float* output2 = top_blob.channel(i + 2);
float* output3 = top_blob.channel(i + 3);
float* output4 = top_blob.channel(i + 4);
float* output5 = top_blob.channel(i + 5);
float* output6 = top_blob.channel(i + 6);
float* output7 = top_blob.channel(i + 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 + i : zeros;
int j = 0;
for (; j + 7 < N; j = j + 8)
{
const float* vb = bottom_tm.channel(j / 8);
const float* va = kernel_tm.channel(i / 8);
#if __AVX__
__m256 _sum0 = _mm256_broadcast_ss(biasptr);
__m256 _sum1 = _mm256_broadcast_ss(biasptr + 1);
__m256 _sum2 = _mm256_broadcast_ss(biasptr + 2);
__m256 _sum3 = _mm256_broadcast_ss(biasptr + 3);
__m256 _sum4 = _mm256_broadcast_ss(biasptr + 4);
__m256 _sum5 = _mm256_broadcast_ss(biasptr + 5);
__m256 _sum6 = _mm256_broadcast_ss(biasptr + 6);
__m256 _sum7 = _mm256_broadcast_ss(biasptr + 7);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _vb0 = _mm256_loadu_ps(vb);
__m256 _vb1 = _mm256_loadu_ps(vb + 8);
__m256 _vb2 = _mm256_loadu_ps(vb + 16);
__m256 _vb3 = _mm256_loadu_ps(vb + 24);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
_va0 = _mm256_broadcast_ss(va + 4);
_va1 = _mm256_broadcast_ss(va + 5);
_va2 = _mm256_broadcast_ss(va + 6);
_va3 = _mm256_broadcast_ss(va + 7);
_sum4 = _mm256_fmadd_ps(_vb0, _va0, _sum4); // sum4 = (a00-a07) * k40
_sum5 = _mm256_fmadd_ps(_vb0, _va1, _sum5); // sum5 = (a00-a07) * k50
_sum6 = _mm256_fmadd_ps(_vb0, _va2, _sum6); // sum6 = (a00-a07) * k60
_sum7 = _mm256_fmadd_ps(_vb0, _va3, _sum7); // sum7 = (a00-a07) * k70
va += 8;
// k1
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb1, _va0, _sum0); // sum0 += (a10-a17) * k01
_sum1 = _mm256_fmadd_ps(_vb1, _va1, _sum1); // sum1 += (a10-a17) * k11
_sum2 = _mm256_fmadd_ps(_vb1, _va2, _sum2); // sum2 += (a10-a17) * k21
_sum3 = _mm256_fmadd_ps(_vb1, _va3, _sum3); // sum3 += (a10-a17) * k31
_va0 = _mm256_broadcast_ss(va + 4);
_va1 = _mm256_broadcast_ss(va + 5);
_va2 = _mm256_broadcast_ss(va + 6);
_va3 = _mm256_broadcast_ss(va + 7);
_sum4 = _mm256_fmadd_ps(_vb1, _va0, _sum4); // sum4 += (a10-a17) * k41
_sum5 = _mm256_fmadd_ps(_vb1, _va1, _sum5); // sum5 += (a10-a17) * k51
_sum6 = _mm256_fmadd_ps(_vb1, _va2, _sum6); // sum6 += (a10-a17) * k61
_sum7 = _mm256_fmadd_ps(_vb1, _va3, _sum7); // sum7 += (a10-a17) * k71
va += 8;
// k2
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb2, _va0, _sum0); // sum0 += (a20-a27) * k02
_sum1 = _mm256_fmadd_ps(_vb2, _va1, _sum1); // sum1 += (a20-a27) * k12
_sum2 = _mm256_fmadd_ps(_vb2, _va2, _sum2); // sum2 += (a20-a27) * k22
_sum3 = _mm256_fmadd_ps(_vb2, _va3, _sum3); // sum3 += (a20-a27) * k32
_va0 = _mm256_broadcast_ss(va + 4);
_va1 = _mm256_broadcast_ss(va + 5);
_va2 = _mm256_broadcast_ss(va + 6);
_va3 = _mm256_broadcast_ss(va + 7);
_sum4 = _mm256_fmadd_ps(_vb2, _va0, _sum4); // sum4 += (a20-a27) * k42
_sum5 = _mm256_fmadd_ps(_vb2, _va1, _sum5); // sum5 += (a20-a27) * k52
_sum6 = _mm256_fmadd_ps(_vb2, _va2, _sum6); // sum6 += (a20-a27) * k62
_sum7 = _mm256_fmadd_ps(_vb2, _va3, _sum7); // sum7 += (a20-a27) * k72
va += 8;
// k3
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb3, _va0, _sum0); // sum0 += (a30-a37) * k03
_sum1 = _mm256_fmadd_ps(_vb3, _va1, _sum1); // sum1 += (a30-a37) * k13
_sum2 = _mm256_fmadd_ps(_vb3, _va2, _sum2); // sum2 += (a30-a37) * k23
_sum3 = _mm256_fmadd_ps(_vb3, _va3, _sum3); // sum3 += (a30-a37) * k33
_va0 = _mm256_broadcast_ss(va + 4);
_va1 = _mm256_broadcast_ss(va + 5);
_va2 = _mm256_broadcast_ss(va + 6);
_va3 = _mm256_broadcast_ss(va + 7);
_sum4 = _mm256_fmadd_ps(_vb3, _va0, _sum4); // sum4 += (a30-a37) * k43
_sum5 = _mm256_fmadd_ps(_vb3, _va1, _sum5); // sum5 += (a30-a37) * k53
_sum6 = _mm256_fmadd_ps(_vb3, _va2, _sum6); // sum6 += (a30-a37) * k63
_sum7 = _mm256_fmadd_ps(_vb3, _va3, _sum7); // sum7 += (a30-a37) * k73
va += 8;
vb += 32;
}
for (; k < L; k++)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _va4 = _mm256_broadcast_ss(va + 4);
__m256 _va5 = _mm256_broadcast_ss(va + 5);
__m256 _va6 = _mm256_broadcast_ss(va + 6);
__m256 _va7 = _mm256_broadcast_ss(va + 7);
__m256 _vb0 = _mm256_loadu_ps(vb);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
_sum4 = _mm256_fmadd_ps(_vb0, _va4, _sum4); // sum4 = (a00-a07) * k40
_sum5 = _mm256_fmadd_ps(_vb0, _va5, _sum5); // sum5 = (a00-a07) * k50
_sum6 = _mm256_fmadd_ps(_vb0, _va6, _sum6); // sum6 = (a00-a07) * k60
_sum7 = _mm256_fmadd_ps(_vb0, _va7, _sum7); // sum7 = (a00-a07) * k70
va += 8;
vb += 8;
}
_mm256_storeu_ps(output0, _sum0);
_mm256_storeu_ps(output1, _sum1);
_mm256_storeu_ps(output2, _sum2);
_mm256_storeu_ps(output3, _sum3);
_mm256_storeu_ps(output4, _sum4);
_mm256_storeu_ps(output5, _sum5);
_mm256_storeu_ps(output6, _sum6);
_mm256_storeu_ps(output7, _sum7);
#else
float sum0[8] = {0};
float sum1[8] = {0};
float sum2[8] = {0};
float sum3[8] = {0};
float sum4[8] = {0};
float sum5[8] = {0};
float sum6[8] = {0};
float sum7[8] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
sum4[n] += va[4] * vb[n];
sum5[n] += va[5] * vb[n];
sum6[n] += va[6] * vb[n];
sum7[n] += va[7] * vb[n];
va += 8;
sum0[n] += va[0] * vb[n + 8];
sum1[n] += va[1] * vb[n + 8];
sum2[n] += va[2] * vb[n + 8];
sum3[n] += va[3] * vb[n + 8];
sum4[n] += va[4] * vb[n + 8];
sum5[n] += va[5] * vb[n + 8];
sum6[n] += va[6] * vb[n + 8];
sum7[n] += va[7] * vb[n + 8];
va += 8;
sum0[n] += va[0] * vb[n + 16];
sum1[n] += va[1] * vb[n + 16];
sum2[n] += va[2] * vb[n + 16];
sum3[n] += va[3] * vb[n + 16];
sum4[n] += va[4] * vb[n + 16];
sum5[n] += va[5] * vb[n + 16];
sum6[n] += va[6] * vb[n + 16];
sum7[n] += va[7] * vb[n + 16];
va += 8;
sum0[n] += va[0] * vb[n + 24];
sum1[n] += va[1] * vb[n + 24];
sum2[n] += va[2] * vb[n + 24];
sum3[n] += va[3] * vb[n + 24];
sum4[n] += va[4] * vb[n + 24];
sum5[n] += va[5] * vb[n + 24];
sum6[n] += va[6] * vb[n + 24];
sum7[n] += va[7] * vb[n + 24];
va += 8;
sum0[n] += va[0] * vb[n + 32];
sum1[n] += va[1] * vb[n + 32];
sum2[n] += va[2] * vb[n + 32];
sum3[n] += va[3] * vb[n + 32];
sum4[n] += va[4] * vb[n + 32];
sum5[n] += va[5] * vb[n + 32];
sum6[n] += va[6] * vb[n + 32];
sum7[n] += va[7] * vb[n + 32];
va += 8;
sum0[n] += va[0] * vb[n + 40];
sum1[n] += va[1] * vb[n + 40];
sum2[n] += va[2] * vb[n + 40];
sum3[n] += va[3] * vb[n + 40];
sum4[n] += va[4] * vb[n + 40];
sum5[n] += va[5] * vb[n + 40];
sum6[n] += va[6] * vb[n + 40];
sum7[n] += va[7] * vb[n + 40];
va += 8;
sum0[n] += va[0] * vb[n + 48];
sum1[n] += va[1] * vb[n + 48];
sum2[n] += va[2] * vb[n + 48];
sum3[n] += va[3] * vb[n + 48];
sum4[n] += va[4] * vb[n + 48];
sum5[n] += va[5] * vb[n + 48];
sum6[n] += va[6] * vb[n + 48];
sum7[n] += va[7] * vb[n + 48];
va += 8;
sum0[n] += va[0] * vb[n + 56];
sum1[n] += va[1] * vb[n + 56];
sum2[n] += va[2] * vb[n + 56];
sum3[n] += va[3] * vb[n + 56];
sum4[n] += va[4] * vb[n + 56];
sum5[n] += va[5] * vb[n + 56];
sum6[n] += va[6] * vb[n + 56];
sum7[n] += va[7] * vb[n + 56];
va -= 56;
}
va += 64;
vb += 64;
}
for (; k < L; k++)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
sum4[n] += va[4] * vb[n];
sum5[n] += va[5] * vb[n];
sum6[n] += va[6] * vb[n];
sum7[n] += va[7] * vb[n];
}
va += 8;
vb += 8;
}
for (int n = 0; n < 8; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
output4[n] = sum4[n] + biasptr[4];
output5[n] = sum5[n] + biasptr[5];
output6[n] = sum6[n] + biasptr[6];
output7[n] = sum7[n] + biasptr[7];
}
#endif // __AVX__
output0 += 8;
output1 += 8;
output2 += 8;
output3 += 8;
output4 += 8;
output5 += 8;
output6 += 8;
output7 += 8;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 8 + j % 8);
const float* va = kernel_tm.channel(i / 8);
#if __AVX__
__m256 _sum0_7 = _mm256_loadu_ps(biasptr);
__m256 _sum0 = _mm256_set1_ps(0.0);
__m256 _sum1 = _mm256_set1_ps(0.0);
__m256 _sum2 = _mm256_set1_ps(0.0);
__m256 _sum3 = _mm256_set1_ps(0.0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
__m256 _vb0 = _mm256_broadcast_ss(vb);
__m256 _vb1 = _mm256_broadcast_ss(vb + 1);
__m256 _vb2 = _mm256_broadcast_ss(vb + 2);
__m256 _vb3 = _mm256_broadcast_ss(vb + 3);
__m256 _va0 = _mm256_loadu_ps(va);
__m256 _va1 = _mm256_loadu_ps(va + 8);
__m256 _va2 = _mm256_loadu_ps(va + 16);
__m256 _va3 = _mm256_loadu_ps(va + 24);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); // sum0 += (k00-k70) * a00
_sum1 = _mm256_fmadd_ps(_va1, _vb1, _sum1); // sum1 += (k01-k71) * a10
_sum2 = _mm256_fmadd_ps(_va2, _vb2, _sum2); // sum2 += (k02-k72) * a20
_sum3 = _mm256_fmadd_ps(_va3, _vb3, _sum3); // sum3 += (k03-k73) * a30
va += 32;
vb += 4;
}
_sum0 = _mm256_add_ps(_sum0, _sum1);
_sum2 = _mm256_add_ps(_sum2, _sum3);
_sum0_7 = _mm256_add_ps(_sum0_7, _sum0);
_sum0_7 = _mm256_add_ps(_sum0_7, _sum2);
for (; k < L; k++)
{
__m256 _vb0 = _mm256_broadcast_ss(vb);
__m256 _va = _mm256_loadu_ps(va);
_sum0_7 = _mm256_fmadd_ps(_va, _vb0, _sum0_7); // sum0 += (k00-k70) * a00
va += 8;
vb += 1;
}
float output_sum0_7[8] = {0.f};
_mm256_storeu_ps(output_sum0_7, _sum0_7);
output0[0] = output_sum0_7[0];
output1[0] = output_sum0_7[1];
output2[0] = output_sum0_7[2];
output3[0] = output_sum0_7[3];
output4[0] = output_sum0_7[4];
output5[0] = output_sum0_7[5];
output6[0] = output_sum0_7[6];
output7[0] = output_sum0_7[7];
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
float sum4 = biasptr[4];
float sum5 = biasptr[5];
float sum6 = biasptr[6];
float sum7 = biasptr[7];
for (int k = 0; k < L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
sum4 += va[4] * vb[0];
sum5 += va[5] * vb[0];
sum6 += va[6] * vb[0];
sum7 += va[7] * vb[0];
va += 8;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
output4[0] = sum4;
output5[0] = sum5;
output6[0] = sum6;
output7[0] = sum7;
#endif // __AVX__
output0++;
output1++;
output2++;
output3++;
output4++;
output5++;
output6++;
output7++;
}
}
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 i = remain_outch_start + pp * 4;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i + 1);
float* output2 = top_blob.channel(i + 2);
float* output3 = top_blob.channel(i + 3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + i : zeros;
int j = 0;
for (; j + 7 < N; j = j + 8)
{
const float* vb = bottom_tm.channel(j / 8);
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4);
#if __AVX__
__m256 _sum0 = _mm256_broadcast_ss(biasptr);
__m256 _sum1 = _mm256_broadcast_ss(biasptr + 1);
__m256 _sum2 = _mm256_broadcast_ss(biasptr + 2);
__m256 _sum3 = _mm256_broadcast_ss(biasptr + 3);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _vb0 = _mm256_loadu_ps(vb);
__m256 _vb1 = _mm256_loadu_ps(vb + 8);
__m256 _vb2 = _mm256_loadu_ps(vb + 16);
__m256 _vb3 = _mm256_loadu_ps(vb + 24);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
va += 4;
// k1
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb1, _va0, _sum0); // sum0 += (a10-a17) * k01
_sum1 = _mm256_fmadd_ps(_vb1, _va1, _sum1); // sum1 += (a10-a17) * k11
_sum2 = _mm256_fmadd_ps(_vb1, _va2, _sum2); // sum2 += (a10-a17) * k21
_sum3 = _mm256_fmadd_ps(_vb1, _va3, _sum3); // sum3 += (a10-a17) * k31
va += 4;
// k2
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb2, _va0, _sum0); // sum0 += (a20-a27) * k02
_sum1 = _mm256_fmadd_ps(_vb2, _va1, _sum1); // sum1 += (a20-a27) * k12
_sum2 = _mm256_fmadd_ps(_vb2, _va2, _sum2); // sum2 += (a20-a27) * k22
_sum3 = _mm256_fmadd_ps(_vb2, _va3, _sum3); // sum3 += (a20-a27) * k32
va += 4;
// k3
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va + 1);
_va2 = _mm256_broadcast_ss(va + 2);
_va3 = _mm256_broadcast_ss(va + 3);
_sum0 = _mm256_fmadd_ps(_vb3, _va0, _sum0); // sum0 += (a30-a37) * k03
_sum1 = _mm256_fmadd_ps(_vb3, _va1, _sum1); // sum1 += (a30-a37) * k13
_sum2 = _mm256_fmadd_ps(_vb3, _va2, _sum2); // sum2 += (a30-a37) * k23
_sum3 = _mm256_fmadd_ps(_vb3, _va3, _sum3); // sum3 += (a30-a37) * k33
va += 4;
vb += 32;
}
for (; k < L; k++)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _vb0 = _mm256_loadu_ps(vb);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
va += 4;
vb += 8;
}
_mm256_storeu_ps(output0, _sum0);
_mm256_storeu_ps(output1, _sum1);
_mm256_storeu_ps(output2, _sum2);
_mm256_storeu_ps(output3, _sum3);
#else
float sum0[8] = {0};
float sum1[8] = {0};
float sum2[8] = {0};
float sum3[8] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
va += 4;
sum0[n] += va[0] * vb[n + 8];
sum1[n] += va[1] * vb[n + 8];
sum2[n] += va[2] * vb[n + 8];
sum3[n] += va[3] * vb[n + 8];
va += 4;
sum0[n] += va[0] * vb[n + 16];
sum1[n] += va[1] * vb[n + 16];
sum2[n] += va[2] * vb[n + 16];
sum3[n] += va[3] * vb[n + 16];
va += 4;
sum0[n] += va[0] * vb[n + 24];
sum1[n] += va[1] * vb[n + 24];
sum2[n] += va[2] * vb[n + 24];
sum3[n] += va[3] * vb[n + 24];
va += 4;
sum0[n] += va[0] * vb[n + 32];
sum1[n] += va[1] * vb[n + 32];
sum2[n] += va[2] * vb[n + 32];
sum3[n] += va[3] * vb[n + 32];
va += 4;
sum0[n] += va[0] * vb[n + 40];
sum1[n] += va[1] * vb[n + 40];
sum2[n] += va[2] * vb[n + 40];
sum3[n] += va[3] * vb[n + 40];
va += 4;
sum0[n] += va[0] * vb[n + 48];
sum1[n] += va[1] * vb[n + 48];
sum2[n] += va[2] * vb[n + 48];
sum3[n] += va[3] * vb[n + 48];
va += 4;
sum0[n] += va[0] * vb[n + 56];
sum1[n] += va[1] * vb[n + 56];
sum2[n] += va[2] * vb[n + 56];
sum3[n] += va[3] * vb[n + 56];
va -= 28;
}
va += 32;
vb += 64;
}
for (; k < L; k++)
{
for (int n = 0; n < 8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
}
va += 4;
vb += 8;
}
for (int n = 0; n < 8; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
}
#endif // __AVX__
output0 += 8;
output1 += 8;
output2 += 8;
output3 += 8;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 8 + j % 8);
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4);
#if __AVX__
__m128 _sum0_3 = _mm_loadu_ps(biasptr);
__m128 _sum0 = _mm_set1_ps(0.0);
__m128 _sum1 = _mm_set1_ps(0.0);
__m128 _sum2 = _mm_set1_ps(0.0);
__m128 _sum3 = _mm_set1_ps(0.0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _vb1 = _mm_set1_ps(vb[1]);
__m128 _vb2 = _mm_set1_ps(vb[2]);
__m128 _vb3 = _mm_set1_ps(vb[3]);
__m128 _va0 = _mm_loadu_ps(va);
__m128 _va1 = _mm_loadu_ps(va + 4);
__m128 _va2 = _mm_loadu_ps(va + 8);
__m128 _va3 = _mm_loadu_ps(va + 12);
_sum0 = _mm_fmadd_ps(_va0, _vb0, _sum0); // sum0 += (k00-k30) * a00
_sum1 = _mm_fmadd_ps(_va1, _vb1, _sum1); // sum1 += (k01-k31) * a10
_sum2 = _mm_fmadd_ps(_va2, _vb2, _sum2); // sum2 += (k02-k32) * a20
_sum3 = _mm_fmadd_ps(_va3, _vb3, _sum3); // sum3 += (k03-k33) * a30
va += 16;
vb += 4;
}
_sum0 = _mm_add_ps(_sum0, _sum1);
_sum2 = _mm_add_ps(_sum2, _sum3);
_sum0_3 = _mm_add_ps(_sum0_3, _sum0);
_sum0_3 = _mm_add_ps(_sum0_3, _sum2);
for (; k < L; k++)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _va = _mm_loadu_ps(va);
_sum0_3 = _mm_fmadd_ps(_va, _vb0, _sum0_3); // sum0 += (k00-k30) * a00
va += 4;
vb += 1;
}
float output_sum0_3[4] = {0.f};
_mm_storeu_ps(output_sum0_3, _sum0_3);
output0[0] = output_sum0_3[0];
output1[0] = output_sum0_3[1];
output2[0] = output_sum0_3[2];
output3[0] = output_sum0_3[3];
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
for (int k = 0; k < L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
va += 4;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
#endif // __AVX__
output0++;
output1++;
output2++;
output3++;
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_outch_start; i < outch; i++)
{
float* output = top_blob.channel(i);
const float bias0 = bias ? bias[i] : 0.f;
int j = 0;
for (; j + 7 < N; j = j + 8)
{
const float* vb = bottom_tm.channel(j / 8);
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4 + i % 4);
#if __AVX__
__m256 _sum0 = _mm256_broadcast_ss(&bias0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va + 1);
__m256 _va2 = _mm256_broadcast_ss(va + 2);
__m256 _va3 = _mm256_broadcast_ss(va + 3);
__m256 _vb0 = _mm256_loadu_ps(vb);
__m256 _vb1 = _mm256_loadu_ps(vb + 8);
__m256 _vb2 = _mm256_loadu_ps(vb + 16);
__m256 _vb3 = _mm256_loadu_ps(vb + 24);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum0 = _mm256_fmadd_ps(_vb1, _va1, _sum0); // sum0 += (a10-a17) * k01
_sum0 = _mm256_fmadd_ps(_vb2, _va2, _sum0); // sum0 += (a20-a27) * k02
_sum0 = _mm256_fmadd_ps(_vb3, _va3, _sum0); // sum0 += (a30-a37) * k03
va += 4;
vb += 32;
}
for (; k < L; k++)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _vb0 = _mm256_loadu_ps(vb);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
va += 1;
vb += 8;
}
_mm256_storeu_ps(output, _sum0);
#else
float sum[8] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 8; n++)
{
sum[n] += va[0] * vb[n];
sum[n] += va[1] * vb[n + 8];
sum[n] += va[2] * vb[n + 16];
sum[n] += va[3] * vb[n + 24];
sum[n] += va[4] * vb[n + 32];
sum[n] += va[5] * vb[n + 40];
sum[n] += va[6] * vb[n + 48];
sum[n] += va[7] * vb[n + 56];
}
va += 8;
vb += 64;
}
for (; k < L; k++)
{
for (int n = 0; n < 8; n++)
{
sum[n] += va[0] * vb[n];
}
va += 1;
vb += 8;
}
for (int n = 0; n < 8; n++)
{
output[n] = sum[n] + bias0;
}
#endif // __AVX__
output += 8;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 8 + j % 8);
const float* va = kernel_tm.channel(i / 8 + (i % 8) / 4 + i % 4);
int k = 0;
#if __AVX__
__m128 _sum0 = _mm_set1_ps(0.f);
for (; k + 3 < L; k += 4)
{
__m128 _p0 = _mm_loadu_ps(vb);
vb += 4;
__m128 _k0 = _mm_loadu_ps(va);
va += 4;
_sum0 = _mm_fmadd_ps(_p0, _k0, _sum0);
}
float output_sum0[4] = {0.f};
_mm_storeu_ps(output_sum0, _sum0);
float sum0 = bias0 + output_sum0[0] + output_sum0[1] + output_sum0[2] + output_sum0[3];
#else
float sum0 = bias0;
#endif // __AVX__
for (; k < L; k++)
{
sum0 += va[0] * vb[0];
va += 1;
vb += 1;
}
output[0] = sum0;
output++;
}
}
}
}
#else
static void conv_im2col_sgemm_transform_kernel_sse(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size)
{
const float* kernel = _kernel;
// kernel memory packed 4 x 4
kernel_tm.create(4 * kernel_size, inch, outch / 4 + outch % 4);
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 2;
remain_outch_start = nn_outch << 2;
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 4;
const float* k0 = kernel + (p + 0) * inch * kernel_size;
const float* k1 = kernel + (p + 1) * inch * kernel_size;
const float* k2 = kernel + (p + 2) * inch * kernel_size;
const float* k3 = kernel + (p + 3) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 4);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp += 4;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
}
}
for (int p = remain_outch_start; p < outch; p++)
{
const float* k0 = kernel + (p + 0) * inch * kernel_size;
float* ktmp = kernel_tm.channel(p / 4 + p % 4);
for (int q = 0; q < inch * kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp++;
k0++;
}
}
}
static void conv_im2col_sgemm_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias,
const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
// im2col
Mat bottom_im2col(outw * outh, kernel_h * kernel_w * inch, elemsize, opt.workspace_allocator);
{
const int stride = kernel_h * kernel_w * outw * outh;
float* ret = (float*)bottom_im2col;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const float* input = bottom_blob.channel(p);
int retID = stride * p;
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
int row = u + i * stride_h;
int col = v + j * stride_w;
int index = row * w + col;
ret[retID] = input[index];
retID++;
}
}
}
}
}
}
int kernel_size = kernel_w * kernel_h;
int out_size = outw * outh;
// bottom_im2col memory packed 4 x 4
Mat bottom_tm(4 * kernel_size, inch, out_size / 4 + out_size % 4, elemsize, opt.workspace_allocator);
{
int nn_size = out_size >> 2;
int remain_size_start = nn_size << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = ii * 4;
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 4);
for (int q = 0; q < inch * kernel_size; q++)
{
#if __SSE__
_mm_storeu_ps(tmpptr, _mm_loadu_ps(img0));
#else
tmpptr[0] = img0[0];
tmpptr[1] = img0[1];
tmpptr[2] = img0[2];
tmpptr[3] = img0[3];
#endif // __SSE__
tmpptr += 4;
img0 += out_size;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < out_size; i++)
{
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i / 4 + i % 4);
for (int q = 0; q < inch * kernel_size; q++)
{
tmpptr[0] = img0[0];
tmpptr += 1;
img0 += out_size;
}
}
}
// sgemm(int M, int N, int L, float* A, float* B, float* C)
{
//int M = outch; // outch
int N = outw * outh; // outsize or out stride
int L = kernel_w * kernel_h * inch; // ksize * inch
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 2;
remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int i = pp * 4;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i + 1);
float* output2 = top_blob.channel(i + 2);
float* output3 = top_blob.channel(i + 3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + i : zeros;
int j = 0;
for (; j + 3 < N; j = j + 4)
{
const float* vb = bottom_tm.channel(j / 4);
const float* va = kernel_tm.channel(i / 4);
#if __SSE__
__m128 _sum0 = _mm_set1_ps(biasptr[0]);
__m128 _sum1 = _mm_set1_ps(biasptr[1]);
__m128 _sum2 = _mm_set1_ps(biasptr[2]);
__m128 _sum3 = _mm_set1_ps(biasptr[3]);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m128 _vb = _mm_loadu_ps(vb);
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _va1 = _mm_set1_ps(va[1]);
__m128 _va2 = _mm_set1_ps(va[2]);
__m128 _va3 = _mm_set1_ps(va[3]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a00-a03) * k00
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a00-a03) * k10
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a00-a03) * k20
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a00-a03) * k30
// k1
_vb = _mm_loadu_ps(vb + 4);
_va0 = _mm_set1_ps(va[4]);
_va1 = _mm_set1_ps(va[5]);
_va2 = _mm_set1_ps(va[6]);
_va3 = _mm_set1_ps(va[7]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a10-a13) * k01
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a10-a13) * k11
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a10-a13) * k21
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a10-a13) * k31
// k2
_vb = _mm_loadu_ps(vb + 8);
_va0 = _mm_set1_ps(va[8]);
_va1 = _mm_set1_ps(va[9]);
_va2 = _mm_set1_ps(va[10]);
_va3 = _mm_set1_ps(va[11]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a20-a23) * k02
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a20-a23) * k12
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a20-a23) * k22
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a20-a23) * k32
// k3
_vb = _mm_loadu_ps(vb + 12);
_va0 = _mm_set1_ps(va[12]);
_va1 = _mm_set1_ps(va[13]);
_va2 = _mm_set1_ps(va[14]);
_va3 = _mm_set1_ps(va[15]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a30-a33) * k03
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a30-a33) * k13
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a30-a33) * k23
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a30-a33) * k33
va += 16;
vb += 16;
}
for (; k < L; k++)
{
// k0
__m128 _vb = _mm_loadu_ps(vb);
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _va1 = _mm_set1_ps(va[1]);
__m128 _va2 = _mm_set1_ps(va[2]);
__m128 _va3 = _mm_set1_ps(va[3]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0)); // sum0 = (a00-a03) * k00
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1)); // sum1 = (a00-a03) * k10
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2)); // sum2 = (a00-a03) * k20
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3)); // sum3 = (a00-a03) * k30
va += 4;
vb += 4;
}
_mm_storeu_ps(output0, _sum0);
_mm_storeu_ps(output1, _sum1);
_mm_storeu_ps(output2, _sum2);
_mm_storeu_ps(output3, _sum3);
#else
float sum0[4] = {0};
float sum1[4] = {0};
float sum2[4] = {0};
float sum3[4] = {0};
int k = 0;
for (; k + 7 < L; k = k + 8)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
va += 4;
sum0[n] += va[0] * vb[n + 4];
sum1[n] += va[1] * vb[n + 4];
sum2[n] += va[2] * vb[n + 4];
sum3[n] += va[3] * vb[n + 4];
va += 4;
sum0[n] += va[0] * vb[n + 8];
sum1[n] += va[1] * vb[n + 8];
sum2[n] += va[2] * vb[n + 8];
sum3[n] += va[3] * vb[n + 8];
va += 4;
sum0[n] += va[0] * vb[n + 12];
sum1[n] += va[1] * vb[n + 12];
sum2[n] += va[2] * vb[n + 12];
sum3[n] += va[3] * vb[n + 12];
va += 4;
sum0[n] += va[0] * vb[n + 16];
sum1[n] += va[1] * vb[n + 16];
sum2[n] += va[2] * vb[n + 16];
sum3[n] += va[3] * vb[n + 16];
va += 4;
sum0[n] += va[0] * vb[n + 20];
sum1[n] += va[1] * vb[n + 20];
sum2[n] += va[2] * vb[n + 20];
sum3[n] += va[3] * vb[n + 20];
va += 4;
sum0[n] += va[0] * vb[n + 24];
sum1[n] += va[1] * vb[n + 24];
sum2[n] += va[2] * vb[n + 24];
sum3[n] += va[3] * vb[n + 24];
va += 4;
sum0[n] += va[0] * vb[n + 28];
sum1[n] += va[1] * vb[n + 28];
sum2[n] += va[2] * vb[n + 28];
sum3[n] += va[3] * vb[n + 28];
va -= 28;
}
va += 32;
vb += 32;
}
for (; k < L; k++)
{
for (int n = 0; n < 4; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
}
va += 4;
vb += 4;
}
for (int n = 0; n < 4; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
}
#endif // __SSE__
output0 += 4;
output1 += 4;
output2 += 4;
output3 += 4;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 4 + j % 4);
const float* va = kernel_tm.channel(i / 4);
#if __SSE__
__m128 _sum0_3 = _mm_loadu_ps(biasptr);
__m128 _sum0 = _mm_set1_ps(0.0);
__m128 _sum1 = _mm_set1_ps(0.0);
__m128 _sum2 = _mm_set1_ps(0.0);
__m128 _sum3 = _mm_set1_ps(0.0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _vb1 = _mm_set1_ps(vb[1]);
__m128 _vb2 = _mm_set1_ps(vb[2]);
__m128 _vb3 = _mm_set1_ps(vb[3]);
__m128 _va0 = _mm_loadu_ps(va);
__m128 _va1 = _mm_loadu_ps(va + 4);
__m128 _va2 = _mm_loadu_ps(va + 8);
__m128 _va3 = _mm_loadu_ps(va + 12);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0)); // sum0 += (k00-k30) * a00
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va1, _vb1)); // sum1 += (k01-k31) * a10
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va2, _vb2)); // sum2 += (k02-k32) * a20
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va3, _vb3)); // sum3 += (k03-k33) * a30
va += 16;
vb += 4;
}
_sum0 = _mm_add_ps(_sum0, _sum1);
_sum2 = _mm_add_ps(_sum2, _sum3);
_sum0_3 = _mm_add_ps(_sum0_3, _sum0);
_sum0_3 = _mm_add_ps(_sum0_3, _sum2);
for (; k < L; k++)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _va = _mm_loadu_ps(va);
_sum0_3 = _mm_add_ps(_sum0_3, _mm_mul_ps(_va, _vb0)); // sum0 += (k00-k30) * a00
va += 4;
vb += 1;
}
output0[0] = _sum0_3[0];
output1[0] = _sum0_3[1];
output2[0] = _sum0_3[2];
output3[0] = _sum0_3[3];
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
for (int k = 0; k < L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
va += 4;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
#endif // __SSE__
output0++;
output1++;
output2++;
output3++;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_outch_start; i < outch; i++)
{
float* output = top_blob.channel(i);
const float bias0 = bias ? bias[i] : 0.f;
int j = 0;
for (; j + 3 < N; j = j + 4)
{
const float* vb = bottom_tm.channel(j / 4);
const float* va = kernel_tm.channel(i / 4 + i % 4);
#if __SSE__
__m128 _sum0 = _mm_set1_ps(bias0);
int k = 0;
for (; k + 3 < L; k = k + 4)
{
// k0
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _va1 = _mm_set1_ps(va[1]);
__m128 _va2 = _mm_set1_ps(va[2]);
__m128 _va3 = _mm_set1_ps(va[3]);
__m128 _vb0 = _mm_loadu_ps(vb);
__m128 _vb1 = _mm_loadu_ps(vb + 4);
__m128 _vb2 = _mm_loadu_ps(vb + 8);
__m128 _vb3 = _mm_loadu_ps(vb + 12);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb0, _va0)); // sum0 = (a00-a03) * k00
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb1, _va1)); // sum0 += (a10-a13) * k01
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb2, _va2)); // sum0 += (a20-a23) * k02
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb3, _va3)); // sum0 += (a30-a33) * k03
va += 4;
vb += 16;
}
for (; k < L; k++)
{
// k0
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _vb0 = _mm_loadu_ps(vb);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb0, _va0)); // sum0 = (a00-a03) * k00
va += 1;
vb += 4;
}
_mm_storeu_ps(output, _sum0);
#else
float sum[4] = {0};
int k = 0;
for (; k + 3 < L; k = k + 4)
{
for (int n = 0; n < 4; n++)
{
sum[n] += va[0] * vb[n];
sum[n] += va[1] * vb[n + 4];
sum[n] += va[2] * vb[n + 8];
sum[n] += va[3] * vb[n + 12];
//sum[n] += va[4] * vb[n+16];
//sum[n] += va[5] * vb[n+20];
//sum[n] += va[6] * vb[n+24];
//sum[n] += va[7] * vb[n+28];
}
va += 4;
vb += 16;
}
for (; k < L; k++)
{
for (int n = 0; n < 4; n++)
{
sum[n] += va[0] * vb[n];
}
va += 1;
vb += 4;
}
for (int n = 0; n < 4; n++)
{
output[n] = sum[n] + bias0;
}
#endif // __SSE__
output += 4;
}
for (; j < N; j++)
{
const float* vb = bottom_tm.channel(j / 4 + j % 4);
const float* va = kernel_tm.channel(i / 4 + i % 4);
int k = 0;
#if __SSE__
__m128 _sum0 = _mm_set1_ps(0.f);
for (; k + 3 < L; k += 4)
{
__m128 _p0 = _mm_loadu_ps(vb);
__m128 _k0 = _mm_loadu_ps(va);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_p0, _k0));
va += 4;
vb += 4;
}
float sum0 = bias0 + _sum0[0] + _sum0[1] + _sum0[2] + _sum0[3];
#else
float sum0 = bias0;
#endif // __SSE__
for (; k < L; k++)
{
sum0 += va[0] * vb[0];
va += 1;
vb += 1;
}
output[0] = sum0;
output++;
}
}
}
}
#endif
|
DRB108-atomic-orig-no.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>
/*
* Test if atomic can be recognized properly. No data races.
* */
int main (void)
{
int a=0;
#pragma omp parallel for reduction (+:a)
for (int i = 0; i < 100; i++)
{
a += 1;
}
printf ("a=%d\n",a);
return 0;
}
|
synchrotron.c | // Licensed under a 3-clause BSD style license - see LICENSE
#include "math.h"
#include "stdlib.h"
#include "common.h"
#include "edist.h"
#include "stdio.h"
#include "gsl/gsl_integration.h"
/*****************************************************************************/
// Calculate synchrotron F(x) function with interpolation
const double sF_x[50] = {7.943e-05, 1.014e-04, 1.295e-04, 1.653e-04, 2.111e-04,
2.695e-04, 3.441e-04, 4.394e-04, 5.610e-04, 7.163e-04,
9.146e-04, 1.168e-03, 1.491e-03, 1.904e-03, 2.431e-03,
3.103e-03, 3.962e-03, 5.059e-03, 6.460e-03, 8.248e-03,
1.053e-02, 1.345e-02, 1.717e-02, 2.192e-02, 2.799e-02,
3.573e-02, 4.562e-02, 5.825e-02, 7.438e-02, 9.496e-02,
1.212e-01, 1.548e-01, 1.977e-01, 2.524e-01, 3.222e-01,
4.114e-01, 5.253e-01, 6.707e-01, 8.564e-01, 1.093e+00,
1.396e+00, 1.782e+00, 2.276e+00, 2.906e+00, 3.710e+00,
4.737e+00, 6.048e+00, 7.722e+00, 9.860e+00, 1.259e+01};
const double sF_val[50] = {9.226e-02, 1.001e-01, 1.085e-01, 1.177e-01, 1.276e-01,
1.384e-01, 1.500e-01, 1.626e-01, 1.763e-01, 1.910e-01,
2.070e-01, 2.242e-01, 2.429e-01, 2.630e-01, 2.846e-01,
3.079e-01, 3.330e-01, 3.598e-01, 3.886e-01, 4.193e-01,
4.521e-01, 4.868e-01, 5.234e-01, 5.619e-01, 6.019e-01,
6.434e-01, 6.856e-01, 7.281e-01, 7.700e-01, 8.101e-01,
8.469e-01, 8.784e-01, 9.025e-01, 9.161e-01, 9.161e-01,
8.990e-01, 8.614e-01, 8.009e-01, 7.166e-01, 6.104e-01,
4.882e-01, 3.602e-01, 2.397e-01, 1.396e-01, 6.855e-02,
2.704e-02, 8.056e-03, 1.675e-03, 2.198e-04, 1.600e-05};
double synchF_s(double x, gsl_interp_accel* sFacc, gsl_spline* sFsp)
{
if (x < 1e-4){
return 4.*M_PI / sqrt(3) / GAMMAF(1/3.) * pow(x*0.5, 1/3.);
} else if (x < 10.){
return gsl_spline_eval (sFsp, x, sFacc);
} else {
return sqrt(M_PI*0.5) * exp(-x) * sqrt(x);
}
}
int synchF(double *res, int sz, double *x)
{
gsl_interp_accel *acc = gsl_interp_accel_alloc ();
gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, 50);
gsl_spline_init(spline, &sF_x[0], &sF_val[0], 50);
int i;
for (i=0; i<sz; i++)
res[i] = synchF_s(x[i], acc, spline);
gsl_spline_free (spline);
gsl_interp_accel_free (acc);
return 0;
}
/*****************************************************************************/
// Brute F(x) calc
double b_synchF_integrand(double x, void* params){
gsl_sf_result eval;
gsl_error_handler_t *old_error_handler=gsl_set_error_handler_off (); // turn off the error handler
int code = gsl_sf_bessel_Knu_e(5./3, x, &eval); // compute the density, see gsl/gsl_errno.h for the error code
gsl_set_error_handler(old_error_handler); //reset the error handler
return (code==GSL_SUCCESS ? eval.val : 0.0);
}
double b_synchF_s(double x, gsl_integration_workspace* w_integ){
double epsabs=0;
double epsrel=1e-3;
double result;
double err;
gsl_function F;
F.function = &b_synchF_integrand;
F.params = NULL;
if (x < 1e-4){
return 4.*M_PI / sqrt(3) / GAMMAF(1/3.) * pow(x*0.5, 1/3.);
} else if (x > 10.){
return sqrt(M_PI*0.5) * exp(-x) * sqrt(x);
} else {
gsl_integration_qagiu(&F, x, epsabs, epsrel, 1000, w_integ, &result, &err);
return result;
}
}
int b_synchF(double *res, int sz, double *x){
gsl_integration_workspace* w_integ = gsl_integration_workspace_alloc(1000);
int i;
for (i=0; i<sz; i++)
res[i] = x[i]*b_synchF_s(x[i], w_integ);
gsl_integration_workspace_free(w_integ);
return 0;
}
/*****************************************************************************/
double inline get_nu_B(double B)
{
return e*B/(2*M_PI*M_e*c);
}
/*****************************************************************************/
// {j,a}_nu_brute
int j_nu_brute(double *res, int sz, double *nu, Source* source_t){
double B = source_t->B;
//If incang == -1, use angle averaged factor instead of sin_theta
double sin_theta = (source_t->incang == -1) ? M_PI/4. : sin(source_t->incang);
double P_el_factor = sqrt(3.0)*e*e*e*B/M_e/c/c*sin_theta;
double P_dist_factor = 1./4./M_PI;
int len_gamma = (log10(source_t->gamma_max)-log10(source_t->gamma_min))*source_t->gamma_steps;
double dgam = (log10(source_t->gamma_max)-log10(source_t->gamma_min))/(len_gamma-1);
double* gamma = (double*) malloc(len_gamma*sizeof(double));
double* e_dist = (double*) malloc(len_gamma*sizeof(double));
double* j_nu_int;
double* nu_over_nu_crit;
double* sFs;
int i,j;
for (j=0; j<len_gamma; j++){
gamma[j] = pow(10, j*dgam + log10(source_t->gamma_min));
}
eDist(e_dist, len_gamma, gamma, source_t);
#pragma omp parallel private(nu_over_nu_crit, sFs, j_nu_int, j)
{
j_nu_int = (double*) malloc(len_gamma*sizeof(double));
sFs = (double*) malloc(len_gamma*sizeof(double));
nu_over_nu_crit = (double*) malloc(len_gamma*sizeof(double));
#pragma omp for
for (i=0; i<sz; i++){
for (j=0; j<len_gamma; j++){
nu_over_nu_crit[j] = nu[i]/((3/2.)*get_nu_B(B)*POW2(gamma[j])*sin_theta);
}
synchF(sFs, len_gamma, nu_over_nu_crit);
for(j=0; j< len_gamma; j++){
j_nu_int[j] = P_dist_factor*P_el_factor*sFs[j]*e_dist[j];
}
res[i] = trapz(gamma, j_nu_int, len_gamma);
}
free(j_nu_int);
free(nu_over_nu_crit);
free(sFs);
}
free(gamma);
free(e_dist);
return 0;
}
int a_nu_brute(double *res, int sz, double *nu, Source* source_t){
double B = source_t->B;
//If incang == -1, use angle averaged factor instead of sin_theta
double sin_theta = (source_t->incang == -1) ? M_PI/4. : sin(source_t->incang);
double P_el_factor = sqrt(3.0)*e*e*e*B/M_e/c/c*sin_theta;
double a_dist_factor= - 1./8./M_PI/M_e;
int len_gamma = (log10(source_t->gamma_max)-log10(source_t->gamma_min))*source_t->gamma_steps;
double dgam = (log10(source_t->gamma_max)-log10(source_t->gamma_min))/(len_gamma-1);
double* gamma = (double*) malloc(len_gamma*sizeof(double));
double* e_dist = (double*) malloc(len_gamma*sizeof(double));
double* de_distdgam = (double*) malloc(len_gamma*sizeof(double));
double* a_nu_int;
double* nu_over_nu_crit;
double* sFs;
int i,j;
for (j=0; j<len_gamma; j++){
gamma[j] = pow(10, j*dgam + log10(source_t->gamma_min));
}
eDist(e_dist, len_gamma, gamma, source_t);
deDistdgam(de_distdgam, len_gamma, gamma, source_t);
#pragma omp parallel private(nu_over_nu_crit, sFs, a_nu_int, j)
{
a_nu_int = (double*) malloc(len_gamma*sizeof(double));
sFs = (double*) malloc(len_gamma*sizeof(double));
nu_over_nu_crit = (double*) malloc(len_gamma*sizeof(double));
#pragma omp for
for (i=0; i<sz; i++){
for (j=0; j<len_gamma; j++){
nu_over_nu_crit[j] = nu[i]/((3/2.)*get_nu_B(B)*POW2(gamma[j])*sin_theta);
}
synchF(sFs, len_gamma, nu_over_nu_crit);
for(j=0; j< len_gamma; j++){
a_nu_int[j] = (a_dist_factor/POW2(nu[i]))*(P_el_factor*sFs[j])*(de_distdgam[j]-2*e_dist[j]/gamma[j]);
}
res[i] = trapz(gamma, a_nu_int, len_gamma);
}
free(a_nu_int);
free(nu_over_nu_crit);
free(sFs);
}
free(gamma);
free(e_dist);
free(de_distdgam);
return 0;
}
/*****************************************************************************/
int j_nu_userdist(double *res, int sz, double *nu, int len_gamma, double *gamma, double* e_dist, Source* source_t){
double B = source_t->B;
//If incang == -1, use angle averaged factor instead of sin_theta
double sin_theta = (source_t->incang == -1) ? M_PI/4. : sin(source_t->incang);
double P_el_factor = sqrt(3.0)*e*e*e*B/M_e/c/c*sin_theta;
double P_dist_factor = 1./4./M_PI;
double* j_nu_int;
double* nu_over_nu_crit;
double* sFs;
int i,j;
#pragma omp parallel private(j_nu_int, nu_over_nu_crit, sFs, j)
{
j_nu_int = (double*) malloc(len_gamma*sizeof(double));
sFs = (double*) malloc(len_gamma*sizeof(double));
nu_over_nu_crit = (double*) malloc(len_gamma*sizeof(double));
#pragma omp for
for (i=0; i<sz; i++){
for (j=0; j<len_gamma; j++){
nu_over_nu_crit[j] = nu[i]/((3/2.)*get_nu_B(B)*POW2(gamma[j])*sin_theta);
}
synchF(sFs, len_gamma, nu_over_nu_crit);
for(j=0; j< len_gamma; j++){
j_nu_int[j] = P_dist_factor*P_el_factor*sFs[j]*e_dist[j];
}
res[i] = trapz(gamma, j_nu_int, len_gamma);
}
free(j_nu_int);
free(nu_over_nu_crit);
free(sFs);
}
return 0;
}
int a_nu_userdist(double *res, int sz, double *nu, int len_gamma, double *gamma, double *e_dist, Source* source_t){
double B = source_t->B;
//If incang == -1, use angle averaged factor instead of sin_theta
double sin_theta = (source_t->incang == -1) ? M_PI/4. : sin(source_t->incang);
double P_el_factor = sqrt(3.0)*e*e*e*B/M_e/c/c*sin_theta;
double a_dist_factor= - 1./8./M_PI/M_e;
double* de_distdgam = (double*) malloc(len_gamma*sizeof(double));
double* a_nu_int;
double* nu_over_nu_crit;
double* sFs;
int i,j;
vec_deriv_num(de_distdgam, gamma, e_dist, len_gamma);
#pragma omp parallel private(nu_over_nu_crit, sFs, a_nu_int, j)
{
a_nu_int = (double*) malloc(len_gamma*sizeof(double));
sFs = (double*) malloc(len_gamma*sizeof(double));
nu_over_nu_crit = (double*) malloc(len_gamma*sizeof(double));
#pragma omp for
for (i=0; i<sz; i++){
for (j=0; j<len_gamma; j++){
nu_over_nu_crit[j] = nu[i]/((3/2.)*get_nu_B(B)*POW2(gamma[j])*sin_theta);
}
synchF(sFs, len_gamma, nu_over_nu_crit);
for(j=0; j< len_gamma; j++){
a_nu_int[j] = (a_dist_factor/POW2(nu[i]))*(P_el_factor*sFs[j])*(de_distdgam[j]-2*e_dist[j]/gamma[j]);
}
res[i] = trapz(gamma, a_nu_int, len_gamma);
}
free(a_nu_int);
free(nu_over_nu_crit);
free(sFs);
}
free(de_distdgam);
return 0;
}
/*****************************************************************************/
|
parallel_for_omp.c | /* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
* See COPYRIGHT in top-level directory.
*/
/* Pragma omp parallel for directive evaluation
* Output: avg time
*/
#include <assert.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define NUM_ELEMS 5017600 /* 2GB */
#define EXT_LOOP_ELEM 2 /* 2GB */
#define IN_LOOP_ELEM 2 /* 2GB */
#define IN_LOOP_TH 1 /* 2GB */
#define NUM_REPS 1
/* Vector initialization */
void init(float *v, int n)
{
int i = 0;
for (i = 0; i < n; i++) {
v[i] = i + 100.0f;
}
}
/* Called after each test to be sure that the compiler does
not avoid to execute the test */
void check(float *v, int n)
{
int i = 0;
for (i = 0; i < n; i++) {
if (v[i] != (i + 100.0f) * 0.9f) {
printf("v[%d]<=0.0f\n", i);
}
}
}
int main(int argc, char *argv[])
{
int i, r, nthreads;
double *time, avg_time = 0.0;
float *v;
#pragma omp parallel
{
#pragma omp master
{
nthreads = omp_get_num_threads();
}
}
int n = (argc > 1) ? atoi(argv[1]) : NUM_ELEMS;
int rep = (argc > 2) ? atoi(argv[2]) : 1;
time = (double *)malloc(sizeof(double) * rep);
v = (float *)malloc(sizeof(float) * n);
init(v, n);
for (r = 0; r < rep; r++) {
time[r] = omp_get_wtime();
#pragma omp parallel for
for (i = 0; i < n; i++) {
v[i] *= 0.9f;
}
time[r] = omp_get_wtime() - time[r];
avg_time += time[r];
}
avg_time /= rep;
check(v, n);
printf("%d %d %f\n", nthreads, n, avg_time);
free(time);
free(v);
return EXIT_SUCCESS;
}
|
GB_binop__plus_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 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__plus_int8
// A.*B function (eWiseMult): GB_AemultB__plus_int8
// A*D function (colscale): GB_AxD__plus_int8
// D*A function (rowscale): GB_DxB__plus_int8
// C+=B function (dense accum): GB_Cdense_accumB__plus_int8
// C+=b function (dense accum): GB_Cdense_accumb__plus_int8
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__plus_int8
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__plus_int8
// C=scalar+B GB_bind1st__plus_int8
// C=scalar+B' GB_bind1st_tran__plus_int8
// C=A+scalar GB_bind2nd__plus_int8
// C=A'+scalar GB_bind2nd_tran__plus_int8
// C type: int8_t
// A type: int8_t
// B,b type: int8_t
// BinaryOp: cij = (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) \
int8_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
int8_t bij = Bx [pB]
// 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) \
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_PLUS || GxB_NO_INT8 || GxB_NO_PLUS_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__plus_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__plus_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__plus_int8
(
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__plus_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__plus_int8
(
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
int8_t *GB_RESTRICT Cx = (int8_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__plus_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 *GB_RESTRICT Cx = (int8_t *) 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__plus_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 *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__plus_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 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__plus_int8
(
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
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 < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
int8_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__plus_int8
(
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 ;
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 = 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) \
{ \
int8_t aij = Ax [pA] ; \
Cx [pC] = (x + aij) ; \
}
GrB_Info GB_bind1st_tran__plus_int8
(
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 \
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 = Ax [pA] ; \
Cx [pC] = (aij + y) ; \
}
GrB_Info GB_bind2nd_tran__plus_int8
(
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
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
segment.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS EEEEE GGGG M M EEEEE N N TTTTT %
% SS E G MM MM E NN N T %
% SSS EEE G GGG M M M EEE N N N T %
% SS E G G M M E N NN T %
% SSSSS EEEEE GGGG M M EEEEE N N T %
% %
% %
% MagickCore Methods to Segment an Image with Thresholding Fuzzy c-Means %
% %
% Software Design %
% Cristy %
% April 1993 %
% %
% %
% 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Segment segments an image by analyzing the histograms of the color
% components and identifying units that are homogeneous with the fuzzy
% c-means technique. The scale-space filter analyzes the histograms of
% the three color components of the image and identifies a set of
% classes. The extents of each class is used to coarsely segment the
% image with thresholding. The color associated with each class is
% determined by the mean color of all pixels within the extents of a
% particular class. Finally, any unclassified pixels are assigned to
% the closest class with the fuzzy c-means technique.
%
% The fuzzy c-Means algorithm can be summarized as follows:
%
% o Build a histogram, one for each color component of the image.
%
% o For each histogram, successively apply the scale-space filter and
% build an interval tree of zero crossings in the second derivative
% at each scale. Analyze this scale-space ''fingerprint'' to
% determine which peaks and valleys in the histogram are most
% predominant.
%
% o The fingerprint defines intervals on the axis of the histogram.
% Each interval contains either a minima or a maxima in the original
% signal. If each color component lies within the maxima interval,
% that pixel is considered ''classified'' and is assigned an unique
% class number.
%
% o Any pixel that fails to be classified in the above thresholding
% pass is classified using the fuzzy c-Means technique. It is
% assigned to one of the classes discovered in the histogram analysis
% phase.
%
% The fuzzy c-Means technique attempts to cluster a pixel by finding
% the local minima of the generalized within group sum of squared error
% objective function. A pixel is assigned to the closest class of
% which the fuzzy membership has a maximum value.
%
% Segment is strongly based on software written by Andy Gallo,
% University of Delaware.
%
% The following reference was used in creating this program:
%
% Young Won Lim, Sang Uk Lee, "On The Color Image Segmentation
% Algorithm Based on the Thresholding and the Fuzzy c-Means
% Techniques", Pattern Recognition, Volume 23, Number 9, pages
% 935-952, 1990.
%
%
*/
#include "MagickCore/studio.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
/*
Define declarations.
*/
#define MaxDimension 3
#define DeltaTau 0.5f
#if defined(FastClassify)
#define WeightingExponent 2.0
#define SegmentPower(ratio) (ratio)
#else
#define WeightingExponent 2.5
#define SegmentPower(ratio) pow(ratio,(double) (1.0/(weighting_exponent-1.0)));
#endif
#define Tau 5.2f
/*
Typedef declarations.
*/
typedef struct _ExtentPacket
{
double
center;
ssize_t
index,
left,
right;
} ExtentPacket;
typedef struct _Cluster
{
struct _Cluster
*next;
ExtentPacket
red,
green,
blue;
ssize_t
count,
id;
} Cluster;
typedef struct _IntervalTree
{
double
tau;
ssize_t
left,
right;
double
mean_stability,
stability;
struct _IntervalTree
*sibling,
*child;
} IntervalTree;
typedef struct _ZeroCrossing
{
double
tau,
histogram[256];
short
crossings[256];
} ZeroCrossing;
/*
Constant declarations.
*/
static const int
Blue = 2,
Green = 1,
Red = 0,
SafeMargin = 3,
TreeLength = 600;
/*
Method prototypes.
*/
static double
OptimalTau(const ssize_t *,const double,const double,const double,
const double,short *);
static ssize_t
DefineRegion(const short *,ExtentPacket *);
static void
FreeNodes(IntervalTree *),
InitializeHistogram(const Image *,ssize_t **,ExceptionInfo *),
ScaleSpace(const ssize_t *,const double,double *),
ZeroCrossHistogram(double *,const double,short *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l a s s i f y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Classify() defines one or more classes. Each pixel is thresholded to
% determine which class it belongs to. If the class is not identified it is
% assigned to the closest class based on the fuzzy c-Means technique.
%
% The format of the Classify method is:
%
% MagickBooleanType Classify(Image *image,short **extrema,
% const double cluster_threshold,const double weighting_exponent,
% const MagickBooleanType verbose,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o extrema: Specifies a pointer to an array of integers. They
% represent the peaks and valleys of the histogram for each color
% component.
%
% o cluster_threshold: This double represents the minimum number of
% pixels contained in a hexahedra before it can be considered valid
% (expressed as a percentage).
%
% o weighting_exponent: Specifies the membership weighting exponent.
%
% o verbose: A value greater than zero prints detailed information about
% the identified classes.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType Classify(Image *image,short **extrema,
const double cluster_threshold,const double weighting_exponent,
const MagickBooleanType verbose,ExceptionInfo *exception)
{
#define SegmentImageTag "Segment/Image"
#define ThrowClassifyException(severity,tag,label) \
{\
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) \
{ \
next_cluster=cluster->next; \
cluster=(Cluster *) RelinquishMagickMemory(cluster); \
} \
if (squares != (double *) NULL) \
{ \
squares-=255; \
free_squares=squares; \
free_squares=(double *) RelinquishMagickMemory(free_squares); \
} \
ThrowBinaryException(severity,tag,label); \
}
CacheView
*image_view;
Cluster
*cluster,
*head,
*last_cluster,
*next_cluster;
double
*free_squares;
ExtentPacket
blue,
green,
red;
MagickOffsetType
progress;
MagickStatusType
status;
ssize_t
i;
double
*squares;
size_t
number_clusters;
ssize_t
count,
y;
/*
Form clusters.
*/
cluster=(Cluster *) NULL;
head=(Cluster *) NULL;
squares=(double *) NULL;
(void) memset(&red,0,sizeof(red));
(void) memset(&green,0,sizeof(green));
(void) memset(&blue,0,sizeof(blue));
while (DefineRegion(extrema[Red],&red) != 0)
{
green.index=0;
while (DefineRegion(extrema[Green],&green) != 0)
{
blue.index=0;
while (DefineRegion(extrema[Blue],&blue) != 0)
{
/*
Allocate a new class.
*/
if (head != (Cluster *) NULL)
{
cluster->next=(Cluster *) AcquireQuantumMemory(1,
sizeof(*cluster->next));
cluster=cluster->next;
}
else
{
cluster=(Cluster *) AcquireQuantumMemory(1,sizeof(*cluster));
head=cluster;
}
if (cluster == (Cluster *) NULL)
ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Initialize a new class.
*/
(void) memset(cluster,0,sizeof(*cluster));
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
}
}
}
if (head == (Cluster *) NULL)
{
/*
No classes were identified-- create one.
*/
cluster=(Cluster *) AcquireQuantumMemory(1,sizeof(*cluster));
if (cluster == (Cluster *) NULL)
ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Initialize a new class.
*/
(void) memset(cluster,0,sizeof(*cluster));
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
head=cluster;
}
/*
Count the pixels for each cluster.
*/
status=MagickTrue;
count=0;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*p;
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++)
{
PixelInfo
pixel;
pixel.red=(double) ScaleQuantumToChar(GetPixelRed(image,p));
pixel.green=(double) ScaleQuantumToChar(GetPixelGreen(image,p));
pixel.blue=(double) ScaleQuantumToChar(GetPixelBlue(image,p));
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
if ((pixel.red >= (double) (cluster->red.left-SafeMargin)) &&
(pixel.red <= (double) (cluster->red.right+SafeMargin)) &&
(pixel.green >= (double) (cluster->green.left-SafeMargin)) &&
(pixel.green <= (double) (cluster->green.right+SafeMargin)) &&
(pixel.blue >= (double) (cluster->blue.left-SafeMargin)) &&
(pixel.blue <= (double) (cluster->blue.right+SafeMargin)))
{
/*
Count this pixel.
*/
count++;
cluster->red.center+=pixel.red;
cluster->green.center+=pixel.green;
cluster->blue.center+=pixel.blue;
cluster->count++;
break;
}
p+=GetPixelChannels(image);
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
/*
Remove clusters that do not meet minimum cluster threshold.
*/
count=0;
last_cluster=head;
next_cluster=head;
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
if ((cluster->count > 0) &&
(cluster->count >= (count*cluster_threshold/100.0)))
{
/*
Initialize cluster.
*/
cluster->id=count;
cluster->red.center/=cluster->count;
cluster->green.center/=cluster->count;
cluster->blue.center/=cluster->count;
count++;
last_cluster=cluster;
continue;
}
/*
Delete cluster.
*/
if (cluster == head)
head=next_cluster;
else
last_cluster->next=next_cluster;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
number_clusters=(size_t) count;
if (verbose != MagickFalse)
{
/*
Print cluster statistics.
*/
(void) FormatLocaleFile(stdout,"Fuzzy C-means Statistics\n");
(void) FormatLocaleFile(stdout,"===================\n\n");
(void) FormatLocaleFile(stdout,"\tCluster Threshold = %g\n",(double)
cluster_threshold);
(void) FormatLocaleFile(stdout,"\tWeighting Exponent = %g\n",(double)
weighting_exponent);
(void) FormatLocaleFile(stdout,"\tTotal Number of Clusters = %.20g\n\n",
(double) number_clusters);
/*
Print the total number of points per cluster.
*/
(void) FormatLocaleFile(stdout,"\n\nNumber of Vectors Per Cluster\n");
(void) FormatLocaleFile(stdout,"=============================\n\n");
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
(void) FormatLocaleFile(stdout,"Cluster #%.20g = %.20g\n",(double)
cluster->id,(double) cluster->count);
/*
Print the cluster extents.
*/
(void) FormatLocaleFile(stdout,
"\n\n\nCluster Extents: (Vector Size: %d)\n",MaxDimension);
(void) FormatLocaleFile(stdout,"================");
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
(void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
cluster->id);
(void) FormatLocaleFile(stdout,
"%.20g-%.20g %.20g-%.20g %.20g-%.20g\n",(double)
cluster->red.left,(double) cluster->red.right,(double)
cluster->green.left,(double) cluster->green.right,(double)
cluster->blue.left,(double) cluster->blue.right);
}
/*
Print the cluster center values.
*/
(void) FormatLocaleFile(stdout,
"\n\n\nCluster Center Values: (Vector Size: %d)\n",MaxDimension);
(void) FormatLocaleFile(stdout,"=====================");
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
(void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
cluster->id);
(void) FormatLocaleFile(stdout,"%g %g %g\n",(double)
cluster->red.center,(double) cluster->green.center,(double)
cluster->blue.center);
}
(void) FormatLocaleFile(stdout,"\n");
}
if (number_clusters > 256)
ThrowClassifyException(ImageError,"TooManyClusters",image->filename);
/*
Speed up distance calculations.
*/
squares=(double *) AcquireQuantumMemory(513UL,sizeof(*squares));
if (squares == (double *) NULL)
ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
squares+=255;
for (i=(-255); i <= 255; i++)
squares[i]=(double) i*(double) i;
/*
Allocate image colormap.
*/
if (AcquireImageColormap(image,number_clusters,exception) == MagickFalse)
ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
i=0;
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
image->colormap[i].red=(double) ScaleCharToQuantum((unsigned char)
(cluster->red.center+0.5));
image->colormap[i].green=(double) ScaleCharToQuantum((unsigned char)
(cluster->green.center+0.5));
image->colormap[i].blue=(double) ScaleCharToQuantum((unsigned char)
(cluster->blue.center+0.5));
i++;
}
/*
Do course grain classes.
*/
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++)
{
Cluster
*cluster;
const PixelInfo
*magick_restrict p;
ssize_t
x;
Quantum
*magick_restrict q;
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++)
{
PixelInfo
pixel;
SetPixelIndex(image,(Quantum) 0,q);
pixel.red=(double) ScaleQuantumToChar(GetPixelRed(image,q));
pixel.green=(double) ScaleQuantumToChar(GetPixelGreen(image,q));
pixel.blue=(double) ScaleQuantumToChar(GetPixelBlue(image,q));
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
if ((pixel.red >= (double) (cluster->red.left-SafeMargin)) &&
(pixel.red <= (double) (cluster->red.right+SafeMargin)) &&
(pixel.green >= (double) (cluster->green.left-SafeMargin)) &&
(pixel.green <= (double) (cluster->green.right+SafeMargin)) &&
(pixel.blue >= (double) (cluster->blue.left-SafeMargin)) &&
(pixel.blue <= (double) (cluster->blue.right+SafeMargin)))
{
/*
Classify this pixel.
*/
SetPixelIndex(image,(Quantum) cluster->id,q);
break;
}
}
if (cluster == (Cluster *) NULL)
{
double
distance_squared,
local_minima,
numerator,
ratio,
sum;
ssize_t
j,
k;
/*
Compute fuzzy membership.
*/
local_minima=0.0;
for (j=0; j < (ssize_t) image->colors; j++)
{
sum=0.0;
p=image->colormap+j;
distance_squared=
squares[(ssize_t) (pixel.red-ScaleQuantumToChar(p->red))]+
squares[(ssize_t) (pixel.green-ScaleQuantumToChar(p->green))]+
squares[(ssize_t) (pixel.blue-ScaleQuantumToChar(p->blue))];
numerator=distance_squared;
for (k=0; k < (ssize_t) image->colors; k++)
{
p=image->colormap+k;
distance_squared=
squares[(ssize_t) (pixel.red-ScaleQuantumToChar(p->red))]+
squares[(ssize_t) (pixel.green-ScaleQuantumToChar(p->green))]+
squares[(ssize_t) (pixel.blue-ScaleQuantumToChar(p->blue))];
ratio=numerator/distance_squared;
sum+=SegmentPower(ratio);
}
if ((sum != 0.0) && ((1.0/sum) > local_minima))
{
/*
Classify this pixel.
*/
local_minima=1.0/sum;
SetPixelIndex(image,(Quantum) j,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,SegmentImageTag,progress,2*image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
status&=SyncImage(image,exception);
/*
Relinquish resources.
*/
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
squares-=255;
free_squares=squares;
free_squares=(double *) RelinquishMagickMemory(free_squares);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n s o l i d a t e C r o s s i n g s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConsolidateCrossings() guarantees that an even number of zero crossings
% always lie between two crossings.
%
% The format of the ConsolidateCrossings method is:
%
% ConsolidateCrossings(ZeroCrossing *zero_crossing,
% const size_t number_crossings)
%
% A description of each parameter follows.
%
% o zero_crossing: Specifies an array of structures of type ZeroCrossing.
%
% o number_crossings: This size_t specifies the number of elements
% in the zero_crossing array.
%
*/
static void ConsolidateCrossings(ZeroCrossing *zero_crossing,
const size_t number_crossings)
{
ssize_t
i,
j,
k,
l;
ssize_t
center,
correct,
count,
left,
right;
/*
Consolidate zero crossings.
*/
for (i=(ssize_t) number_crossings-1; i >= 0; i--)
for (j=0; j <= 255; j++)
{
if (zero_crossing[i].crossings[j] == 0)
continue;
/*
Find the entry that is closest to j and still preserves the
property that there are an even number of crossings between
intervals.
*/
for (k=j-1; k > 0; k--)
if (zero_crossing[i+1].crossings[k] != 0)
break;
left=MagickMax(k,0);
center=j;
for (k=j+1; k < 255; k++)
if (zero_crossing[i+1].crossings[k] != 0)
break;
right=MagickMin(k,255);
/*
K is the zero crossing just left of j.
*/
for (k=j-1; k > 0; k--)
if (zero_crossing[i].crossings[k] != 0)
break;
if (k < 0)
k=0;
/*
Check center for an even number of crossings between k and j.
*/
correct=(-1);
if (zero_crossing[i+1].crossings[j] != 0)
{
count=0;
for (l=k+1; l < center; l++)
if (zero_crossing[i+1].crossings[l] != 0)
count++;
if (((count % 2) == 0) && (center != k))
correct=center;
}
/*
Check left for an even number of crossings between k and j.
*/
if (correct == -1)
{
count=0;
for (l=k+1; l < left; l++)
if (zero_crossing[i+1].crossings[l] != 0)
count++;
if (((count % 2) == 0) && (left != k))
correct=left;
}
/*
Check right for an even number of crossings between k and j.
*/
if (correct == -1)
{
count=0;
for (l=k+1; l < right; l++)
if (zero_crossing[i+1].crossings[l] != 0)
count++;
if (((count % 2) == 0) && (right != k))
correct=right;
}
l=(ssize_t) zero_crossing[i].crossings[j];
zero_crossing[i].crossings[j]=0;
if (correct != -1)
zero_crossing[i].crossings[correct]=(short) l;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e f i n e R e g i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefineRegion() defines the left and right boundaries of a peak region.
%
% The format of the DefineRegion method is:
%
% ssize_t DefineRegion(const short *extrema,ExtentPacket *extents)
%
% A description of each parameter follows.
%
% o extrema: Specifies a pointer to an array of integers. They
% represent the peaks and valleys of the histogram for each color
% component.
%
% o extents: This pointer to an ExtentPacket represent the extends
% of a particular peak or valley of a color component.
%
*/
static ssize_t DefineRegion(const short *extrema,ExtentPacket *extents)
{
/*
Initialize to default values.
*/
extents->left=0;
extents->center=0.0;
extents->right=255;
/*
Find the left side (maxima).
*/
for ( ; extents->index <= 255; extents->index++)
if (extrema[extents->index] > 0)
break;
if (extents->index > 255)
return(MagickFalse); /* no left side - no region exists */
extents->left=extents->index;
/*
Find the right side (minima).
*/
for ( ; extents->index <= 255; extents->index++)
if (extrema[extents->index] < 0)
break;
extents->right=extents->index-1;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e r i v a t i v e H i s t o g r a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DerivativeHistogram() determines the derivative of the histogram using
% central differencing.
%
% The format of the DerivativeHistogram method is:
%
% DerivativeHistogram(const double *histogram,
% double *derivative)
%
% A description of each parameter follows.
%
% o histogram: Specifies an array of doubles representing the number
% of pixels for each intensity of a particular color component.
%
% o derivative: This array of doubles is initialized by
% DerivativeHistogram to the derivative of the histogram using central
% differencing.
%
*/
static void DerivativeHistogram(const double *histogram,
double *derivative)
{
ssize_t
i,
n;
/*
Compute endpoints using second order polynomial interpolation.
*/
n=255;
derivative[0]=(-1.5*histogram[0]+2.0*histogram[1]-0.5*histogram[2]);
derivative[n]=(0.5*histogram[n-2]-2.0*histogram[n-1]+1.5*histogram[n]);
/*
Compute derivative using central differencing.
*/
for (i=1; i < n; i++)
derivative[i]=(histogram[i+1]-histogram[i-1])/2.0;
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e D y n a m i c T h r e s h o l d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageDynamicThreshold() returns the dynamic threshold for an image.
%
% The format of the GetImageDynamicThreshold method is:
%
% MagickBooleanType GetImageDynamicThreshold(const Image *image,
% const double cluster_threshold,const double smooth_threshold,
% PixelInfo *pixel,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cluster_threshold: This double represents the minimum number of
% pixels contained in a hexahedra before it can be considered valid
% (expressed as a percentage).
%
% o smooth_threshold: the smoothing threshold eliminates noise in the second
% derivative of the histogram. As the value is increased, you can expect a
% smoother second derivative.
%
% o pixel: return the dynamic threshold here.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageDynamicThreshold(const Image *image,
const double cluster_threshold,const double smooth_threshold,
PixelInfo *pixel,ExceptionInfo *exception)
{
Cluster
*background,
*cluster,
*object,
*head,
*last_cluster,
*next_cluster;
ExtentPacket
blue,
green,
red;
MagickBooleanType
proceed;
double
threshold;
const Quantum
*p;
ssize_t
i,
x;
short
*extrema[MaxDimension];
ssize_t
count,
*histogram[MaxDimension],
y;
/*
Allocate histogram and extrema.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
GetPixelInfo(image,pixel);
for (i=0; i < MaxDimension; i++)
{
histogram[i]=(ssize_t *) AcquireQuantumMemory(256UL,sizeof(**histogram));
extrema[i]=(short *) AcquireQuantumMemory(256UL,sizeof(**histogram));
if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL))
{
for (i-- ; i >= 0; i--)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
}
/*
Initialize histogram.
*/
InitializeHistogram(image,histogram,exception);
(void) OptimalTau(histogram[Red],Tau,0.2f,DeltaTau,
(smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Red]);
(void) OptimalTau(histogram[Green],Tau,0.2f,DeltaTau,
(smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Green]);
(void) OptimalTau(histogram[Blue],Tau,0.2f,DeltaTau,
(smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Blue]);
/*
Form clusters.
*/
cluster=(Cluster *) NULL;
head=(Cluster *) NULL;
(void) memset(&red,0,sizeof(red));
(void) memset(&green,0,sizeof(green));
(void) memset(&blue,0,sizeof(blue));
while (DefineRegion(extrema[Red],&red) != 0)
{
green.index=0;
while (DefineRegion(extrema[Green],&green) != 0)
{
blue.index=0;
while (DefineRegion(extrema[Blue],&blue) != 0)
{
/*
Allocate a new class.
*/
if (head != (Cluster *) NULL)
{
cluster->next=(Cluster *) AcquireQuantumMemory(1,
sizeof(*cluster->next));
cluster=cluster->next;
}
else
{
cluster=(Cluster *) AcquireQuantumMemory(1,sizeof(*cluster));
head=cluster;
}
if (cluster == (Cluster *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
return(MagickFalse);
}
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
}
}
}
if (head == (Cluster *) NULL)
{
/*
No classes were identified-- create one.
*/
cluster=(Cluster *) AcquireQuantumMemory(1,sizeof(*cluster));
if (cluster == (Cluster *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
head=cluster;
}
/*
Count the pixels for each cluster.
*/
count=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
PixelInfo
pixel;
pixel.red=(double) ScaleQuantumToChar(GetPixelRed(image,p));
pixel.green=(double) ScaleQuantumToChar(GetPixelGreen(image,p));
pixel.blue=(double) ScaleQuantumToChar(GetPixelBlue(image,p));
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
if ((pixel.red >= (double) (cluster->red.left-SafeMargin)) &&
(pixel.red <= (double) (cluster->red.right+SafeMargin)) &&
(pixel.green >= (double) (cluster->green.left-SafeMargin)) &&
(pixel.green <= (double) (cluster->green.right+SafeMargin)) &&
(pixel.blue >= (double) (cluster->blue.left-SafeMargin)) &&
(pixel.blue <= (double) (cluster->blue.right+SafeMargin)))
{
/*
Count this pixel.
*/
count++;
cluster->red.center+=pixel.red;
cluster->green.center+=pixel.green;
cluster->blue.center+=pixel.blue;
cluster->count++;
break;
}
p+=GetPixelChannels(image);
}
proceed=SetImageProgress(image,SegmentImageTag,(MagickOffsetType) y,
2*image->rows);
if (proceed == MagickFalse)
break;
}
/*
Remove clusters that do not meet minimum cluster threshold.
*/
count=0;
last_cluster=head;
next_cluster=head;
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
if ((cluster->count > 0) &&
(cluster->count >= (count*cluster_threshold/100.0)))
{
/*
Initialize cluster.
*/
cluster->id=count;
cluster->red.center/=cluster->count;
cluster->green.center/=cluster->count;
cluster->blue.center/=cluster->count;
count++;
last_cluster=cluster;
continue;
}
/*
Delete cluster.
*/
if (cluster == head)
head=next_cluster;
else
last_cluster->next=next_cluster;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
object=head;
background=head;
if (count > 1)
{
object=head->next;
for (cluster=object; cluster->next != (Cluster *) NULL; )
{
if (cluster->count < object->count)
object=cluster;
cluster=cluster->next;
}
background=head->next;
for (cluster=background; cluster->next != (Cluster *) NULL; )
{
if (cluster->count > background->count)
background=cluster;
cluster=cluster->next;
}
}
if (background != (Cluster *) NULL)
{
threshold=(background->red.center+object->red.center)/2.0;
pixel->red=(double) ScaleCharToQuantum((unsigned char)
(threshold+0.5));
threshold=(background->green.center+object->green.center)/2.0;
pixel->green=(double) ScaleCharToQuantum((unsigned char)
(threshold+0.5));
threshold=(background->blue.center+object->blue.center)/2.0;
pixel->blue=(double) ScaleCharToQuantum((unsigned char)
(threshold+0.5));
}
/*
Relinquish resources.
*/
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
for (i=0; i < MaxDimension; i++)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I n i t i a l i z e H i s t o g r a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InitializeHistogram() computes the histogram for an image.
%
% The format of the InitializeHistogram method is:
%
% InitializeHistogram(const Image *image,ssize_t **histogram)
%
% A description of each parameter follows.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
% o histogram: Specifies an array of integers representing the number
% of pixels for each intensity of a particular color component.
%
*/
static void InitializeHistogram(const Image *image,ssize_t **histogram,
ExceptionInfo *exception)
{
const Quantum
*p;
ssize_t
i,
x;
ssize_t
y;
/*
Initialize histogram.
*/
for (i=0; i <= 255; i++)
{
histogram[Red][i]=0;
histogram[Green][i]=0;
histogram[Blue][i]=0;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
histogram[Red][(ssize_t) ScaleQuantumToChar(GetPixelRed(image,p))]++;
histogram[Green][(ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p))]++;
histogram[Blue][(ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p))]++;
p+=GetPixelChannels(image);
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I n i t i a l i z e I n t e r v a l T r e e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InitializeIntervalTree() initializes an interval tree from the lists of
% zero crossings.
%
% The format of the InitializeIntervalTree method is:
%
% InitializeIntervalTree(IntervalTree **list,ssize_t *number_nodes,
% IntervalTree *node)
%
% A description of each parameter follows.
%
% o zero_crossing: Specifies an array of structures of type ZeroCrossing.
%
% o number_crossings: This size_t specifies the number of elements
% in the zero_crossing array.
%
*/
static void InitializeList(IntervalTree **list,ssize_t *number_nodes,
IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
if (node->child == (IntervalTree *) NULL)
list[(*number_nodes)++]=node;
InitializeList(list,number_nodes,node->sibling);
InitializeList(list,number_nodes,node->child);
}
static void MeanStability(IntervalTree *node)
{
IntervalTree
*child;
if (node == (IntervalTree *) NULL)
return;
node->mean_stability=0.0;
child=node->child;
if (child != (IntervalTree *) NULL)
{
ssize_t
count;
double
sum;
sum=0.0;
count=0;
for ( ; child != (IntervalTree *) NULL; child=child->sibling)
{
sum+=child->stability;
count++;
}
node->mean_stability=sum/(double) count;
}
MeanStability(node->sibling);
MeanStability(node->child);
}
static void Stability(IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
if (node->child == (IntervalTree *) NULL)
node->stability=0.0;
else
node->stability=node->tau-(node->child)->tau;
Stability(node->sibling);
Stability(node->child);
}
static IntervalTree *InitializeIntervalTree(const ZeroCrossing *zero_crossing,
const size_t number_crossings)
{
IntervalTree
*head,
**list,
*node,
*root;
ssize_t
i;
ssize_t
j,
k,
left,
number_nodes;
/*
Allocate interval tree.
*/
list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength,
sizeof(*list));
if (list == (IntervalTree **) NULL)
return((IntervalTree *) NULL);
/*
The root is the entire histogram.
*/
root=(IntervalTree *) AcquireCriticalMemory(sizeof(*root));
root->child=(IntervalTree *) NULL;
root->sibling=(IntervalTree *) NULL;
root->tau=0.0;
root->left=0;
root->right=255;
root->mean_stability=0.0;
root->stability=0.0;
(void) memset(list,0,TreeLength*sizeof(*list));
for (i=(-1); i < (ssize_t) number_crossings; i++)
{
/*
Initialize list with all nodes with no children.
*/
number_nodes=0;
InitializeList(list,&number_nodes,root);
/*
Split list.
*/
for (j=0; j < number_nodes; j++)
{
head=list[j];
left=head->left;
node=head;
for (k=head->left+1; k < head->right; k++)
{
if (zero_crossing[i+1].crossings[k] != 0)
{
if (node == head)
{
node->child=(IntervalTree *) AcquireQuantumMemory(1,
sizeof(*node->child));
node=node->child;
}
else
{
node->sibling=(IntervalTree *) AcquireQuantumMemory(1,
sizeof(*node->sibling));
node=node->sibling;
}
if (node == (IntervalTree *) NULL)
{
list=(IntervalTree **) RelinquishMagickMemory(list);
FreeNodes(root);
return((IntervalTree *) NULL);
}
node->tau=zero_crossing[i+1].tau;
node->child=(IntervalTree *) NULL;
node->sibling=(IntervalTree *) NULL;
node->left=left;
node->right=k;
left=k;
}
}
if (left != head->left)
{
node->sibling=(IntervalTree *) AcquireQuantumMemory(1,
sizeof(*node->sibling));
node=node->sibling;
if (node == (IntervalTree *) NULL)
{
list=(IntervalTree **) RelinquishMagickMemory(list);
FreeNodes(root);
return((IntervalTree *) NULL);
}
node->tau=zero_crossing[i+1].tau;
node->child=(IntervalTree *) NULL;
node->sibling=(IntervalTree *) NULL;
node->left=left;
node->right=head->right;
}
}
}
/*
Determine the stability: difference between a nodes tau and its child.
*/
Stability(root->child);
MeanStability(root->child);
list=(IntervalTree **) RelinquishMagickMemory(list);
return(root);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ O p t i m a l T a u %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OptimalTau() finds the optimal tau for each band of the histogram.
%
% The format of the OptimalTau method is:
%
% double OptimalTau(const ssize_t *histogram,const double max_tau,
% const double min_tau,const double delta_tau,
% const double smooth_threshold,short *extrema)
%
% A description of each parameter follows.
%
% o histogram: Specifies an array of integers representing the number
% of pixels for each intensity of a particular color component.
%
% o extrema: Specifies a pointer to an array of integers. They
% represent the peaks and valleys of the histogram for each color
% component.
%
*/
static void ActiveNodes(IntervalTree **list,ssize_t *number_nodes,
IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
if (node->stability >= node->mean_stability)
{
list[(*number_nodes)++]=node;
ActiveNodes(list,number_nodes,node->sibling);
}
else
{
ActiveNodes(list,number_nodes,node->sibling);
ActiveNodes(list,number_nodes,node->child);
}
}
static void FreeNodes(IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
FreeNodes(node->sibling);
FreeNodes(node->child);
node=(IntervalTree *) RelinquishMagickMemory(node);
}
static double OptimalTau(const ssize_t *histogram,const double max_tau,
const double min_tau,const double delta_tau,const double smooth_threshold,
short *extrema)
{
double
average_tau,
*derivative,
*second_derivative,
tau,
value;
IntervalTree
**list,
*node,
*root;
MagickBooleanType
peak;
ssize_t
i,
x;
size_t
count,
number_crossings;
ssize_t
index,
j,
k,
number_nodes;
ZeroCrossing
*zero_crossing;
/*
Allocate interval tree.
*/
list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength,
sizeof(*list));
if (list == (IntervalTree **) NULL)
return(0.0);
/*
Allocate zero crossing list.
*/
count=(size_t) ((max_tau-min_tau)/delta_tau)+2;
zero_crossing=(ZeroCrossing *) AcquireQuantumMemory((size_t) count,
sizeof(*zero_crossing));
if (zero_crossing == (ZeroCrossing *) NULL)
{
list=(IntervalTree **) RelinquishMagickMemory(list);
return(0.0);
}
for (i=0; i < (ssize_t) count; i++)
zero_crossing[i].tau=(-1.0);
/*
Initialize zero crossing list.
*/
derivative=(double *) AcquireCriticalMemory(256*sizeof(*derivative));
second_derivative=(double *) AcquireCriticalMemory(256*
sizeof(*second_derivative));
i=0;
for (tau=max_tau; tau >= min_tau; tau-=delta_tau)
{
zero_crossing[i].tau=tau;
ScaleSpace(histogram,tau,zero_crossing[i].histogram);
DerivativeHistogram(zero_crossing[i].histogram,derivative);
DerivativeHistogram(derivative,second_derivative);
ZeroCrossHistogram(second_derivative,smooth_threshold,
zero_crossing[i].crossings);
i++;
}
/*
Add an entry for the original histogram.
*/
zero_crossing[i].tau=0.0;
for (j=0; j <= 255; j++)
zero_crossing[i].histogram[j]=(double) histogram[j];
DerivativeHistogram(zero_crossing[i].histogram,derivative);
DerivativeHistogram(derivative,second_derivative);
ZeroCrossHistogram(second_derivative,smooth_threshold,
zero_crossing[i].crossings);
number_crossings=(size_t) i;
derivative=(double *) RelinquishMagickMemory(derivative);
second_derivative=(double *) RelinquishMagickMemory(second_derivative);
/*
Ensure the scale-space fingerprints form lines in scale-space, not loops.
*/
ConsolidateCrossings(zero_crossing,number_crossings);
/*
Force endpoints to be included in the interval.
*/
for (i=0; i <= (ssize_t) number_crossings; i++)
{
for (j=0; j < 255; j++)
if (zero_crossing[i].crossings[j] != 0)
break;
zero_crossing[i].crossings[0]=(-zero_crossing[i].crossings[j]);
for (j=255; j > 0; j--)
if (zero_crossing[i].crossings[j] != 0)
break;
zero_crossing[i].crossings[255]=(-zero_crossing[i].crossings[j]);
}
/*
Initialize interval tree.
*/
root=InitializeIntervalTree(zero_crossing,number_crossings);
if (root == (IntervalTree *) NULL)
{
zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing);
list=(IntervalTree **) RelinquishMagickMemory(list);
return(0.0);
}
/*
Find active nodes: Stability is greater (or equal) to the mean stability of
its children.
*/
number_nodes=0;
ActiveNodes(list,&number_nodes,root->child);
/*
Initialize extrema.
*/
for (i=0; i <= 255; i++)
extrema[i]=0;
for (i=0; i < number_nodes; i++)
{
/*
Find this tau in zero crossings list.
*/
k=0;
node=list[i];
for (j=0; j <= (ssize_t) number_crossings; j++)
if (zero_crossing[j].tau == node->tau)
k=j;
/*
Find the value of the peak.
*/
peak=zero_crossing[k].crossings[node->right] == -1 ? MagickTrue :
MagickFalse;
index=node->left;
value=zero_crossing[k].histogram[index];
for (x=node->left; x <= node->right; x++)
{
if (peak != MagickFalse)
{
if (zero_crossing[k].histogram[x] > value)
{
value=zero_crossing[k].histogram[x];
index=x;
}
}
else
if (zero_crossing[k].histogram[x] < value)
{
value=zero_crossing[k].histogram[x];
index=x;
}
}
for (x=node->left; x <= node->right; x++)
{
if (index == 0)
index=256;
if (peak != MagickFalse)
extrema[x]=(short) index;
else
extrema[x]=(short) (-index);
}
}
/*
Determine the average tau.
*/
average_tau=0.0;
for (i=0; i < number_nodes; i++)
average_tau+=list[i]->tau;
average_tau*=PerceptibleReciprocal((double) number_nodes);
/*
Relinquish resources.
*/
FreeNodes(root);
zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing);
list=(IntervalTree **) RelinquishMagickMemory(list);
return(average_tau);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S c a l e S p a c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ScaleSpace() performs a scale-space filter on the 1D histogram.
%
% The format of the ScaleSpace method is:
%
% ScaleSpace(const ssize_t *histogram,const double tau,
% double *scale_histogram)
%
% A description of each parameter follows.
%
% o histogram: Specifies an array of doubles representing the number
% of pixels for each intensity of a particular color component.
%
*/
static void ScaleSpace(const ssize_t *histogram,const double tau,
double *scale_histogram)
{
double
alpha,
beta,
*gamma,
sum;
ssize_t
u,
x;
gamma=(double *) AcquireQuantumMemory(256,sizeof(*gamma));
if (gamma == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAllocateGammaMap");
alpha=PerceptibleReciprocal(tau*sqrt(2.0*MagickPI));
beta=(-1.0*PerceptibleReciprocal(2.0*tau*tau));
for (x=0; x <= 255; x++)
gamma[x]=0.0;
for (x=0; x <= 255; x++)
{
gamma[x]=exp((double) beta*x*x);
if (gamma[x] < MagickEpsilon)
break;
}
for (x=0; x <= 255; x++)
{
sum=0.0;
for (u=0; u <= 255; u++)
sum+=(double) histogram[u]*gamma[MagickAbsoluteValue(x-u)];
scale_histogram[x]=alpha*sum;
}
gamma=(double *) RelinquishMagickMemory(gamma);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e g m e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SegmentImage() segment an image by analyzing the histograms of the color
% components and identifying units that are homogeneous with the fuzzy
% C-means technique.
%
% The format of the SegmentImage method is:
%
% MagickBooleanType SegmentImage(Image *image,
% const ColorspaceType colorspace,const MagickBooleanType verbose,
% const double cluster_threshold,const double smooth_threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o colorspace: Indicate the colorspace.
%
% o verbose: Set to MagickTrue to print detailed information about the
% identified classes.
%
% o cluster_threshold: This represents the minimum number of pixels
% contained in a hexahedra before it can be considered valid (expressed
% as a percentage).
%
% o smooth_threshold: the smoothing threshold eliminates noise in the second
% derivative of the histogram. As the value is increased, you can expect a
% smoother second derivative.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SegmentImage(Image *image,
const ColorspaceType colorspace,const MagickBooleanType verbose,
const double cluster_threshold,const double smooth_threshold,
ExceptionInfo *exception)
{
ColorspaceType
previous_colorspace;
MagickBooleanType
status;
ssize_t
i;
short
*extrema[MaxDimension];
ssize_t
*histogram[MaxDimension];
/*
Allocate histogram and extrema.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
for (i=0; i < MaxDimension; i++)
{
histogram[i]=(ssize_t *) AcquireQuantumMemory(256,sizeof(**histogram));
extrema[i]=(short *) AcquireQuantumMemory(256,sizeof(**extrema));
if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL))
{
for (i-- ; i >= 0; i--)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename)
}
}
/*
Initialize histogram.
*/
previous_colorspace=image->colorspace;
(void) TransformImageColorspace(image,colorspace,exception);
InitializeHistogram(image,histogram,exception);
(void) OptimalTau(histogram[Red],Tau,0.2,DeltaTau,smooth_threshold == 0.0 ?
1.0 : smooth_threshold,extrema[Red]);
(void) OptimalTau(histogram[Green],Tau,0.2,DeltaTau,smooth_threshold == 0.0 ?
1.0 : smooth_threshold,extrema[Green]);
(void) OptimalTau(histogram[Blue],Tau,0.2,DeltaTau,smooth_threshold == 0.0 ?
1.0 : smooth_threshold,extrema[Blue]);
/*
Classify using the fuzzy c-Means technique.
*/
status=Classify(image,extrema,cluster_threshold,WeightingExponent,verbose,
exception);
(void) TransformImageColorspace(image,previous_colorspace,exception);
/*
Relinquish resources.
*/
for (i=0; i < MaxDimension; i++)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Z e r o C r o s s H i s t o g r a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ZeroCrossHistogram() find the zero crossings in a histogram and marks
% directions as: 1 is negative to positive; 0 is zero crossing; and -1
% is positive to negative.
%
% The format of the ZeroCrossHistogram method is:
%
% ZeroCrossHistogram(double *second_derivative,
% const double smooth_threshold,short *crossings)
%
% A description of each parameter follows.
%
% o second_derivative: Specifies an array of doubles representing the
% second derivative of the histogram of a particular color component.
%
% o crossings: This array of integers is initialized with
% -1, 0, or 1 representing the slope of the first derivative of the
% of a particular color component.
%
*/
static void ZeroCrossHistogram(double *second_derivative,
const double smooth_threshold,short *crossings)
{
ssize_t
i;
ssize_t
parity;
/*
Merge low numbers to zero to help prevent noise.
*/
for (i=0; i <= 255; i++)
if ((second_derivative[i] < smooth_threshold) &&
(second_derivative[i] >= -smooth_threshold))
second_derivative[i]=0.0;
/*
Mark zero crossings.
*/
parity=0;
for (i=0; i <= 255; i++)
{
crossings[i]=0;
if (second_derivative[i] < 0.0)
{
if (parity > 0)
crossings[i]=(-1);
parity=1;
}
else
if (second_derivative[i] > 0.0)
{
if (parity < 0)
crossings[i]=1;
parity=(-1);
}
}
}
|
pdf_fmt_plug.c | /* PDF cracker patch for JtR. Hacked together during Monsoon of 2012 by
* Dhiru Kholia <dhiru.kholia at gmail.com> .
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>
*
* Uses code from Sumatra PDF and MuPDF which are under GPL
*
* Edited by Shane Quigley 2013
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_pdf;
#elif FMT_REGISTERS_H
john_register_one(&fmt_pdf);
#else
#include <string.h>
#include "arch.h"
#include "params.h"
#include "common.h"
#include "formats.h"
#include "misc.h"
#include "md5.h"
#include "rc4.h"
#include "pdfcrack_md5.h"
#include "aes.h"
#include "sha2.h"
#include "loader.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 64
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "PDF"
#define FORMAT_NAME ""
#define FORMAT_TAG "$pdf$"
#define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1)
#define FORMAT_TAG_OLD "$pdf$Standard*"
#define FORMAT_TAG_OLD_LEN (sizeof(FORMAT_TAG_OLD)-1)
#define ALGORITHM_NAME "MD5 SHA2 RC4/AES 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1000
#define PLAINTEXT_LENGTH 32
#define BINARY_SIZE 0
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN 1
#define SALT_ALIGN sizeof(int)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#if defined (_OPENMP)
static int omp_t = 1;
#endif
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int *cracked;
static int any_cracked;
static size_t cracked_size;
static struct custom_salt {
int V;
int R;
int P;
char encrypt_metadata;
unsigned char u[127];
unsigned char o[127];
unsigned char ue[32];
unsigned char oe[32];
unsigned char id[32];
int length;
int length_id;
int length_u;
int length_o;
int length_ue;
int length_oe;
} *crypt_out;
static struct fmt_tests pdf_tests[] = {
{"$pdf$4*4*128*-1028*1*16*e03460febe17a048b0adc7f7631bcc56*32*3456205208ad52066d5604018d498a6400000000000000000000000000000000*32*6d598152b22f8fa8085b19a866dce1317f645788a065a74831588a739a579ac4", "openwall"},
{"$pdf$2*3*128*-4*1*16*34b1b6e593787af681a9b63fa8bf563b*32*289ece9b5ce451a5d7064693dab3badf101112131415161718191a1b1c1d1e1f*32*badad1e86442699427116d3e5d5271bc80a27814fc5e80f815efeef839354c5f", "test"},
{"$pdf$4*4*128*-1028*1*16*c015cff8dbf99345ac91c84a45667784*32*0231a4c9cae29b53892874e168cfae9600000000000000000000000000000000*32*137ad7063db5114a66ce1900d47e5cab9c5d7053487d92ac978f54db86eca393", "testpassword"},
{"$pdf$5*6*256*-1028*1*16*05e5abeb21ad2e47adac1c2b2c7b7a31*127*51d3a6a09a675503383e5bc0b53da77ec5d5ea1d1998fb94e00a02a1c2e49313c177905272a4e8e68b382254ec8ed74800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*127*dc38f01ef129aae2fca847396465ed518f9c7cf4f2c8cb4399a849d0fe9110227739ab88ddc9a6cf388ae11941270af500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*32*b8e137baf316e0789ffa73f888d26495c14d31f2cfff3799e339e2fa078649f5*32*835a9e07461992791914c3d62d37493e07d140937529ab43e26ac2a657152c3c", "testpassword"},
{"$pdf$5*5*256*-1028*1*16*762896ef582ca042a15f380c63ab9f2c*127*8713e2afdb65df1d3801f77a4c4da4905c49495e7103afc2deb06d9fba7949a565143288823871270d9d882075a75da600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*127*15d0b992974ff80529e4b616b8c4c79d787705b6c8a9e0f85446498ae2432e0027d8406b57f78b60b11341a0757d7c4a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*32*a7a0f3891b469ba7261ce04752dad9c6de0db9c4155c4180e721938a7d9666c7*32*2fa9a0c52badebae2c19dfa7b0005a9cfc909b92babbe7db66a794e96a9f91e3", "openwall"},
/* following are old-style hashes */
{"$pdf$Standard*badad1e86442699427116d3e5d5271bc80a27814fc5e80f815efeef839354c5f*289ece9b5ce451a5d7064693dab3badf101112131415161718191a1b1c1d1e1f*16*34b1b6e593787af681a9b63fa8bf563b*1*1*0*1*4*128*-4*3*2", "test"},
{"$pdf$Standard*9a1156c38ab8177598d1608df7d7e340ae639679bd66bc4cda9bc9a4eedeb170*1f300cd939dd5cf0920c787f12d16be22205e55a5bec5c9c6d563ab4fd0770d7*16*c015cff8dbf99345ac91c84a45667784*1*1*0*1*6*40*-4*2*1", "testpassword"},
{"$pdf$Standard*7303809eaf677bdb5ca64b9d8cb0ccdd47d09a7b28ad5aa522c62685c6d9e499*bf38d7a59daaf38365a338e1fc07976102f1dfd6bdb52072032f57920109b43a*16*c56bbc4145d25b468a873618cd71c2d3*1*1*0*1*6*40*-4*2*1", "test"},
{"$pdf$Standard*137ad7063db5114a66ce1900d47e5cab9c5d7053487d92ac978f54db86eca393*0231a4c9cae29b53892874e168cfae9600000000000000000000000000000000*16*c015cff8dbf99345ac91c84a45667784*1*1*0*1*6*128*-1028*3*2", "testpassword"},
{"$pdf$Standard*d83a8ab680f144dfb2ff2334c206a6060779e007701ab881767f961aecda7984*a5ed4de7e078cb75dfdcd63e8da7a25800000000000000000000000000000000*16*06a7f710cf8dfafbd394540d40984ae2*1*1*0*1*4*128*-1028*3*2", "July2099"},
{"$pdf$Standard*6a80a547b8b8b7636fcc5b322f1c63ce4b670c9b01f2aace09e48d85e1f19f83*e64eb62fc46be66e33571d50a29b464100000000000000000000000000000000*16*14a8c53ffa4a79b3ed9421ef15618420*1*1*0*1*4*128*-1028*3*2", "38r285a9"},
{"$pdf$Standard*2446dd5ed2e18b3ce1ac9b56733226018e3f5c2639051eb1c9b2b215b30bc820*fa3af175d761963c8449ee7015b7770800000000000000000000000000000000*16*12a4da1abe6b7a1ceb84610bad87236d*1*1*0*1*4*128*-1028*3*2", "WHATwhatWHERE?"},
{"$pdf$Standard*e600ecc20288ad8b0d64a929c6a83ee2517679aa0218beceea8b7986726a8cdb*38aca54678d67c003a8193381b0fa1cc101112131415161718191a1b1c1d1e1f*16*1521fbe61419fcad51878cc5d478d5ff*1*1*0*1*4*128*-3904*3*2", ""},
/* CMIYC 2013 "pro" hashes */
{"$pdf$4*4*128*-4*1*16*f7bc2744e1652cf61ca83cac8fccb535*32*f55cc5032f04b985c5aeacde5ec4270f0122456a91bae5134273a6db134c87c4*32*785d891cdcb5efa59893c78f37e7b75acef8924951039b4fa13f62d92bb3b660", "L4sV3g4z"},
{"$pdf$4*4*128*-4*1*16*ec8ea2af2977db1faa4a955904dc956f*32*fc413edb049720b1f8eac87a358faa740122456a91bae5134273a6db134c87c4*32*1ba7aed2f19c77ac6b5061230b62e80b48fc42918f92aef689ceb07d26204991", "ZZt0pr0x"},
{"$pdf$4*4*128*-4*1*16*56761d6da774d8d47387dccf1a84428c*32*640782cab5b7c8f6cf5eab82c38016540122456a91bae5134273a6db134c87c4*32*b5720d5f3d9675a280c6bb8050cbb169e039b578b2de4a42a40dc14765e064cf", "24Le`m0ns"},
{NULL}
};
static void init(struct fmt_main *self)
{
#if defined (_OPENMP)
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(sizeof(*saved_key), self->params.max_keys_per_crypt);
any_cracked = 0;
cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt;
cracked = mem_calloc(sizeof(*cracked), self->params.max_keys_per_crypt);
}
static void done(void)
{
MEM_FREE(cracked);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *keeptr;
char *p;
int res;
if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0)
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += FORMAT_TAG_LEN;
if ((p = strtokm(ctcopy, "*")) == NULL) /* V */
goto err;
if (!isdec(p)) goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* R */
goto err;
if (!isdec(p)) goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* length */
goto err;
if (!isdec(p)) goto err;
res = atoi(p);
if (res > 256)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* P */
goto err;
if (!isdec_negok(p)) goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* encrypt_metadata */
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* length_id */
goto err;
if (!isdec(p)) goto err;
res = atoi(p);
if (res > 32)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* id */
goto err;
if (strlen(p) != res * 2)
goto err;
if (!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* length_u */
goto err;
if (!isdec(p)) goto err;
res = atoi(p);
if (res > 127)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* u */
goto err;
if (strlen(p) != res * 2)
goto err;
if (!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* length_o */
goto err;
if (!isdec(p)) goto err;
res = atoi(p);
if (res > 127)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* o */
goto err;
if (strlen(p) != res * 2)
goto err;
if (!ishexlc(p))
goto err;
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
static int old_valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *ptr, *keeptr;
int res;
if (strncmp(ciphertext, FORMAT_TAG_OLD, FORMAT_TAG_OLD_LEN))
return 0;
if (!(ctcopy = strdup(ciphertext)))
return 0;
keeptr = ctcopy;
ctcopy += FORMAT_TAG_OLD_LEN;
if (!(ptr = strtokm(ctcopy, "*"))) /* o_string */
goto error;
if (!ishexlc(ptr))
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* u_string */
goto error;
if (!ishexlc(ptr))
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* fileIDLen */
goto error;
if (strncmp(ptr, "16", 2))
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* fileID */
goto error;
if (!ishexlc(ptr))
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* encryptMetaData */
goto error;
res = atoi(ptr);
if (res != 0 && res != 1)
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* work_with_user */
goto error;
res = atoi(ptr);
if (res != 0 && res != 1)
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* have_userpassword */
goto error;
res = atoi(ptr);
if (res != 0 && res != 1)
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* version_major */
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* version_minor */
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* length */
goto error;
res = atoi(ptr);
if (res < 0 || res > 256)
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* permissions */
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* revision */
goto error;
if (!(ptr = strtokm(NULL, "*"))) /* version */
goto error;
MEM_FREE(keeptr);
return 1;
error:
MEM_FREE(keeptr);
return 0;
}
char * convert_old_to_new(char ciphertext[])
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
char *out = mem_alloc_tiny(strlen(ctcopy), MEM_ALIGN_NONE);
const char *fields[14];
char *p;
int c = 0;
p = strtokm(ctcopy, "*");
for (c = 0; c < 14; c++) {
fields[c] = p;
p = strtokm(NULL, "*");
}
strcpy(out,FORMAT_TAG);
strcat(out,fields[13]);
strcat(out,"*");
strcat(out,fields[12]);
strcat(out,"*");
strcat(out,fields[10]);
strcat(out,"*");
strcat(out,fields[11]);
strcat(out,"*");
strcat(out,fields[5]);
strcat(out,"*");
strcat(out,fields[3]);
strcat(out,"*");
strcat(out,fields[4]);
strcat(out,"*32*");
strcat(out,fields[2]);
strcat(out,"*32*");
strcat(out,fields[1]);
MEM_FREE(keeptr);
return out;
}
static char *prepare(char *split_fields[10], struct fmt_main *self)
{
// if it is the old format
if (strncmp(split_fields[1], FORMAT_TAG_OLD, FORMAT_TAG_OLD_LEN) == 0){
if(old_valid(split_fields[1], self)) {
char * in_new_format = convert_old_to_new(split_fields[1]);
// following line segfaults!
// strcpy(split_fields[1], in_new_format);
return in_new_format;
}else{
//Return something invalid
return "";
}
}
return split_fields[1];
}
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
int i;
char *p;
static struct custom_salt cs;
memset(&cs, 0, sizeof(cs));
ctcopy += FORMAT_TAG_LEN; /* skip over "$pdf$" marker */
p = strtokm(ctcopy, "*");
cs.V = atoi(p);
p = strtokm(NULL, "*");
cs.R = atoi(p);
p = strtokm(NULL, "*");
cs.length = atoi(p);
p = strtokm(NULL, "*");
cs.P = atoi(p);
p = strtokm(NULL, "*");
cs.encrypt_metadata = atoi(p);
p = strtokm(NULL, "*");
cs.length_id = atoi(p);
p = strtokm(NULL, "*");
for (i = 0; i < cs.length_id; i++)
cs.id[i] =
atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
p = strtokm(NULL, "*");
cs.length_u = atoi(p);
p = strtokm(NULL, "*");
for (i = 0; i < cs.length_u; i++)
cs.u[i] =
atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
p = strtokm(NULL, "*");
cs.length_o = atoi(p);
p = strtokm(NULL, "*");
for (i = 0; i < cs.length_o; i++)
cs.o[i] =
atoi16[ARCH_INDEX(p[i * 2])] * 16 +
atoi16[ARCH_INDEX(p[i * 2 + 1])];
MEM_FREE(keeptr);
return (void *)&cs;
}
static void set_salt(void *salt)
{
crypt_out = (struct custom_salt *)salt;
}
static void pdf_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 const unsigned char padding[32] =
{
0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a
};
/* Compute an encryption key (PDF 1.7 algorithm 3.2) */
static void
pdf_compute_encryption_key(unsigned char *password, int pwlen, unsigned char *key)
{
unsigned char buf[32];
unsigned int p;
int n;
MD5_CTX md5;
n = crypt_out->length / 8;
/* Step 1 - copy and pad password string */
if (pwlen > 32)
pwlen = 32;
memcpy(buf, password, pwlen);
memcpy(buf + pwlen, padding, 32 - pwlen);
/* Step 2 - init md5 and pass value of step 1 */
MD5_Init(&md5);
MD5_Update(&md5, buf, 32);
/* Step 3 - pass O value */
MD5_Update(&md5, crypt_out->o, 32);
/* Step 4 - pass P value as unsigned int, low-order byte first */
p = (unsigned int) crypt_out->P;
buf[0] = (p) & 0xFF;
buf[1] = (p >> 8) & 0xFF;
buf[2] = (p >> 16) & 0xFF;
buf[3] = (p >> 24) & 0xFF;
MD5_Update(&md5, buf, 4);
/* Step 5 - pass first element of ID array */
MD5_Update(&md5, crypt_out->id, crypt_out->length_id);
/* Step 6 (revision 4 or greater) - if metadata is not encrypted pass 0xFFFFFFFF */
if (crypt_out->R >= 4)
{
if (!crypt_out->encrypt_metadata)
{
buf[0] = 0xFF;
buf[1] = 0xFF;
buf[2] = 0xFF;
buf[3] = 0xFF;
MD5_Update(&md5, buf, 4);
}
}
/* Step 7 - finish the hash */
MD5_Final(buf, &md5);
/* Step 8 (revision 3 or greater) - do some voodoo 50 times */
if (crypt_out->R >= 3)
{
/* for (i = 0; i < 50; i++)
{
MD5_Init(&md5);
MD5_Update(&md5, buf, n);
MD5_Final(buf, &md5);
} */
md5_50(buf);
}
/* Step 9 - the key is the first 'n' bytes of the result */
memcpy(key, buf, n);
}
/* Compute an encryption key (PDF 1.7 ExtensionLevel 3 algorithm 3.2a) */
static void
pdf_compute_encryption_key_r5(unsigned char *password, int pwlen, int ownerkey, unsigned char *validationkey)
{
unsigned char buffer[128 + 8 + 48];
SHA256_CTX sha256;
/* Step 2 - truncate UTF-8 password to 127 characters */
if (pwlen > 127)
pwlen = 127;
/* Step 3/4 - test password against owner/user key and compute encryption key */
memcpy(buffer, password, pwlen);
if (ownerkey)
{
memcpy(buffer + pwlen, crypt_out->o + 32, 8);
memcpy(buffer + pwlen + 8, crypt_out->u, 48);
}
else
memcpy(buffer + pwlen, crypt_out->u + 32, 8);
SHA256_Init(&sha256);
SHA256_Update(&sha256, buffer, pwlen + 8 + (ownerkey ? 48 : 0));
SHA256_Final(validationkey, &sha256);
}
/* SumatraPDF: support crypt version 5 revision 6 */
/*
* Compute an encryption key (PDF 1.7 ExtensionLevel 8 algorithm 3.2b)
* http://esec-lab.sogeti.com/post/The-undocumented-password-validation-algorithm-of-Adobe-Reader-X
*/
static void
pdf_compute_hardened_hash_r6(unsigned char *password, int pwlen, unsigned char salt[8],
unsigned char *ownerkey, unsigned char hash[32])
{
unsigned char data[(128 + 64 + 48) * 64];
unsigned char block[64];
int block_size = 32;
int data_len = 0;
int i, j, sum;
SHA256_CTX sha256;
SHA512_CTX sha384;
SHA512_CTX sha512;
AES_KEY aes;
/* Step 1: calculate initial data block */
SHA256_Init(&sha256);
SHA256_Update(&sha256, password, pwlen);
SHA256_Update(&sha256, salt, 8);
if (ownerkey)
SHA256_Update(&sha256, ownerkey, 48);
SHA256_Final(block, &sha256);
for (i = 0; i < 64 || i < data[data_len * 64 - 1] + 32; i++)
{
/* Step 2: repeat password and data block 64 times */
memcpy(data, password, pwlen);
memcpy(data + pwlen, block, block_size);
// ownerkey is always NULL
// memcpy(data + pwlen + block_size, ownerkey, ownerkey ? 48 : 0);
data_len = pwlen + block_size + (ownerkey ? 48 : 0);
for (j = 1; j < 64; j++)
memcpy(data + j * data_len, data, data_len);
/* Step 3: encrypt data using data block as key and iv */
AES_set_encrypt_key(block, 128, &aes);
// aes_crypt_cbc(&aes, AES_ENCRYPT, data_len * 64, block + 16, data, data);
AES_cbc_encrypt(data, data, data_len * 64, &aes, block + 16, AES_ENCRYPT);
/* Step 4: determine SHA-2 hash size for this round */
for (j = 0, sum = 0; j < 16; j++)
sum += data[j];
/* Step 5: calculate data block for next round */
block_size = 32 + (sum % 3) * 16;
switch (block_size)
{
case 32:
SHA256_Init(&sha256);
SHA256_Update(&sha256, data, data_len * 64);
SHA256_Final(block, &sha256);
break;
case 48:
SHA384_Init(&sha384);
SHA384_Update(&sha384, data, data_len * 64);
SHA384_Final(block, &sha384);
break;
case 64:
SHA512_Init(&sha512);
SHA512_Update(&sha512, data, data_len * 64);
SHA512_Final(block, &sha512);
break;
}
}
memset(data, 0, sizeof(data));
memcpy(hash, block, 32);
}
/* Computing the user password (PDF 1.7 algorithm 3.4 and 3.5) */
static void pdf_compute_user_password(unsigned char *password, unsigned char *output)
{
int pwlen = strlen((char*)password);
unsigned char key[128];
if (crypt_out->R == 2) {
RC4_KEY arc4;
int n;
n = crypt_out->length / 8;
pdf_compute_encryption_key(password, pwlen, key);
RC4_set_key(&arc4, n, key);
RC4(&arc4, 32, padding, output);
}
if (crypt_out->R == 3 || crypt_out->R == 4) {
unsigned char xor[32];
unsigned char digest[16];
MD5_CTX md5;
RC4_KEY arc4;
int i, x, n;
n = crypt_out->length / 8;
pdf_compute_encryption_key(password, pwlen, key);
MD5_Init(&md5);
MD5_Update(&md5, (char*)padding, 32);
MD5_Update(&md5, crypt_out->id, crypt_out->length_id);
MD5_Final(digest, &md5);
RC4_set_key(&arc4, n, key);
RC4(&arc4, 16, digest, output);
for (x = 1; x <= 19; x++) {
for (i = 0; i < n; i++)
xor[i] = key[i] ^ x;
RC4_set_key(&arc4, n, xor);
RC4(&arc4, 16, output, output);
}
memcpy(output + 16, padding, 16);
}
if (crypt_out->R == 5) {
pdf_compute_encryption_key_r5(password, pwlen, 0, output);
}
/* SumatraPDF: support crypt version 5 revision 6 */
if (crypt_out->R == 6)
pdf_compute_hardened_hash_r6(password, pwlen, crypt_out->u + 32, NULL, output);
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
if (any_cracked) {
memset(cracked, 0, cracked_size);
any_cracked = 0;
}
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
#if !defined(_OPENMP) && defined (__CYGWIN32__) && defined (MEMDBG_ON)
static /* work around for some 'unknown' bug in cygwin gcc when using memdbg.h code. I have NO explanation, JimF. */
#endif
unsigned char output[32];
pdf_compute_user_password((unsigned char*)saved_key[index], output);
if (crypt_out->R == 2 || crypt_out->R == 5 || crypt_out->R == 6)
if(memcmp(output, crypt_out->u, 32) == 0) {
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
if (crypt_out->R == 3 || crypt_out->R == 4)
if(memcmp(output, crypt_out->u, 16) == 0) {
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
}
return count;
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return cracked[index];
}
/*
* Report revision as tunable cost, since between revisions 2 and 6,
* only revisions 3 and 4 seem to have a similar c/s rate.
*/
static unsigned int pdf_revision(void *salt)
{
struct custom_salt *my_salt;
my_salt = salt;
return (unsigned int) my_salt->R;
}
struct fmt_main fmt_pdf = {
{
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,
{
"revision",
},
{ FORMAT_TAG, FORMAT_TAG_OLD },
pdf_tests
},
{
init,
done,
fmt_default_reset,
prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
{
pdf_revision,
},
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
pdf_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
GB_subassign_13.c | //------------------------------------------------------------------------------
// GB_subassign_13: C(I,J)<!M> = scalar ; using S
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Method 13: C(I,J)<!M> = scalar ; using S
// M: present
// Mask_comp: true
// C_replace: false
// accum: NULL
// A: scalar
// S: constructed
// C: not bitmap, but can be full since no zombies are inserted in that case
// M: not bitmap
#include "GB_subassign_methods.h"
GrB_Info GB_subassign_13
(
GrB_Matrix C,
// input:
const GrB_Index *I,
const int64_t ni,
const int64_t nI,
const int Ikind,
const int64_t Icolon [3],
const GrB_Index *J,
const int64_t nj,
const int64_t nJ,
const int Jkind,
const int64_t Jcolon [3],
const GrB_Matrix M,
const bool Mask_struct,
const void *scalar,
const GrB_Type atype,
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (!GB_IS_BITMAP (C)) ;
ASSERT (!GB_aliased (C, M)) ; // NO ALIAS of C==M
//--------------------------------------------------------------------------
// S = C(I,J)
//--------------------------------------------------------------------------
GB_EMPTY_TASKLIST ;
GB_OK (GB_subassign_symbolic (&S, C, I, ni, J, nj, true, Context)) ;
//--------------------------------------------------------------------------
// get inputs
//--------------------------------------------------------------------------
GB_MATRIX_WAIT_IF_JUMBLED (M) ;
GB_GET_C ; // C must not be bitmap
const int64_t Cnvec = C->nvec ;
const int64_t *GB_RESTRICT Ch = C->h ;
const int64_t *GB_RESTRICT Cp = C->p ;
const bool C_is_hyper = (Ch != NULL) ;
GB_GET_MASK ;
GB_GET_SCALAR ;
GB_GET_S ;
GrB_BinaryOp accum = NULL ;
//--------------------------------------------------------------------------
// Method 13: C(I,J)<!M> = scalar ; using S
//--------------------------------------------------------------------------
// Time: Close to optimal; must visit all IxJ, so Omega(|I|*|J|) is
// required. The sparsity of !M cannot be exploited.
// Methods 13, 15, 17, and 19 are very similar.
//--------------------------------------------------------------------------
// Parallel: all IxJ (Methods 01, 03, 13, 15, 17, 19)
//--------------------------------------------------------------------------
GB_SUBASSIGN_IXJ_SLICE ;
//--------------------------------------------------------------------------
// phase 1: create zombies, update entries, and count pending tuples
//--------------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
GB_GET_IXJ_TASK_DESCRIPTOR_PHASE1 (iA_start, iA_end) ;
//----------------------------------------------------------------------
// compute all vectors in this task
//----------------------------------------------------------------------
for (int64_t j = kfirst ; j <= klast ; j++)
{
//------------------------------------------------------------------
// get jC, the corresponding vector of C
//------------------------------------------------------------------
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
//------------------------------------------------------------------
// get S(iA_start:end,j) and M(iA_start:end,j)
//------------------------------------------------------------------
GB_GET_VECTOR_FOR_IXJ (S, iA_start) ;
GB_GET_VECTOR_FOR_IXJ (M, iA_start) ;
//------------------------------------------------------------------
// C(I(iA_start,iA_end-1),jC)<!M,repl> = scalar
//------------------------------------------------------------------
for (int64_t iA = iA_start ; iA < iA_end ; iA++)
{
//--------------------------------------------------------------
// Get the indices at the top of each list.
//--------------------------------------------------------------
int64_t iS = (pS < pS_end) ? GBI (Si, pS, Svlen) : INT64_MAX ;
int64_t iM = (pM < pM_end) ? GBI (Mi, pM, Mvlen) : INT64_MAX ;
//--------------------------------------------------------------
// find the smallest index of [iS iA iM] (always iA)
//--------------------------------------------------------------
int64_t i = iA ;
//--------------------------------------------------------------
// get M(i,j)
//--------------------------------------------------------------
bool mij ;
if (i == iM)
{
// mij = (bool) M [pM]
mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ;
GB_NEXT (M) ;
}
else
{
// mij not present, implicitly false
ASSERT (i < iM) ;
mij = false ;
}
// complement the mask entry mij since Mask_comp is true
mij = !mij ;
//--------------------------------------------------------------
// assign the entry
//--------------------------------------------------------------
if (i == iS)
{
ASSERT (i == iA) ;
{
// both S (i,j) and A (i,j) present
if (mij)
{
// ----[C A 1] or [X A 1]---------------------------
// [C A 1]: action: ( =A ): copy A, no accum
// [X A 1]: action: ( undelete ): zombie lives
GB_C_S_LOOKUP ;
GB_noaccum_C_A_1_scalar ;
}
GB_NEXT (S) ;
}
}
else
{
ASSERT (i == iA) ;
{
// S (i,j) is not present, A (i,j) is present
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
}
}
}
}
GB_PHASE1_TASK_WRAPUP ;
}
//--------------------------------------------------------------------------
// phase 2: insert pending tuples
//--------------------------------------------------------------------------
GB_PENDING_CUMSUM ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(&&:pending_sorted)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
GB_GET_IXJ_TASK_DESCRIPTOR_PHASE2 (iA_start, iA_end) ;
//----------------------------------------------------------------------
// compute all vectors in this task
//----------------------------------------------------------------------
for (int64_t j = kfirst ; j <= klast ; j++)
{
//------------------------------------------------------------------
// get jC, the corresponding vector of C
//------------------------------------------------------------------
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
//------------------------------------------------------------------
// get S(iA_start:end,j) and M(iA_start:end,j)
//------------------------------------------------------------------
GB_GET_VECTOR_FOR_IXJ (S, iA_start) ;
GB_GET_VECTOR_FOR_IXJ (M, iA_start) ;
//------------------------------------------------------------------
// C(I(iA_start,iA_end-1),jC)<!M,repl> = scalar
//------------------------------------------------------------------
for (int64_t iA = iA_start ; iA < iA_end ; iA++)
{
//--------------------------------------------------------------
// Get the indices at the top of each list.
//--------------------------------------------------------------
int64_t iS = (pS < pS_end) ? GBI (Si, pS, Svlen) : INT64_MAX ;
int64_t iM = (pM < pM_end) ? GBI (Mi, pM, Mvlen) : INT64_MAX ;
//--------------------------------------------------------------
// find the smallest index of [iS iA iM] (always iA)
//--------------------------------------------------------------
int64_t i = iA ;
//--------------------------------------------------------------
// get M(i,j)
//--------------------------------------------------------------
bool mij ;
if (i == iM)
{
// mij = (bool) M [pM]
mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ;
GB_NEXT (M) ;
}
else
{
// mij not present, implicitly false
ASSERT (i < iM) ;
mij = false ;
}
// complement the mask entry mij since Mask_comp is true
mij = !mij ;
//--------------------------------------------------------------
// assign the entry
//--------------------------------------------------------------
if (i == iS)
{
ASSERT (i == iA) ;
{
GB_NEXT (S) ;
}
}
else
{
ASSERT (i == iA) ;
{
// S (i,j) is not present, A (i,j) is present
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT (scalar) ;
}
}
}
}
}
GB_PHASE2_TASK_WRAPUP ;
}
//--------------------------------------------------------------------------
// finalize the matrix and return result
//--------------------------------------------------------------------------
GB_SUBASSIGN_WRAPUP ;
}
|
GB_binop__le_uint8.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__le_uint8)
// A.*B function (eWiseMult): GB (_AemultB_01__le_uint8)
// A.*B function (eWiseMult): GB (_AemultB_02__le_uint8)
// A.*B function (eWiseMult): GB (_AemultB_03__le_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__le_uint8)
// A*D function (colscale): GB (_AxD__le_uint8)
// D*A function (rowscale): GB (_DxB__le_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__le_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__le_uint8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__le_uint8)
// C=scalar+B GB (_bind1st__le_uint8)
// C=scalar+B' GB (_bind1st_tran__le_uint8)
// C=A+scalar GB (_bind2nd__le_uint8)
// C=A'+scalar GB (_bind2nd_tran__le_uint8)
// C type: bool
// A type: uint8_t
// B,b type: uint8_t
// BinaryOp: cij = (aij <= bij)
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_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,A_iso) \
uint8_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint8_t bij = GBX (Bx, pB, B_iso)
// 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_LE || GxB_NO_UINT8 || GxB_NO_LE_UINT8)
//------------------------------------------------------------------------------
// 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__le_uint8)
(
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__le_uint8)
(
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
#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__le_uint8)
(
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 uint8_t
uint8_t bwork = (*((uint8_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__le_uint8)
(
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
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__le_uint8)
(
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 *restrict Cx = (bool *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__le_uint8)
(
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__le_uint8)
(
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__le_uint8)
(
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__le_uint8)
(
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__le_uint8)
(
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__le_uint8)
(
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 ;
uint8_t x = (*((uint8_t *) x_input)) ;
uint8_t *Bx = (uint8_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 ;
uint8_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__le_uint8)
(
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 ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint8_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) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x <= aij) ; \
}
GrB_Info GB (_bind1st_tran__le_uint8)
(
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 \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_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) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij <= y) ; \
}
GrB_Info GB (_bind2nd_tran__le_uint8)
(
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
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
2.norace6.c | // RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s
#include <omp.h>
#define N 200
int main() {
int A[N], x = 0;
#pragma omp simd linear(x : 2)
for (int i = 0; i < N; i++)
A[i] = x;
}
// CHECK: Region is Data Race Free.
// END
|
omp6.c | #include<stdio.h>
int N;
struct State {
int col[99], d0[99], d1[99];
};
int set(int r, int c, struct State *s) {
if (s->col[c] || s->d0[r+c] || s->d1[N+r-c])
return 0;
s->col[c]++;
s->d0[r+c]++;
s->d1[N+r-c]++;
return 1;
}
void unset(int r, int c, struct State *s) {
s->col[c]--;
s->d0[r+c]--;
s->d1[N+r-c]--;
}
int q(int r, struct State *s) {
if (r >= N) return 1;
int c, sum = 0;
for (c = 0; c < N; c++) {
if (set(r, c, s)) {
sum += q(r+1, s);
unset(r, c, s);
}
}
return sum;
}
int main() {
int i, j, count[N];
struct State s;
scanf("%d", &N);
#pragma omp parallel for private(s, j)
for (i = 0; i < 14; i++) {
if (i >= N/2) continue;
for (j = 0; j < N*2; ++j)
s.col[j] = s.d0[j] = s.d1[j] = 0;
set(0, i, &s);
count[i] = q(1, &s);
unset(0, i, &s);
}
for (i = 0; i < N/2; ++i)
printf("%d ", count[i]);
return 0;
}
|
5742.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
#pragma omp parallel for simd schedule(dynamic, 8) private(j)
for (i = 1; i < _PB_NI - 1; ++i)
{
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;
}
|
MultiLevelSetup.h | /*
* MultiLevelSetup.h
*
* Created on: 10.01.2015
* Author: Michael Wegner (michael.wegner@student.kit.edu)
*/
#ifndef MULTILEVELSETUP_H_
#define MULTILEVELSETUP_H_
#include "LevelHierarchy.h"
#include "../Smoother.h"
#include "../../algebraic/CSRMatrix.h"
#include <limits>
namespace NetworKit {
/**
* @ingroup
* Implements the setup phase of LAMG (Lean Algebraic Multigrid by Livne et al.).
*/
template<class Matrix>
class MultiLevelSetup {
#define UNDECIDED std::numeric_limits<index>::max()
private:
const Smoother<Matrix> &smoother;
/**
* Elimination phase of LAMG for the specified Laplacian matrix @a matrix. If an elemination stage is created,
* it is stored in the LevelHierarchy @a hierarchy and the method returns @code{true}. Otherwise, @code{false}
* is returned.
* @param matrix Laplacian matrix for which an elimination stage should be created.
* @param hierarchy LevelHierarchy in which the created elimination stage is stored (if created)
* @return @code{True} if an elimination stage has been created, otherwise @code{false}.
*/
bool coarseningElimination(Matrix& matrix, LevelHierarchy<Matrix>& hierarchy) const;
/**
* Scans the Laplacian matrix for nodes with a low degree (i.e. nodes with less than 5 neighbors). For each node
* having low degree and independent from already found low degree nodes, @code{true} is stored in @a fNode. The
* @a stage parameter specifies if we are in the first or subsequent stages during elimination.
* @param matrix Laplacian matrix.
* @param fNode[out] For each node, @code{true} if the node is of low degree and @code{false} otherwise.
* @param stage The stage of the elimination phase.
* @return Number of low degree nodes found.
*/
count lowDegreeSweep(const Matrix& matrix, std::vector<bool>& fNode, index stage) const;
/**
* Computes the projection matrix @a P and the @a q vector used to restrict and interpolate the matrix for an
* elimination stage.
* @param matrix Laplacian matrix.
* @param fSet Set of nodes having low degree.
* @param coarseIndex Set of nodes equal to V \setminus fSet
* @param P[out] The projection matrix.
* @param q[out] The q vector.
*/
void eliminationOperators(const Matrix& matrix, const std::vector<index>& fSet, const std::vector<index>& coarseIndex, Matrix& P, Vector& q) const;
/**
* Aggregation phase of LAMG for the specified Laplacian matrix @a matrix. The coarsened matrix is stored in the
* LevelHierarchy @a hierarchy. The test vector @a tv is used for determining the affinity of nodes. The parameter
* @a numTVVectors specifies how many test vectors will be created to determine the affinities between nodes.
* @param matrix Laplacian matrix.
* @param hierarchy LevelHierarchy to store the stage.
* @param tv Test vector.
* @param numTVVectors Number of test vectors to use.
*/
void coarseningAggregation(Matrix& matrix, LevelHierarchy<Matrix>& hierarchy, Vector& tv, count numTVVectors) const;
/**
* Create @a numVectors test vectors for the given Laplacian matrix @a matrix. The test vector @a tv will be
* reused.
* @param matrix Laplacian matrix.
* @param tv Test vector.
* @param numVectors Number of test vectors to create.
* @return The created test vectors.
*/
std::vector<Vector> generateTVs(const Matrix& matrix, Vector& tv, const count numVectors) const;
/**
* Adds high degree nodes as seeds to @a status.
* @param matrix Laplacian matrix.
* @param status[out] High degree nodes are flagged as seed.
*/
void addHighDegreeSeedNodes(const Matrix& matrix, std::vector<index>& status) const;
/**
* Aggregates loose nodes (nodes with low adjacency) together.
* @param strongAdjMatrix Strong adjacency matrix.
* @param status[out] Aggregates loose nodes together and labels them in @a status accordingly.
* @param nc[out] The altered number of coarse nodes.
*/
void aggregateLooseNodes(const Matrix& strongAdjMatrix, std::vector<index>& status, count& nc) const;
/**
* Computes the strong adjacency matrix for the given Laplacian matrix @a matrix.
* @param matrix Laplacian matrix.
* @param strongAdjMatrix[out] The resulting strong adjacency matrix.
*/
void computeStrongAdjacencyMatrix(const Matrix& matrix, Matrix& strongAdjMatrix) const;
/**
* Computes the affinity matrix for the given Laplacian matrix @a matrix and the test vectors @a tVs.
* @param matrix Laplacian matrix.
* @param tVs Test vectors.
* @param affinityMatrix[out] The resulting affinity matrix.
*/
void computeAffinityMatrix(const Matrix& matrix, const std::vector<Vector>& tVs, Matrix& affinityMatrix) const;
/**
* Models one stage in the aggregation phase. New aggregates are labeled accordingly in @a status.
* @param matrix Laplacian matrix.
* @param nc Number of coarse nodes.
* @param strongAdjMatrix Strong adjacency matrix.
* @param affinityMatrix Affinity matrix.
* @param tVs[out] Test vectors.
* @param status[out] Aggregation labels.
*/
void aggregationStage(const Matrix& matrix, count& nc, const Matrix& strongAdjMatrix, const Matrix& affinityMatrix, std::vector<Vector>& tVs, std::vector<index>& status) const;
/**
* Computes strong (cf. LAMG paper) neighbors and stores them sorted into @a bins.
* @param affinityMatrix Affinity matrix.
* @param status Aggregation labels.
* @param bins[out] Strong neighbors sorted into bins.
*/
void computeStrongNeighbors(const Matrix& affinityMatrix, const std::vector<index>& status, std::vector<std::vector<index>>& bins) const;
/**
* Finds the best seed for node @a u and stores it in @a s.
* @param strongAdjMatrix
* @param affinityMatrix Affinity matrix.
* @param diag Vector of diagonal entries of the Laplacian matrix.
* @param tVs Test vectors.
* @param status Aggregation labels.
* @param u The node to find the best seed for.
* @param s[out] The best seed for node @a u.
* @return @code{True} if a seed has been found for @a u, @code{false} otherwise.
*/
bool findBestSeedEnergyCorrected(const Matrix& strongAdjMatrix, const Matrix& affinityMatrix, const std::vector<double>& diag, const std::vector<Vector>& tVs, const std::vector<index>& status, const index u, index& s) const;
/**
* Determines if the Laplacian matrix @a A can be coarsened further.
* @param A Laplacian matrix.
* @return @code{True} if @a A can be coarsened further, @code{false} otherwise.
*/
inline bool canCoarsen(const Matrix& A) const {
return A.numberOfRows() > MAX_DIRECT_SOLVE_SIZE;
}
/**
* Determines if the relaxation is fast enough to stop coarsening.
* @param A Laplacian matrix.
* @param lvlIndex The number of levels already created in the hierarchy.
* @param tv Test vector.
* @return @code{True} if convergence of relaxation is fast, @code{false} otherwise.
*/
bool isRelaxationFast(const Matrix& A, index lvlIndex, Vector& tv) const;
/**
* Computes the coarsened matrix of @a matrix by means of the projection matrix @a P and stores the result in @a B.
* @param P Projection matrix.
* @param A Laplacian matrix.
* @param PColIndex Stores the column index of the 1 entry at each row.
* @param PRowIndex Stores the row index of the 1 entry at each column.
* @param B[out] Resulting coarsened Laplacian matrix.
*/
void galerkinOperator(const Matrix& P, const Matrix& A, const std::vector<index>& PColIndex, const std::vector<std::vector<index>>& PRowIndex, Matrix& B) const;
/**
* Creates a @a hierarchy for the given Laplacian matrix @a matrix.
* @param matrix Laplcian matrix.
* @param hierarchy[out] The constructed hierarchy.
*/
void setupForMatrix(Matrix& matrix, LevelHierarchy<Matrix>& hierarchy) const;
public:
/**
* Creates an instance of MultiLevelSetup with the specified @a smoother used for relaxing during the setup phase.
* @param smoother Reference to smoother.
*/
MultiLevelSetup(const Smoother<Matrix>& smoother) : smoother(smoother) {}
/**
* Creates a @å hierarchy for the given Laplacian matrix of the graph @a G.
* @param G The graph.
* @param hierarchy[out] The constructed hierarchy.
*/
void setup(const Graph& G, LevelHierarchy<Matrix>& hierarchy) const {
setup(Matrix::laplacianMatrix(G), hierarchy);
}
/**
* Creates a @a hierarchy for the given Laplacian matrix @a matrix.
* @param matrix Laplcian matrix.
* @param hierarchy[out] The constructed hierarchy.
*/
void setup(const Matrix& matrix, LevelHierarchy<Matrix>& hierarchy) const;
};
template<class Matrix>
void MultiLevelSetup<Matrix>::setup(const Matrix& matrix, LevelHierarchy<Matrix>& hierarchy) const {
CSRMatrix A = matrix;
setupForMatrix(A, hierarchy);
}
template<class Matrix>
void MultiLevelSetup<Matrix>::setupForMatrix(Matrix& A, LevelHierarchy<Matrix>& hierarchy) const {
hierarchy.addFinestLevel(A);
#ifndef NDEBUG
DEBUG("FINEST\t", A.numberOfRows(), "\t", A.nnz());
#endif
bool doneCoarsening = false;
count numTVs = TV_NUM;
index level = 0;
while (!doneCoarsening) {
// ELIMINATION
if (coarseningElimination(A, hierarchy)) {
if (!canCoarsen(A)) doneCoarsening = true;
level++;
#ifndef NDEBUG
DEBUG(level, " ELIM\t\t", A.numberOfRows(), "\t", A.nnz() / 2);
#endif
}
// AGGREGATION
Vector tv;
if (doneCoarsening || isRelaxationFast(A, level, tv)) {
doneCoarsening = true;
} else {
coarseningAggregation(A, hierarchy, tv, numTVs);
level++;
#ifndef NDEBUG
DEBUG(level, " AGG\t\t", A.numberOfRows(), "\t", A.nnz() / 2);
#endif
if (numTVs < TV_MAX) {
numTVs += TV_INC;
}
}
if (!canCoarsen(A)) doneCoarsening = true;
}
hierarchy.setLastAsCoarsest();
}
template<class Matrix>
bool MultiLevelSetup<Matrix>::coarseningElimination(Matrix& matrix, LevelHierarchy<Matrix>& hierarchy) const {
std::vector<EliminationStage<Matrix>> coarseningStages;
count stageNum = 0;
while (stageNum < SETUP_ELIMINATION_MAX_STAGES) {
if (matrix.numberOfRows() <= MAX_DIRECT_SOLVE_SIZE) break; // we do not need to coarsen the matrix any further
std::vector<bool> fNode;
count nf = lowDegreeSweep(matrix, fNode, stageNum);
count nc = matrix.numberOfRows() - nf;
if (nc == 0) { // do not eliminate all nodes -> leave one entry in c
nc = 1;
nf--;
}
// add f nodes to fSet and c nodes to cSet
std::vector<index> fSet(nf);
std::vector<index> cSet(nc);
std::vector<index> coarseIndex(matrix.numberOfRows());
count numFNodes = 0;
for (index i = 0, fIndex = 0, cIndex = 0; i < matrix.numberOfRows(); ++i) {
if (fNode[i] && fIndex < nf) {
coarseIndex[i] = fIndex;
fSet[fIndex++] = i;
numFNodes++;
} else {
coarseIndex[i] = cIndex;
cSet[cIndex++] = i;
}
}
if (nf <= SETUP_ELIMINATION_MIN_ELIM_FRACTION * matrix.numberOfRows()) {
break;
}
Matrix P;
Vector q;
eliminationOperators(matrix, fSet, coarseIndex, P, q);
coarseningStages.push_back(EliminationStage<Matrix>(P, q, fSet, cSet));
Matrix Acc = matrix.extract(cSet, cSet); // Schur complement
Matrix Acf = matrix.extract(cSet, fSet); // Schur complement
matrix = Acc + Acf * P;
stageNum++;
}
if (stageNum != 0) { // we have coarsened the matrix
hierarchy.addEliminationLevel(matrix, coarseningStages);
return true;
}
return false;
}
template<class Matrix>
count MultiLevelSetup<Matrix>::lowDegreeSweep(const Matrix& matrix, std::vector<bool>& fNode, index stage) const {
fNode.resize(matrix.numberOfRows(), true); // first mark all nodes as f nodes
count numFNodes = 0;
int degreeOffset = stage != 0;
for (index i = 0; i < matrix.numberOfRows(); ++i) {
if ((int) matrix.nnzInRow(i) - degreeOffset <= (int)SETUP_ELIMINATION_MAX_DEGREE && fNode[i]) { // node i has degree <= 4 and can be eliminated
numFNodes++;
matrix.forNonZeroElementsInRow(i, [&](index j, edgeweight w){ // to maintain independence, mark all neighbors as not eliminated
if (j != i) { // all neighbors of this f node are c nodes
fNode[j] = false;
}
});
} else { // node has high degree, thus it is a c node
fNode[i] = false;
}
}
return numFNodes;
}
template<class Matrix>
void MultiLevelSetup<Matrix>::eliminationOperators(const Matrix& matrix, const std::vector<index>& fSet, const std::vector<index>& coarseIndex, Matrix& P, Vector& q) const {
std::vector<Triplet> triples;
q = Vector(fSet.size());
for (index k = 0; k < fSet.size(); ++k) { // Afc
matrix.forNonZeroElementsInRow(fSet[k], [&](index j, edgeweight w){
if (fSet[k] == j) {
q[k] = 1.0 / w;
} else {
triples.push_back({k, coarseIndex[j], w});
}
});
}
for (index i = 0; i < triples.size(); ++i) { // * -Aff^-1
triples[i].value *= -q[triples[i].row];
}
P = Matrix(fSet.size(), coarseIndex.size() - fSet.size(), triples);
}
template<class Matrix>
void MultiLevelSetup<Matrix>::coarseningAggregation(Matrix& matrix, LevelHierarchy<Matrix>& hierarchy, Vector& tv, count numTVVectors) const {
Vector B(SETUP_MAX_AGGREGATION_STAGES, std::numeric_limits<double>::max());
std::vector<std::vector<index>> S(SETUP_MAX_AGGREGATION_STAGES, std::vector<index>(matrix.numberOfRows(), std::numeric_limits<index>::max()));
std::vector<index> status(matrix.numberOfRows(), UNDECIDED);
std::vector<count> nc(SETUP_MAX_AGGREGATION_STAGES, matrix.numberOfRows());
double alpha = 1.0;
double maxCoarseningRatio = SETUP_COARSENING_WORK_GUARD / SETUP_CYCLE_INDEX;
count stage = 0;
count nC = matrix.numberOfRows();
// generate TVs
std::vector<Vector> tVs = generateTVs(matrix, tv, numTVVectors);
// compute strong adjacency matrix
Matrix Wstrong;
computeStrongAdjacencyMatrix(matrix, Wstrong);
// compute affinityMatrix
Matrix affinityMatrix;
computeAffinityMatrix(Wstrong, tVs, affinityMatrix);
// mark all locally high-degree nodes as seeds
addHighDegreeSeedNodes(matrix, status);
// aggregate all loose nodes
aggregateLooseNodes(Wstrong, status, nC);
nc[0] = nC;
while (stage < SETUP_MIN_AGGREGATION_STAGES || (alpha >= maxCoarseningRatio && stage < SETUP_MAX_AGGREGATION_STAGES)) {
nC = stage > 0? nc[stage - 1] : nc[0];
// aggregation stage
aggregationStage(matrix, nC, Wstrong, affinityMatrix, tVs, status);
alpha = (double) nC / (double) matrix.numberOfRows();
alpha <= maxCoarseningRatio? B[stage] = 1.0-alpha : B[stage] = 1.0+alpha;
S[stage] = status;
nc[stage] = nC;
stage++;
}
double min = B[0];
index bestAggregate = 0;
for (index i = 1; i < stage; ++i) {
if (B[i] < min) {
bestAggregate = i;
min = B[i];
}
}
for (index i = 0; i < matrix.numberOfRows(); ++i) {
if (S[bestAggregate][i] == UNDECIDED) { // undediced nodes become their own seeds
S[bestAggregate][i] = i;
}
}
std::vector<index> indexFine(matrix.numberOfRows(), 0);
index newIndex = 0;
for (index i = 0; i < matrix.numberOfRows(); ++i) {
if (S[bestAggregate][i] == i) {
indexFine[i] = newIndex++;
}
}
for (index i = 0; i < matrix.numberOfRows(); ++i) {
status[i] = indexFine[S[bestAggregate][i]];
}
assert(newIndex == nc[bestAggregate]);
// create interpolation matrix
std::vector<Triplet> pTriples(matrix.numberOfRows());
std::vector<Triplet> rTriples(matrix.numberOfRows());
std::vector<index> PColIndex(matrix.numberOfRows());
std::vector<std::vector<index>> PRowIndex(nc[bestAggregate]);
for (index i = 0; i < matrix.numberOfRows(); ++i) {
pTriples[i] = {i, status[i], 1};
rTriples[i] = {status[i], i, 1};
PColIndex[i] = status[i];
PRowIndex[status[i]].push_back(i);
}
Matrix P(matrix.numberOfRows(), nc[bestAggregate], pTriples);
Matrix R(nc[bestAggregate], matrix.numberOfRows(), rTriples);
// create coarsened laplacian
galerkinOperator(P, matrix, PColIndex, PRowIndex, matrix);
hierarchy.addAggregationLevel(matrix, P, R);
}
template<class Matrix>
std::vector<Vector> MultiLevelSetup<Matrix>::generateTVs(const Matrix& matrix, Vector& tv, count numVectors) const {
std::vector<Vector> testVectors(numVectors, Vector(matrix.numberOfColumns()));
testVectors[0] = tv;
if (numVectors > 1) {
Vector b(matrix.numberOfColumns(), 0.0);
#pragma omp parallel for
for (count i = 1; i < numVectors; ++i) {
for (count j = 0; j < matrix.numberOfColumns(); ++j) {
testVectors[i][j] = 2 * Aux::Random::probability() - 1;
}
testVectors[i] = smoother.relax(matrix, b, testVectors[i], SETUP_TV_SWEEPS);
}
}
return testVectors;
}
template<class Matrix>
void MultiLevelSetup<Matrix>::addHighDegreeSeedNodes(const Matrix& matrix, std::vector<index>& status) const {
std::vector<count> deg(matrix.numberOfRows());
#pragma omp parallel for
for (index i = 0; i < matrix.numberOfRows(); ++i) {
deg[i] = matrix.nnzInRow(i) - 1;
}
#pragma omp parallel for
for (index i = 0; i < matrix.numberOfRows(); ++i) {
double num = 0.0;
double denom = 0.0;
matrix.forNonZeroElementsInRow(i, [&](index j, double value){
if (i != j) {
num += std::abs(value) * (double) deg[j];
} else {
denom = std::abs(value);
}
});
if ((double) deg[i] >= SETUP_AGGREGATION_DEGREE_THRESHOLD * (num / denom)) { // high degree node becomes seed
status[i] = i;
}
}
}
template<class Matrix>
void MultiLevelSetup<Matrix>::aggregateLooseNodes(const Matrix& strongAdjMatrix, std::vector<index>& status, count& nc) const {
std::vector<index> looseNodes;
for (index i = 0; i < strongAdjMatrix.numberOfRows(); ++i) {
double max = std::numeric_limits<double>::min();
strongAdjMatrix.forNonZeroElementsInRow(i, [&](index j, double value) {
if (value > max) max = value;
});
if (std::abs(max) < 1e-9 || max == std::numeric_limits<double>::min()) {
looseNodes.push_back(i);
}
}
if (looseNodes.size() > 0) {
status[looseNodes[0]] = looseNodes[0]; // mark first as seed
for (index k = 1; k < looseNodes.size(); ++k) {
status[looseNodes[k]] = looseNodes[0]; // first loose nodes becomes seed
}
nc -= looseNodes.size() - 1;
}
}
template<class Matrix>
void MultiLevelSetup<Matrix>::computeStrongAdjacencyMatrix(const Matrix& matrix, Matrix& strongAdjMatrix) const {
std::vector<double> maxNeighbor(matrix.numberOfRows(), std::numeric_limits<double>::min());
#pragma omp parallel for
for (index i = 0; i < matrix.numberOfRows(); ++i) {
matrix.forNonZeroElementsInRow(i, [&](index j, double value) {
if (i != j && -value > maxNeighbor[i]) {
maxNeighbor[i] = -value;
}
});
}
std::vector<index> rowIdx(matrix.numberOfRows()+1, 0);
matrix.parallelForNonZeroElementsInRowOrder([&](index i, index j, double value) {
if (i != j && std::abs(value) >= 0.1 * std::min(maxNeighbor[i], maxNeighbor[j])) {
++rowIdx[i+1];
}
});
for (index i = 0; i < matrix.numberOfRows(); ++i) {
rowIdx[i+1] += rowIdx[i];
}
count nnz = rowIdx[matrix.numberOfRows()];
std::vector<Triplet> triplets(nnz);
#pragma omp parallel for
for (index i = 0; i < matrix.numberOfRows(); ++i) {
index cIdx = rowIdx[i];
matrix.forNonZeroElementsInRow(i, [&](index j, double value) {
if (i != j && std::abs(value) >= 0.1 * std::min(maxNeighbor[i], maxNeighbor[j])) {
triplets[cIdx] = {i,j,-value};
++cIdx;
}
});
}
strongAdjMatrix = Matrix(matrix.numberOfRows(), matrix.numberOfColumns(), triplets);
}
template<class Matrix>
void MultiLevelSetup<Matrix>::computeAffinityMatrix(const Matrix& matrix, const std::vector<Vector>& tVs, Matrix& affinityMatrix) const {
assert(tVs.size() > 0);
std::vector<index> rowIdx(matrix.numberOfRows()+1);
std::vector<Triplet> triplets(matrix.nnz());
#pragma omp parallel for
for (index i = 0; i < matrix.numberOfRows(); ++i) {
rowIdx[i+1] = matrix.nnzInRow(i);
}
for (index i = 0; i < matrix.numberOfRows(); ++i) {
rowIdx[i+1] += rowIdx[i];
}
std::vector<double> normSquared(matrix.numberOfRows(), 0.0);
#pragma omp parallel for
for (index i = 0; i < matrix.numberOfRows(); ++i) {
for (index k = 0; k < tVs.size(); ++k) {
normSquared[i] += tVs[k][i] * tVs[k][i];
}
}
#pragma omp parallel for
for (index i = 0; i < matrix.numberOfRows(); ++i) {
double nir = 1.0 / normSquared[i];
index cIdx = rowIdx[i];
matrix.forNonZeroElementsInRow(i, [&](index j, double val) {
double ij = 0.0;
for (index k = 0; k < tVs.size(); ++k) {
ij += tVs[k][i] * tVs[k][j];
}
double value = (ij * ij) * nir / normSquared[j];
triplets[cIdx] = {i,j,value};
++cIdx;
});
}
affinityMatrix = Matrix(matrix.numberOfRows(), matrix.numberOfColumns(), triplets);
}
template<class Matrix>
void MultiLevelSetup<Matrix>::aggregationStage(const Matrix& matrix, count& nc, const Matrix& strongAdjMatrix, const Matrix& affinityMatrix, std::vector<Vector>& tVs, std::vector<index>& status) const {
std::vector<std::vector<index>> bins(10);
computeStrongNeighbors(affinityMatrix, status, bins);
std::vector<double> diag(matrix.numberOfRows(), 0.0);
#pragma omp parallel for
for (index i = 0 ; i < matrix.numberOfRows(); ++i) {
diag[i] = matrix(i,i);
}
for (index k = bins.size(); k-- > 0;) { // iterate over undecided nodes with strong neighbors in decreasing order of strongest neighbor
for (index i : bins[k]) {
if (status[i] == UNDECIDED) { // node is still undecided
index s = 0;
if (findBestSeedEnergyCorrected(strongAdjMatrix, affinityMatrix, diag, tVs, status, i, s)) {
status[s] = s; // s becomes seed
status[i] = s; // i's seed is s
nc--;
for (index j = 0; j < tVs.size(); ++j) { // update test vectors
tVs[j][i] = tVs[j][s];
}
}
}
}
if (nc <= matrix.numberOfRows() * SETUP_COARSENING_WORK_GUARD / SETUP_CYCLE_INDEX) {
break;
}
} // iterate over bins
}
template<class Matrix>
void MultiLevelSetup<Matrix>::computeStrongNeighbors(const Matrix& affinityMatrix, const std::vector<index>& status, std::vector<std::vector<index>>& bins) const {
std::vector<bool> undecided(affinityMatrix.numberOfRows(), false);
std::vector<double> maxNeighbor(affinityMatrix.numberOfRows(), std::numeric_limits<double>::min());
double overallMax = 0.0;
double overallMin = std::numeric_limits<double>::max();
affinityMatrix.parallelForNonZeroElementsInRowOrder([&](index i, index j, double value) { // determine the highest affinity neighbor of each node
if (status[i] == UNDECIDED && (status[j] == UNDECIDED || status[j] == j)) { // i is UNDECIDED and its neighbor j is also UNDECIDED or SEED
if (value > maxNeighbor[i]) {
maxNeighbor[i] = value;
}
undecided[i] = true;
}
});
for (index i = 0; i < affinityMatrix.numberOfRows(); ++i) {
if (maxNeighbor[i] > overallMax) {
overallMax = maxNeighbor[i];
}
if (maxNeighbor[i] < overallMin) {
overallMin = maxNeighbor[i];
}
}
double h = fabs(overallMax - overallMin) < 1e-15? 1.0 : (double) bins.size() / (overallMax - overallMin);
for (index i = 0; i < affinityMatrix.numberOfRows(); ++i) {
if (undecided[i]) { // undecided nodes with strong neighbors
index binIndex = (index) std::floor(h * (maxNeighbor[i] - overallMin));
if (binIndex == bins.size()) { // last interval is closed on the right
binIndex--;
}
assert(binIndex >= 0 && binIndex < bins.size());
bins[binIndex].push_back(i);
}
}
}
template<class Matrix>
bool MultiLevelSetup<Matrix>::findBestSeedEnergyCorrected(const Matrix& strongAdjMatrix, const Matrix& affinityMatrix, const std::vector<double>& diag, const std::vector<Vector>& tVs, const std::vector<index>& status, const index u, index& s) const {
bool foundSeed = false;
std::vector<double> r(tVs.size(), 0.0);
std::vector<double> q(tVs.size(), 0.0);
std::vector<double> E(tVs.size(), 0.0);
double d = diag[u];
double d2 = 0.5 * diag[u];
for (index k = 0; k < tVs.size(); ++k) {
double rr = 0.0;
double qq = 0.0;
strongAdjMatrix.forNonZeroElementsInRow(u, [&](index v, double value) {
rr += value * tVs[k][v];
qq += value * 0.5 * tVs[k][v] * tVs[k][v];
});
r[k] = rr;
q[k] = qq;
double y = rr/d;
E[k] = (d2*y - rr)*y + qq;
}
double maxNeighbor = -1.0;
affinityMatrix.forNonZeroElementsInRow(u, [&](index v, double value) {
if (status[v] == UNDECIDED || status[v] == v) {
double maxMu = -1.0;
bool smallRatio = true;
for (index k = 0; k < tVs.size(); ++k) {
double xv = tVs[k][v];
double Ec = (d2*xv - r[k])*xv + q[k];
double mu = Ec / (E[k] + 1e-15);
if (mu > maxMu) {
maxMu = mu;
}
if (maxMu > 2.5) {
smallRatio = false;
break;
}
}
if (smallRatio && value > maxNeighbor) {
maxNeighbor = value;
s = v;
foundSeed = true;
}
}
});
return foundSeed;
}
template<class Matrix>
bool MultiLevelSetup<Matrix>::isRelaxationFast(const Matrix& A, index lvlIndex, Vector& tv) const {
count nu = SETUP_RELAX_ACF_MIN_SWEEPS + 2 * (lvlIndex - 1);
count tvNu = SETUP_TV_SWEEPS;
count initial = 3;
// create testVector in [-1,1]
tv = Vector(A.numberOfRows());
for (index i = 0; i < tv.getDimension(); ++i) {
tv[i] = 2.0 * Aux::Random::probability() - 1.0;
}
Vector b(A.numberOfRows(), 0.0);
Vector x = tv;
x = smoother.relax(A, b, x, initial);
tv = smoother.relax(A, b, x, tvNu - initial);
Vector y = smoother.relax(A, b, tv, nu - tvNu);
double relaxAcf = std::pow((y - y.mean()).length() / (x - x.mean()).length(), (double) 1.0 / (double) (nu - initial));
return relaxAcf <= SETUP_MAX_COARSE_RELAX_ACF || !canCoarsen(A);
}
template<class Matrix>
void MultiLevelSetup<Matrix>::galerkinOperator(const Matrix& P, const Matrix& A, const std::vector<index>& PColIndex, const std::vector<std::vector<index>>& PRowIndex, Matrix& B) const {
std::vector<Triplet> triplets;
SparseAccumulator spa(P.numberOfColumns());
for (index i = 0; i < P.numberOfColumns(); ++i) {
for (index k : PRowIndex[i]) {
double Pki = P(k,i);
A.forNonZeroElementsInRow(k, [&](index l, double value) {
index j = PColIndex[l];
spa.scatter(Pki * value * P(l, j), j);
});
}
spa.gather([&](index i, index j, double value) {
triplets.push_back({i,j,value});
});
spa.increaseRow();
}
B = CSRMatrix(P.numberOfColumns(), P.numberOfColumns(), triplets);
}
} /* namespace NetworKit */
#endif /* MULTILEVELSETUP_H_ */
|
pbkdf2_hmac_sha256_fmt_plug.c | /* 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.
*
* Based on hmac-sha512 by magnum
*
* Minor fixes, format unification and OMP support done by Dhiru Kholia
* <dhiru@openwall.com>
*
* Fixed for supporting $ml$ "dave" format as well as GRUB native format by
* magnum 2013. Note: We support a binary size of >512 bits (64 bytes / 128
* chars of hex) but we currently do not calculate it even in cmp_exact(). The
* chance for a 512-bit hash collision should be pretty dang slim.
*
* the pbkdf2_sha256_hmac was so messed up, I simply copied sha512 over the top
* of it, replacing the code in totality. JimF.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_pbkdf2_hmac_sha256;
#elif FMT_REGISTERS_H
john_register_one(&fmt_pbkdf2_hmac_sha256);
#else
#include <ctype.h>
#include <string.h>
#include <assert.h>
#include "misc.h"
#include "arch.h"
#include "common.h"
#include "formats.h"
#include "base64_convert.h"
#include "sha2.h"
#include "johnswap.h"
#include "stdint.h"
#include "pbkdf2_hmac_sha256.h"
#define FORMAT_LABEL "PBKDF2-HMAC-SHA256"
#define FORMAT_NAME ""
#define BENCHMARK_COMMENT ", rounds=12000"
#ifdef MMX_COEF_SHA256
#define ALGORITHM_NAME "PBKDF2-SHA256 " SHA256_ALGORITHM_NAME
#else
#if ARCH_BITS >= 64
#define ALGORITHM_NAME "PBKDF2-SHA256 64/" ARCH_BITS_STR " " SHA2_LIB
#else
#define ALGORITHM_NAME "PBKDF2-SHA256 32/" ARCH_BITS_STR " " SHA2_LIB
#endif
#endif
#define BINARY_SIZE 32
#define MAX_CIPHERTEXT_LENGTH 1024 /* Bump this and code will adopt */
#define MAX_BINARY_SIZE (4*32) /* Bump this and code will adopt */
#define MAX_SALT_SIZE 128 /* Bump this and code will adopt */
#define SALT_SIZE sizeof(struct custom_salt)
#define FMT_PREFIX "$pbkdf2-sha256$"
#define FMT_CISCO8 "$8$"
#ifdef MMX_COEF_SHA256
#define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
#define BENCHMARK_LENGTH -1
#ifdef _OPENMP
static int omp_t = 1;
#include <omp.h>
#define OMP_SCALE 4
#endif
#include "memdbg.h"
#define PAD_SIZE 128
#define PLAINTEXT_LENGTH 125
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
static struct fmt_tests tests[] = {
{"$pbkdf2-sha256$12000$2NtbSwkhRChF6D3nvJfSGg$OEWLc4keep8Vx3S/WnXgsfalb9q0RQdS1s05LfalSG4", ""},
{"$pbkdf2-sha256$12000$fK8VAoDQuvees5ayVkpp7Q$xfzKAoBR/Iaa68tjn.O8KfGxV.zdidcqEeDoTFvDz2A", "1"},
{"$pbkdf2-sha256$12000$GoMQYsxZ6/0fo5QyhtAaAw$xQ9L6toKn0q245SIZKoYjCu/Fy15hwGme9.08hBde1w", "12"},
{"$pbkdf2-sha256$12000$6r3XWgvh/D/HeA/hXAshJA$11YY39OaSkJuwb.ONKVy5ebCZ00i5f8Qpcgwfe3d5kY", "123"},
{"$pbkdf2-sha256$12000$09q711rLmbMWYgwBIGRMqQ$kHdAHlnQ1i1FHKBCPLV0sA20ai2xtYA1Ev8ODfIkiQg", "1234"},
{"$pbkdf2-sha256$12000$Nebce08pJcT43zuHUMo5Rw$bMW/EsVqy8tMaDecFwuZNEPVfQbXBclwN78okLrxJoA", "openwall"},
{"$pbkdf2-sha256$12000$mtP6/39PSQlhzBmDsJZS6g$zUXxf/9XBGrkedXVwhpC9wLLwwKSvHX39QRz7MeojYE", "password"},
{"$pbkdf2-sha256$12000$35tzjhGi9J5TSilF6L0XAg$MiJA1gPN1nkuaKPVzSJMUL7ucH4bWIQetzX/JrXRYpw", "pbkdf2-sha256"},
{"$pbkdf2-sha256$12000$sxbCeE8pxVjL2ds7hxBizA$uIiwKdo9DbPiiaLi1y3Ljv.r9G1tzxLRdlkD1uIOwKM", " 15 characters "},
{"$pbkdf2-sha256$12000$CUGI8V7rHeP8nzMmhJDyXg$qjq3rBcsUgahqSO/W4B1bvsuWnrmmC4IW8WKMc5bKYE", " 16 characters__"},
{"$pbkdf2-sha256$12000$FmIM4VxLaY1xLuWc8z6n1A$OVe6U1d5dJzYFKlJsZrW1NzUrfgiTpb9R5cAfn96WCk", " 20 characters______"},
{"$pbkdf2-sha256$12000$fA8BAMAY41wrRQihdO4dow$I9BSCuV6UjG55LktTKbV.bIXtyqKKNvT3uL7JQwMLp8", " 24 characters______1234"},
{"$pbkdf2-sha256$12000$/j8npJTSOmdMKcWYszYGgA$PbhiSNRzrELfAavXEsLI1FfitlVjv9NIB.jU1HHRdC8", " 28 characters______12345678"},
{"$pbkdf2-sha256$12000$xfj/f6/1PkcIoXROCeE8Bw$ci.FEcPOKKKhX5b3JwzSDo6TGuYjgj1jKfCTZ9UpDM0", " 32 characters______123456789012"},
{"$pbkdf2-sha256$12000$6f3fW8tZq7WWUmptzfmfEw$GDm/yhq1TnNR1MVGy73UngeOg9QJ7DtW4BnmV2F065s", " 40 characters______12345678901234567890"},
{"$pbkdf2-sha256$12000$dU5p7T2ndM7535tzjpGyVg$ILbppLkipmonlfH1I2W3/vFMyr2xvCI8QhksH8DWn/M", " 55 characters______________________________________end"},
{"$pbkdf2-sha256$12000$iDFmDCHE2FtrDaGUEmKMEaL0Xqv1/t/b.x.DcC6lFEI$tUdEcw3csCnsfiYbFdXH6nvbftH8rzvBDl1nABeN0nE", "salt length = 32"},
{"$pbkdf2-sha256$12000$0zoHwNgbIwSAkDImZGwNQUjpHcNYa43xPqd0DuH8H0OIUWqttfY.h5DynvPeG.O8N.Y$.XK4LNIeewI7w9QF5g9p5/NOYMYrApW03bcv/MaD6YQ", "salt length = 50"},
{"$pbkdf2-sha256$12000$HGPMeS9lTAkhROhd653Tuvc.ZyxFSOk9x5gTYgyBEAIAgND6PwfAmA$WdCipc7O/9tTgbpZvcz.mAkIDkdrebVKBUgGbncvoNw", "salt length = 40"},
{"$pbkdf2-sha256$12001$ay2F0No7p1QKgVAqpbQ2hg$UbKdswiLpjc5wT8Zl2M6VlE2cNiKuhAUntGciP8JjPw", "test"},
// cisco type 8 hashes. 20k iterations, different base-64 (same as WPA). Also salt is used RAW, it is not base64 decoded prior to usage
{"$8$dsYGNam3K1SIJO$7nv/35M/qr6t.dVc7UY9zrJDWRVqncHub1PE9UlMQFs", "cisco"},
{"$8$6NHinlEjiwvb5J$RjC.H.ydVb34wDLqJvfjyG1ubxYKpfXqv.Ry9mtrNBY", "password"},
{"$8$lGO8juTOQLPCHw$cBv2WEaFCLUA24Z48CKUGixIywyGFP78r/slQcMXr3M", "JtR"},
{NULL}
};
static struct custom_salt {
uint8_t length;
uint8_t salt[MAX_SALT_SIZE + 3];
uint32_t rounds;
} *cur_salt;
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)];
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc_tiny(sizeof(*saved_key) *
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
crypt_out = mem_calloc_tiny(sizeof(*crypt_out) *
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
}
static char *prepare(char *fields[10], struct fmt_main *self)
{
static char Buf[120];
char tmp[43+3], *cp;
if (strncmp(fields[1], FMT_CISCO8, 3) != 0)
return fields[1];
if (strlen(fields[1]) != 4+14+43)
return fields[1];
sprintf (Buf, "%s20000$%14.14s$%s", FMT_PREFIX, &(fields[1][3]),
base64_convert_cp(&(fields[1][3+14+1]), e_b64_crypt, 43, tmp, e_b64_mime, sizeof(tmp), flg_Base64_NO_FLAGS));
cp = strchr(Buf, '+');
while (cp) {
*cp = '.';
cp = strchr(cp, '+');
}
return Buf;
}
static int valid(char *ciphertext, struct fmt_main *pFmt)
{
int saltlen = 0;
char *p, *c = ciphertext;
if (strncmp(ciphertext, FMT_CISCO8, 3) == 0) {
char *f[10];
f[1] = ciphertext;
ciphertext = prepare(f, pFmt);
}
if (strncmp(ciphertext, FMT_PREFIX, strlen(FMT_PREFIX)) != 0)
return 0;
if (strlen(ciphertext) < 44 + strlen(FMT_PREFIX))
return 0;
c += strlen(FMT_PREFIX);
if (strtol(c, NULL, 10) == 0)
return 0;
c = strchr(c, '$');
if (c == NULL)
return 0;
c++;
p = strchr(c, '$');
if (p == NULL)
return 0;
saltlen = base64_valid_length(c, e_b64_mime, flg_Base64_MIME_PLUS_TO_DOT);
c += saltlen;
saltlen = B64_TO_RAW_LEN(saltlen);
if (saltlen > MAX_SALT_SIZE)
return 0;
if (*c != '$') return 0;
c++;
if (base64_valid_length(c, e_b64_mime, flg_Base64_MIME_PLUS_TO_DOT) != 43)
return 0;
return 1;
}
static void *get_salt(char *ciphertext)
{
static struct custom_salt salt;
char *p, *c = ciphertext;
memset(&salt, 0, sizeof(salt));
c += strlen(FMT_PREFIX);
salt.rounds = strtol(c, NULL, 10);
c = strchr(c, '$') + 1;
p = strchr(c, '$');
if (p-c==14 && salt.rounds==20000) {
// for now, assume this is a cisco8 hash
strnzcpy((char*)(salt.salt), c, 15);
salt.length = 14;
return (void*)&salt;
}
salt.length = base64_convert(c, e_b64_mime, p-c, salt.salt, e_b64_raw, sizeof(salt.salt), flg_Base64_MIME_PLUS_TO_DOT);
return (void *)&salt;
}
static void *get_binary(char *ciphertext)
{
static union {
char c[BINARY_SIZE + 1];
ARCH_WORD dummy;
} buf;
char *ret = buf.c;
char *c = ciphertext;
#if !ARCH_LITTLE_ENDIAN
int i;
#endif
c += strlen(FMT_PREFIX) + 1;
c = strchr(c, '$') + 1;
c = strchr(c, '$') + 1;
#ifdef DEBUG
assert(strlen(c) == 43);
#endif
base64_convert(c, e_b64_mime, 43, buf.c, e_b64_raw, sizeof(buf.c), flg_Base64_MIME_PLUS_TO_DOT);
#if !ARCH_LITTLE_ENDIAN
for (i = 0; i < BINARY_SIZE/4; ++i) {
((ARCH_WORD_32*)ret)[i] = JOHNSWAP(((ARCH_WORD_32*)ret)[i]);
}
#endif
return ret;
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
}
static int get_hash_0(int index) { return crypt_out[index][0] & 0xf; }
static int get_hash_1(int index) { return crypt_out[index][0] & 0xff; }
static int get_hash_2(int index) { return crypt_out[index][0] & 0xfff; }
static int get_hash_3(int index) { return crypt_out[index][0] & 0xffff; }
static int get_hash_4(int index) { return crypt_out[index][0] & 0xfffff; }
static int get_hash_5(int index) { return crypt_out[index][0] & 0xffffff; }
static int get_hash_6(int index) { return crypt_out[index][0] & 0x7ffffff; }
static int crypt_all(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT)
{
#ifdef SSE_GROUP_SZ_SHA256
int lens[SSE_GROUP_SZ_SHA256], i;
unsigned char *pin[SSE_GROUP_SZ_SHA256];
union {
ARCH_WORD_32 *pout[SSE_GROUP_SZ_SHA256];
unsigned char *poutc;
} x;
for (i = 0; i < SSE_GROUP_SZ_SHA256; ++i) {
lens[i] = strlen(saved_key[index+i]);
pin[i] = (unsigned char*)saved_key[index+i];
x.pout[i] = crypt_out[index+i];
}
pbkdf2_sha256_sse((const unsigned char **)pin, lens, cur_salt->salt, cur_salt->length, cur_salt->rounds, &(x.poutc), BINARY_SIZE, 0);
#else
pbkdf2_sha256((const unsigned char*)(saved_key[index]), strlen(saved_key[index]),
cur_salt->salt, cur_salt->length,
cur_salt->rounds, (unsigned char*)crypt_out[index], BINARY_SIZE, 0);
#endif
}
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);
}
/* Check the FULL binary, just for good measure. There is no chance we'll
have a false positive here but this function is not performance sensitive.
This function not done linke pbkdf2_hmac_sha512. Simply return 1.
*/
static int cmp_exact(char *source, int index)
{
return 1;
}
static void set_key(char *key, int index)
{
int saved_key_length = strlen(key);
if (saved_key_length > PLAINTEXT_LENGTH)
saved_key_length = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, saved_key_length);
saved_key[index][saved_key_length] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
#if FMT_MAIN_VERSION > 11
static unsigned int iteration_count(void *salt)
{
struct custom_salt *my_salt;
my_salt = salt;
return (unsigned int) my_salt->rounds;
}
#endif
struct fmt_main fmt_pbkdf2_hmac_sha256 = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
PLAINTEXT_LENGTH,
BINARY_SIZE,
sizeof(ARCH_WORD_32),
SALT_SIZE,
sizeof(ARCH_WORD),
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP,
#if FMT_MAIN_VERSION > 11
{
"iteration count",
},
#endif
tests
}, {
init,
fmt_default_done,
fmt_default_reset,
prepare,
valid,
fmt_default_split,
get_binary,
get_salt,
#if FMT_MAIN_VERSION > 11
{
iteration_count,
},
#endif
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
spmv.h | /*
* Modifications to this file:
* Copyright (c) 2014-2015, The University of Queensland
* Licensed under the Apache License, Version 2.0.
*
*/
#pragma once
#include <thrust/functional.h>
#include <cusp/detail/functional.h>
#ifndef DIA_CHUNKSIZE
#define DIA_CHUNKSIZE 1024
#endif
//MW: add some OpenMP pragmas
namespace cusp
{
namespace detail
{
namespace host
{
//////////////
// COO SpMV //
//////////////
template <typename Matrix,
typename Vector1,
typename Vector2,
typename UnaryFunction,
typename BinaryFunction1,
typename BinaryFunction2>
void spmv_coo(const Matrix& A,
const Vector1& x,
Vector2& y,
UnaryFunction initialize,
BinaryFunction1 combine,
BinaryFunction2 reduce)
{
typedef typename Matrix::index_type IndexType;
typedef typename Vector2::value_type ValueType;
for(size_t i = 0; i < A.num_rows; i++)
y[i] = initialize(y[i]);
for(size_t n = 0; n < A.num_entries; n++)
{
const IndexType& i = A.row_indices[n];
const IndexType& j = A.column_indices[n];
const ValueType& Aij = A.values[n];
const ValueType& xj = x[j];
y[i] = reduce(y[i], combine(Aij, xj));
}
}
template <typename Matrix,
typename Vector1,
typename Vector2>
void spmv_coo(const Matrix& A,
const Vector1& x,
Vector2& y)
{
typedef typename Vector2::value_type ValueType;
spmv_coo(A, x, y,
cusp::detail::zero_function<ValueType>(),
thrust::multiplies<ValueType>(),
thrust::plus<ValueType>());
}
//////////////
// CSR SpMV //
//////////////
template <typename Matrix,
typename Vector1,
typename Vector2,
typename UnaryFunction,
typename BinaryFunction1,
typename BinaryFunction2>
void spmv_csr(const Matrix& A,
const Vector1& x,
Vector2& y,
UnaryFunction initialize,
BinaryFunction1 combine,
BinaryFunction2 reduce)
{
typedef typename Matrix::index_type IndexType;
typedef typename Vector2::value_type ValueType;
#pragma omp parallel for
for(size_t i = 0; i < A.num_rows; i++)
{
const IndexType& row_start = A.row_offsets[i];
const IndexType& row_end = A.row_offsets[i+1];
ValueType accumulator = initialize(y[i]);
for (IndexType jj = row_start; jj < row_end; jj++)
{
const IndexType& j = A.column_indices[jj];
const ValueType& Aij = A.values[jj];
const ValueType& xj = x[j];
accumulator = reduce(accumulator, combine(Aij, xj));
}
y[i] = accumulator;
}
}
template <typename Matrix,
typename Vector1,
typename Vector2>
void spmv_csr(const Matrix& A,
const Vector1& x,
Vector2& y)
{
typedef typename Vector2::value_type ValueType;
spmv_csr(A, x, y,
cusp::detail::zero_function<ValueType>(),
thrust::multiplies<ValueType>(),
thrust::plus<ValueType>());
}
//////////////
// DIA SpMV //
//////////////
template <typename Matrix,
typename Vector1,
typename Vector2,
typename UnaryFunction,
typename BinaryFunction1,
typename BinaryFunction2>
void spmv_dia(const Matrix& A,
const Vector1& x,
Vector2& y,
UnaryFunction initialize,
BinaryFunction1 combine,
BinaryFunction2 reduce)
{
typedef typename Matrix::index_type IndexType;
//typedef typename Vector2::value_type ValueType;
const size_t num_diagonals = A.values.num_cols;
if (A.symmetric) {
// if matrix has a main diagonal it is the first in offsets and should
// be skipped in the subdiagonal loop below. The main diagonal is
// processed by the second loop
const size_t d0 = (A.diagonal_offsets[0] == 0 ? 1 : 0);
#pragma omp parallel for
for (size_t ch = 0; ch < A.num_rows; ch += DIA_CHUNKSIZE) {
// initialize chunk
for (size_t row = ch; row < std::min(ch+DIA_CHUNKSIZE,A.num_rows); row++)
{
y[row] = initialize(y[row]);
}
// process subdiagonals
for (size_t d = 0; d < num_diagonals-d0; d++)
{
const size_t diag = num_diagonals-d-1;
for (size_t row = ch; row < std::min(ch+DIA_CHUNKSIZE,A.num_rows); row++)
{
const IndexType col = row - A.diagonal_offsets[diag];
if (col >= 0 && col < A.num_rows)
{
y[row] = reduce(y[row], combine(A.values(col, diag), x[col]));
}
}
}
// process main and upper diagonals
for (size_t d = 0; d < num_diagonals; d++)
{
for (size_t row = ch; row < std::min(ch+DIA_CHUNKSIZE,A.num_rows); row++)
{
const IndexType col = row + A.diagonal_offsets[d];
if (col >= 0 && col < A.num_cols)
{
y[row] = reduce(y[row], combine(A.values(row, d), x[col]));
}
}
}
}
} else { // !A.symmetric
#pragma omp parallel for
for (size_t ch = 0; ch < A.num_rows; ch += DIA_CHUNKSIZE) {
// initialize chunk
for (size_t row = ch; row < std::min(ch+DIA_CHUNKSIZE,A.num_rows); row++)
{
y[row] = initialize(y[row]);
}
// for each diagonal
for (size_t d = 0; d < num_diagonals; d++)
{
for (IndexType row=ch; row<std::min(ch+DIA_CHUNKSIZE,A.num_rows); row++)
{
const IndexType col = row + A.diagonal_offsets[d];
if (col >= 0 && col < A.num_cols)
{
y[row] = reduce(y[row], combine(A.values(row, d), x[col]));
}
}
}
}
}
}
template <typename Matrix,
typename Vector1,
typename Vector2>
void spmv_dia(const Matrix& A,
const Vector1& x,
Vector2& y)
{
typedef typename Vector2::value_type ValueType;
spmv_dia(A, x, y,
cusp::detail::zero_function<ValueType>(),
thrust::multiplies<ValueType>(),
thrust::plus<ValueType>());
}
//////////////
// CDS SpMV //
//////////////
template <typename Matrix,
typename Vector1,
typename Vector2,
typename UnaryFunction,
typename BinaryFunction1,
typename BinaryFunction2>
void spmv_cds(const Matrix& A,
const Vector1& x,
Vector2& y,
UnaryFunction initialize,
BinaryFunction1 combine,
BinaryFunction2 reduce)
{
typedef typename Matrix::index_type IndexType;
typedef typename Vector2::value_type ValueType;
const IndexType num_diagonals = A.diagonal_offsets.size();
const IndexType block_size = (IndexType)A.block_size;
const IndexType num_rows = (IndexType)A.num_rows;
// make chunksize a multiple of block_size
const IndexType chunksize = block_size*(DIA_CHUNKSIZE/block_size);
// optimization for special case
if (block_size == 2) {
if (A.symmetric) {
// if there is a main diagonal block, it is the first in offsets
// and should be skipped in the first loop below since the main
// diagonal is processed in the second loop
const IndexType d0 = (A.diagonal_offsets[0] == 0 ? 1 : 0);
#pragma omp parallel for
for (IndexType ch = 0; ch < num_rows; ch+=chunksize)
{
for (IndexType row = ch; row<std::min(ch+chunksize,num_rows); row++)
{
y[row] = initialize(y[row]);
}
// process subdiagonal blocks
for (IndexType d = 0; d < num_diagonals-d0; d++)
{
const IndexType diag = num_diagonals-d-1;
const IndexType k = -2*A.diagonal_offsets[diag];
for (IndexType row = ch; row<std::min(ch+chunksize,num_rows); row+=2)
{
const IndexType col = row + k;
if (col >= 0 && col <= num_rows-2)
{
y[row] = reduce(y[row], combine(A.values(col, 2*diag), x[col]));
y[row] = reduce(y[row], combine(A.values(col+1,2*diag), x[col+1]));
y[row+1] = reduce(y[row+1],combine(A.values(col, 2*diag+1),x[col]));
y[row+1] = reduce(y[row+1],combine(A.values(col+1,2*diag+1),x[col+1]));
}
}
}
// process main and upper diagonal blocks
for (IndexType d = 0; d < num_diagonals; d++)
{
const IndexType k = 2*A.diagonal_offsets[d];
for (IndexType row = ch; row<std::min(ch+chunksize,num_rows); row+=2)
{
const IndexType col = row + k;
if (col >= 0 && col <= num_rows-2)
{
y[row] = reduce(y[row], combine(A.values(row, 2*d), x[col]));
y[row+1] = reduce(y[row+1],combine(A.values(row+1,2*d), x[col]));
y[row] = reduce(y[row], combine(A.values(row, 2*d+1),x[col+1]));
y[row+1] = reduce(y[row+1],combine(A.values(row+1,2*d+1),x[col+1]));
}
}
}
}
} else { // !A.symmetric
#pragma omp parallel for
for (IndexType ch = 0; ch < num_rows; ch+=chunksize)
{
for (IndexType row = ch; row<std::min(ch+chunksize,num_rows); row+=2)
{
ValueType sum1 = initialize(y[row]);
ValueType sum2 = initialize(y[row+1]);
// for each diagonal block
for (IndexType d = 0; d < num_diagonals; d++)
{
const IndexType col = row + A.diagonal_offsets[d]*2;
if (col >= 0 && col <= num_rows-2)
{
sum1 = reduce(sum1,combine(A.values(row, 2*d), x[col]));
sum2 = reduce(sum2,combine(A.values(row+1,2*d), x[col]));
sum1 = reduce(sum1,combine(A.values(row, 2*d+1),x[col+1]));
sum2 = reduce(sum2,combine(A.values(row+1,2*d+1),x[col+1]));
}
}
y[row] = sum1;
y[row+1] = sum2;
}
}
} // A.symmetric
} else { // block size
if (A.symmetric) {
// if there is a main diagonal block, it is the first in offsets
// and should be skipped in the first loop below since the main
// diagonal is processed in the second loop
const IndexType d0 = (A.diagonal_offsets[0] == 0 ? 1 : 0);
const ValueType* values = thrust::raw_pointer_cast(&A.values.values[0]);
const IndexType pitch = A.values.pitch;
#pragma omp parallel for
for (IndexType ch = 0; ch < num_rows; ch+=chunksize)
{
for (IndexType row = ch; row<std::min(ch+chunksize,num_rows); row++)
{
y[row] = initialize(y[row]);
}
IndexType idx = pitch*block_size*(num_diagonals-1);
// process subdiagonal blocks
for (IndexType d = 0; d < num_diagonals-d0; d++)
{
const IndexType diag = num_diagonals-d-1;
const IndexType k = -block_size*A.diagonal_offsets[diag];
for (IndexType row = ch; row<std::min(ch+chunksize,num_rows); row+=block_size)
{
const IndexType col = row + k;
if (col >= 0 && col <= num_rows-block_size)
{
// for each row in block
for (IndexType j = 0; j < block_size; j++)
{
// for each column in block
for (IndexType i = 0; i < block_size; i++)
{
const ValueType& Aij = values[idx+col+i+j*pitch];
const ValueType& xj = x[col + i];
y[row+j] = reduce(y[row+j], combine(Aij, xj));
}
}
}
}
idx -= block_size*pitch;
}
// process main and upper diagonal blocks
for (IndexType d = 0; d < num_diagonals; d++)
{
const IndexType k = A.diagonal_offsets[d]*block_size;
for (IndexType row = ch; row<std::min(ch+chunksize,num_rows); row+=block_size)
{
const IndexType col = row + k;
if (col >= 0 && col <= num_rows-block_size)
{
// for each column in block
for (IndexType i = 0; i < block_size; i++)
{
// for each row in block
for (IndexType j = 0; j < block_size; j++)
{
const ValueType& Aij = values[row+j+(d*block_size+i)*pitch];
const ValueType& xj = x[col + i];
y[row+j] = reduce(y[row+j], combine(Aij, xj));
}
}
}
}
} // diagonals
}
} else { // !A.symmetric
#pragma omp parallel for
for (IndexType ch = 0; ch < num_rows; ch+=chunksize)
{
for (IndexType row = ch; row<std::min(ch+chunksize,num_rows); row++)
{
y[row] = initialize(y[row]);
}
// for each diagonal block
for (IndexType d = 0; d < num_diagonals; d++)
{
const IndexType k = A.diagonal_offsets[d]*block_size;
for (IndexType row=ch; row<std::min(ch+chunksize,num_rows); row+=block_size)
{
const IndexType col = row + k;
if (col >= 0 && col <= num_rows-block_size)
{
// for each column in block
for (IndexType i = 0; i < block_size; i++)
{
// for each row in block
for (IndexType j = 0; j < block_size; j++)
{
const ValueType& Aij = A.values(row+j, d*block_size+i);
const ValueType& xj = x[col + i];
y[row+j] = reduce(y[row+j], combine(Aij, xj));
}
}
}
}
} // diagonals
} // row chunks
} // A.symmetric
} // block size
}
template <typename Matrix,
typename Vector1,
typename Vector2>
void spmv_cds(const Matrix& A,
const Vector1& x,
Vector2& y)
{
typedef typename Vector2::value_type ValueType;
if (A.block_size == 1) {
spmv_dia(A, x, y,
cusp::detail::zero_function<ValueType>(),
thrust::multiplies<ValueType>(),
thrust::plus<ValueType>());
} else {
spmv_cds(A, x, y,
cusp::detail::zero_function<ValueType>(),
thrust::multiplies<ValueType>(),
thrust::plus<ValueType>());
}
}
//////////////
// ELL SpMV //
//////////////
template <typename Matrix,
typename Vector1,
typename Vector2,
typename UnaryFunction,
typename BinaryFunction1,
typename BinaryFunction2>
void spmv_ell(const Matrix& A,
const Vector1& x,
Vector2& y,
UnaryFunction initialize,
BinaryFunction1 combine,
BinaryFunction2 reduce)
{
typedef typename Matrix::index_type IndexType;
typedef typename Vector2::value_type ValueType;
const size_t& num_entries_per_row = A.column_indices.num_cols;
const IndexType invalid_index = Matrix::invalid_index;
for(size_t i = 0; i < A.num_rows; i++)
y[i] = initialize(y[i]);
for(size_t n = 0; n < num_entries_per_row; n++)
{
for(size_t i = 0; i < A.num_rows; i++)
{
const IndexType& j = A.column_indices(i, n);
const ValueType& Aij = A.values(i,n);
if (j != invalid_index)
{
const ValueType& xj = x[j];
y[i] = reduce(y[i], combine(Aij, xj));
}
}
}
}
template <typename Matrix,
typename Vector1,
typename Vector2>
void spmv_ell(const Matrix& A,
const Vector1& x,
Vector2& y)
{
typedef typename Vector2::value_type ValueType;
spmv_ell(A, x, y,
cusp::detail::zero_function<ValueType>(),
thrust::multiplies<ValueType>(),
thrust::plus<ValueType>());
}
} // end namespace host
} // end namespace detail
} // end namespace cusp
|
induced_hybrid.h | #pragma once
/* TODO: describe what this file does */
#include "intersect.h"
#include "pbbslib/seq.h"
namespace induced_hybrid {
template<class Graph>
size_t get_max_deg(Graph& DG) {
size_t max_deg = 0;
parallel_for(0, DG.n, [&] (size_t i) {
size_t deg = DG.get_vertex(i).getOutDegree();
pbbs::write_min(&max_deg, deg, std::greater<size_t>());
});
return max_deg;
}
template <class Graph, class F>
inline size_t KCliqueDir_fast_hybrid_rec(Graph& DG, size_t k_idx, size_t k, HybridSpace_lw* induced, F base_f) {
//if (k == 2) return induced->num_edges;
size_t num_induced = induced->num_induced[k_idx-1];
if (num_induced == 0) return 0;
uintE* prev_induced = induced->induced + induced->nn * (k_idx - 1);
for (size_t i=0; i < num_induced; i++) { induced->labels[prev_induced[i]] = k_idx; }
if (k_idx + 1 == k) {
size_t counts = 0;
for (size_t i=0; i < num_induced; i++) {
uintE vtx = prev_induced[i];
// get neighbors of vtx
uintE* intersect = induced->induced_edges + vtx * induced->nn;
size_t tmp_counts = 0;
for (size_t j=0; j < induced->induced_degs[vtx]; j++) {
if (induced->labels[intersect[j]] == k_idx) {
tmp_counts++;
if (induced->use_base) base_f(induced->relabel[intersect[j]], 1);
}
}
if (induced->use_base) base_f(induced->relabel[vtx], tmp_counts);
counts += tmp_counts;
}
for (size_t i=0; i < num_induced; i++) { induced->labels[prev_induced[i]] = k_idx - 1; }
return counts;
}
size_t total_ct = 0;
for (size_t i=0; i < num_induced; ++i) {
uintE vtx = prev_induced[i];
//if (induced->use_base) induced->base[k_idx] = induced->relabel[vtx]; // TODO problem w/storing base -- we've relabeled our vert w/relabeling: check base is correct
uintE* intersect = induced->induced_edges + vtx * induced->nn;
uintE* out = induced->induced + induced->num_induced[0] * k_idx;
uintE count = 0;
for (size_t j=0; j < induced->induced_degs[vtx]; j++) {
if (induced->labels[intersect[j]] == k_idx) {
out[count] = intersect[j];
count++;
}
}
induced->num_induced[k_idx] = count;
if (induced->num_induced[k_idx] > k - k_idx - 1) {
auto curr_counts = KCliqueDir_fast_hybrid_rec(DG, k_idx + 1, k, induced, base_f);
total_ct += curr_counts;
if (induced->use_base) base_f(induced->relabel[vtx], curr_counts);
}
}
for (size_t i=0; i < num_induced; i++) { induced->labels[prev_induced[i]] = k_idx - 1; }
return total_ct;
}
/*template <class Graph>
inline size_t CountCliques_unbalanced(Graph& DG, size_t k) {
sequence<size_t> tots = sequence<size_t>::no_init(DG.n);
size_t max_deg = get_max_deg(DG);
auto init_induced = [&](HybridSpace_lw* induced) { induced->alloc(max_deg, k, DG.n); };
auto finish_induced = [&](HybridSpace_lw* induced) { if (induced != nullptr) { delete induced; } }; //induced->del();
parallel_for_alloc<HybridSpace_lw>(init_induced, finish_induced, 0, DG.n, [&](size_t i, HybridSpace_lw* induced) {
if (DG.get_vertex(i).getOutDegree() != 0) {
induced->setup(DG, k, i);
tots[i] = KCliqueDir_fast_hybrid_rec(DG, 1, k, induced);
} else tots[i] = 0;
} );
return pbbslib::reduce_add(tots);
}*/
template <class Graph, class F>
inline size_t CountCliques(Graph& DG, size_t k, F base_f, bool use_base=false, bool label=true) {
timer t; t.start();
using W = typename Graph::weight_type;
auto parallel_work = sequence<size_t>(DG.n);
{
auto map_f = [&](uintE u, uintE v, W wgh) -> size_t {
return DG.get_vertex(v).getOutDegree();
};
par_for(0, DG.n, [&] (size_t i) {
auto monoid = pbbslib::addm<size_t>();
parallel_work[i] = DG.get_vertex(i).template reduceOutNgh<size_t>(i, map_f, monoid);
});
}
size_t total_work = pbbslib::scan_add_inplace(parallel_work.slice());
size_t block_size = 50000;
size_t n_blocks = total_work/block_size + 1;
size_t work_per_block = total_work / n_blocks;
n_blocks = (total_work/work_per_block) + 1;
double tt = t.stop();
std::cout << "##### Triangle scheduling: " << tt << std::endl;
timer t2; t2.start();
sequence<size_t> tots = sequence<size_t>::no_init(n_blocks); //DG.n
size_t max_deg = get_max_deg(DG);
auto init_induced = [&](HybridSpace_lw* induced) { induced->alloc(max_deg, k, DG.n, label, use_base); };
auto finish_induced = [&](HybridSpace_lw* induced) { if (induced != nullptr) { delete induced; } }; //induced->del();
parallel_for_alloc<HybridSpace_lw>(init_induced, finish_induced, 0, n_blocks, [&](size_t j, HybridSpace_lw* induced) {
size_t start = j * work_per_block;
size_t end = (j + 1) * work_per_block;
auto less_fn = std::less<size_t>();
size_t start_ind = pbbslib::binary_search(parallel_work, start, less_fn);
size_t end_ind = pbbslib::binary_search(parallel_work, end, less_fn);
tots[j] = 0;
for (size_t i=start_ind; i < end_ind; i++) {
if (DG.get_vertex(i).getOutDegree() != 0) {
induced->setup(DG, k, i);
auto curr_counts = KCliqueDir_fast_hybrid_rec(DG, 1, k, induced, base_f);
tots[j] += curr_counts;
if (induced->use_base) base_f(i, curr_counts);
}
}
}, 1, false);
double tt2 = t2.stop();
std::cout << "##### Actual counting: " << tt2 << std::endl;
/*sequence<size_t> tots = sequence<size_t>::no_init(DG.n);
size_t max_deg = get_max_deg(DG);
auto init_induced = [&](HybridSpace_lw* induced) { induced->alloc(max_deg, k, DG.n); };
auto finish_induced = [&](HybridSpace_lw* induced) { if (induced != nullptr) { delete induced; } }; //induced->del();
parallel_for_alloc<HybridSpace_lw>(init_induced, finish_induced, 0, DG.n, [&](size_t i, HybridSpace_lw* induced) {
if (DG.get_vertex(i).getOutDegree() != 0) {
induced->setup(DG, k, i);
tots[i] = KCliqueDir_fast_hybrid_rec(DG, 1, k, induced);
} else tots[i] = 0;
}, 1, false);*/
/*
#pragma omp parallel private(induced) reduction(+:n)
{
induced = new HybridSpace_lw(max_deg, k);
#pragma omp for schedule(dynamic, 1) nowait
for (size_t i=0; i < DG.n; ++i) {
if (DG.get_vertex(i).getOutDegree() != 0) {
induced->setup(DG, k, i);
n += KCliqueDir_fast_hybrid_rec(DG, 1, k, induced);
}
}
if (induced != nullptr) { induced->del(); delete induced; }
}*/
return pbbslib::reduce_add(tots);
}
} // namespace induced_neighborhood
|
fwk_render.h | // naive rendering framework
// - rlyeh, public domain
//
// IQM skeletal meshes by @lsalzman (public domain) - https://bit.ly/2OQh0Me
// SH code by @ands (public domain) - https://github.com/ands/spherical_harmonics_playground
#ifndef RENDER_H
#define RENDER_H
typedef unsigned handle; // GLuint
// -----------------------------------------------------------------------------
// colors
uint32_t rgba( uint8_t r, uint8_t g, uint8_t b, uint8_t a );
float alpha( uint32_t rgba );
#define RGB_HEX(rgb) (255<<24|((0x##rgb>>16)&255)<<16|((0x##rgb>>8)&255)<<8|((0x##rgb>>0)&255)<<0)
#define BLACK RGB_HEX(000000)
#define RED RGB_HEX(FF004D)
#define GREEN RGB_HEX(00B543)
#define BLUE RGB_HEX(065AB5)
#define ORANGE RGB_HEX(FF6C24)
#define PURPLE RGB_HEX(7E2553)
#define YELLOW RGB_HEX(FFEC27)
#define WHITE RGB_HEX(FFF1E8)
#define GRAY RGB_HEX(725158)
// -----------------------------------------------------------------------------
// images
enum {
IMAGE_R = 0x01000,
IMAGE_RG = 0x02000,
IMAGE_RGB = 0x04000,
IMAGE_RGBA = 0x08000,
IMAGE_FLIP = 0x10000,
};
typedef struct image_t {
union { unsigned x, w; };
union { unsigned y, h; };
union { unsigned n, comps; };
union { void *pixels; unsigned char *pixels8; unsigned short *pixels16; unsigned *pixels32; float *pixelsf; };
} image_t;
image_t image(const char *pathfile, int flags);
image_t image_from_mem(const char *ptr, int len, int flags);
void image_destroy(image_t *img);
// -----------------------------------------------------------------------------
// textures
enum {
// UNIT[0..7]
TEXTURE_BC1 = 8, // DXT1, RGB with 8:1 compression ratio (+ optional 1bpp for alpha)
TEXTURE_BC2 = 16, // DXT3, RGBA with 4:1 compression ratio (BC1 for RGB + 4bpp for alpha)
TEXTURE_BC3 = 32, // DXT5, RGBA with 4:1 compression ratio (BC1 for RGB + BC4 for A)
// TEXTURE_BC4, // Alpha
TEXTURE_NEAREST = 0,
TEXTURE_LINEAR = 64,
TEXTURE_MIPMAPS = 128,
TEXTURE_EDGE = 0,
TEXTURE_BORDER = 0x100,
TEXTURE_REPEAT = 0x200,
TEXTURE_BYTE = 0,
TEXTURE_FLOAT = 0x400,
TEXTURE_COLOR = 0,
TEXTURE_DEPTH = 0x800,
TEXTURE_R = IMAGE_R,
TEXTURE_RG = IMAGE_RG,
TEXTURE_RGB = IMAGE_RGB,
TEXTURE_RGBA = IMAGE_RGBA,
TEXTURE_FLIP = IMAGE_FLIP,
// @fixme
TEXTURE_SRGB = 1 << 24,
TEXTURE_BGR = 1 << 25,
TEXTURE_ARRAY = 1 << 26,
};
typedef struct {
union { unsigned x, w; };
union { unsigned y, h; };
union { unsigned n, bpp; };
handle id;
unsigned flags;
} texture_t;
texture_t texture(const char* filename, int flags);
texture_t texture_from_mem(const char* ptr, int len, int flags);
texture_t texture_create(unsigned w, unsigned h, unsigned n, void *pixels, int flags);
texture_t texture_checker();
void texture_destroy(texture_t *t);
// textureLod(filename, dir, lod);
//void texture_add_loader( int(*loader)(const char *filename, int *w, int *h, int *bpp, int reqbpp, int flags) );
unsigned texture_update(texture_t *t, unsigned w, unsigned h, unsigned n, void *pixels, int flags);
// -----------------------------------------------------------------------------
// fullscreen quads
void fullscreen_rgb_quad( texture_t texture_rgb, float gamma );
void fullscreen_ycbcr_quad( texture_t texture_YCbCr[3], float gamma );
// -----------------------------------------------------------------------------
// sprites
void sprite( texture_t texture, float px, float py, float pz, float rot );
void sprite_ex( texture_t texture,
float px, float py, float pz, float rotation, // position(x,y,depth sort), angle
float ox, float oy, float sx, float sy, // offset(x,y), scale(x,y)
int additive, uint32_t rgba, // is_additive, tint color
float frame, float xcells, float ycells // frame_number in a 8x4 spritesheet
);
// -----------------------------------------------------------------------------
// cubemaps
typedef struct cubemap_t {
unsigned id; // texture id
vec3 sh[9]; // precomputed spherical harmonics coefficients
} cubemap_t;
cubemap_t cubemap( const image_t image, int flags ); // 1 equirectangular panorama
cubemap_t cubemap6( const image_t images[6], int flags ); // 6 cubemap faces
void cubemap_destroy(cubemap_t *c);
cubemap_t* cubemap_get_active();
// -----------------------------------------------------------------------------
// fbos
unsigned fbo( unsigned texture_color, unsigned texture_depth, int wr_flags );
void fbo_bind(unsigned id);
void fbo_unbind();
void fbo_destroy(unsigned id);
// -----------------------------------------------------------------------------
// shadowmaps
unsigned shadowmap(unsigned w, unsigned h, int flags);
// -----------------------------------------------------------------------------
// shaders
unsigned shader(const char *vs, const char *fs, const char *attribs, const char *fragcolor);
unsigned shader_bind(unsigned program);
void shader_int(const char *uniform, int i);
void shader_float(const char *uniform, float f);
void shader_vec2(const char *uniform, vec2 v);
void shader_vec3(const char *uniform, vec3 v);
void shader_vec4(const char *uniform, vec4 v);
void shader_mat44(const char *uniform, mat44 m);
void shader_texture(const char *sampler, unsigned texture, unsigned unit);
unsigned shader_get_active();
void shader_destroy(unsigned shader);
// -----------------------------------------------------------------------------
// meshes (@fixme: deprecate?)
enum MESH_FLAGS {
MESH_STATIC = 0, // STATIC, DYNAMIC, STREAM // zero|single|many updates per frame
MESH_STREAM = 1,
MESH_TRIANGLE_STRIP = 2,
};
typedef struct mesh_t {
handle vao, vbo, ibo;
unsigned vertex_count;
unsigned index_count;
unsigned flags;
} mesh_t;
mesh_t mesh_create(const char *format, int vertex_stride,int vertex_count,const void *interleaved_vertex_data, int index_count,const void *index_data, int flags);
void mesh_upgrade(mesh_t *m, const char *format, int vertex_stride,int vertex_count,const void *interleaved_vertex_data, int index_count,const void *index_data, int flags);
void mesh_push_state(mesh_t *m, unsigned program, unsigned texture_id, float model[16], float view[16], float proj[16], unsigned billboard);
void mesh_pop_state(mesh_t *m);
void mesh_render(mesh_t *m);
void mesh_destroy(mesh_t *m);
aabb mesh_bounds(mesh_t *m);
// -----------------------------------------------------------------------------
// materials (@todo)
//
// typedef struct material_t {
// const char *name;
// texture_t texture;
// uint32_t color;
// } material_t;
// -----------------------------------------------------------------------------
// models
enum {
MODEL_NO_ANIMATIONS = 1,
MODEL_NO_MESHES = 2,
MODEL_NO_TEXTURES = 4,
};
typedef struct model_t {
struct iqm_t *iqm;
unsigned num_meshes;
unsigned num_triangles;
unsigned num_joints; // num_poses;
unsigned num_anims;
unsigned num_frames;
float curframe;
mat44 pivot;
} model_t;
model_t model(const char *filename, int flags);
model_t model_from_mem(const void *mem, int sz, int flags);
float model_animate(model_t, float curframe);
float model_animate_clip(model_t, float curframe, int minframe, int maxframe, bool loop);
aabb model_aabb(model_t, mat44 transform);
void model_render(model_t, mat44 mvp);
void model_destroy(model_t);
// -----------------------------------------------------------------------------
// skyboxes
typedef struct skybox_t {
handle program;
mesh_t geometry;
cubemap_t cubemap;
} skybox_t;
skybox_t skybox(const char *panorama_or_cubemap_folder, int flags);
int skybox_push_state(skybox_t *sky, float mvp[16]);
int skybox_pop_state(skybox_t *sky);
void skybox_destroy(skybox_t *sky);
// -----------------------------------------------------------------------------
// post-processes
void viewport_color(vec3 color);
void viewport_clear(bool color, bool depth);
void viewport_clip(vec2 from, vec2 to);
void fx_load(const char *file);
void fx_begin();
void fx_end();
void fx_enable(int pass, int enabled);
int fx_enabled(int pass);
void fx_enable_all(int enabled);
char * fx_name(int pass);
// -----------------------------------------------------------------------------
// utils
void* screenshot(unsigned components); // 3 RGB, -3 BGR, 4 RGBA, -4 BGRA
#endif
#ifdef RENDER_C
#pragma once
// -----------------------------------------------------------------------------
// opengl
#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
#define GL_DEBUG_SEVERITY_HIGH 0x9146
#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B
#define GL_DEBUG_SOURCE_API 0x8246
#define GL_DEBUG_TYPE_ERROR 0x824C
//
void glDebugCallback(uint32_t source, uint32_t type, uint32_t id, uint32_t severity, int32_t length, const char * message, void * userdata) {
// whitelisted codes (also: 131169, 131204).
if( id == 131154 ) return; // Pixel-path performance warning: Pixel transfer is synchronized with 3D rendering.
if( id == 131185 ) return; // Buffer object 2 (bound to GL_ELEMENT_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations
if( id == 131218 ) return; // Program/shader state performance warning: Vertex shader in program 9 is being recompiled based on GL state.
if( id == 2 ) return; // INFO: API_ID_RECOMPILE_FRAGMENT_SHADER performance warning has been generated. Fragment shader recompiled due to state change. [ID: 2]
const char * GL_ERROR_SOURCE[] = { "API", "WINDOW SYSTEM", "SHADER COMPILER", "THIRD PARTY", "APPLICATION", "OTHER" };
const char * GL_ERROR_SEVERITY[] = { "HIGH", "MEDIUM", "LOW", "NOTIFICATION" };
const char * GL_ERROR_TYPE[] = { "ERROR", "DEPRECATED BEHAVIOR", "UNDEFINED DEHAVIOUR", "PORTABILITY", "PERFORMANCE", "OTHER" };
severity = severity == GL_DEBUG_SEVERITY_NOTIFICATION ? 3 : severity - GL_DEBUG_SEVERITY_HIGH;
source = source - GL_DEBUG_SOURCE_API;
type = type - GL_DEBUG_TYPE_ERROR;
PRINTF( "!%s [ID: %u]\n", message, id );
// PANIC( "!%s [ID: %u]\n", message, id );
}
void glDebugEnable() {
ONCE {
typedef void (*GLDEBUGPROC)(uint32_t, uint32_t, uint32_t, uint32_t, int32_t, const char *, const void *);
typedef void (*GLDEBUGMESSAGECALLBACKPROC)(GLDEBUGPROC, const void *);
void (*glDebugMessageCallback)(GLDEBUGPROC, const void *) = (GLDEBUGMESSAGECALLBACKPROC)glfwGetProcAddress("glDebugMessageCallback");
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
glDebugMessageCallback((GLDEBUGPROC)glDebugCallback, NULL);
}
}
void glNewFrame() {
glViewport(0, 0, window_width(), window_height());
//glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
}
// ----------------------------------------------------------------------------
// embedded shaders (@fixme: promote to files?)
static const char* const vertex_shader_332_32 =
""
//"uniform mat4 u_model, u_view, u_proj;\n"
"uniform mat4 u_mvp;\n"
"in vec3 att_position;\n"
"in vec3 att_normal;\n"
"in vec2 att_texcoord;\n"
"out vec3 v_normal;\n"
"out vec2 v_texcoord;\n"
"void main() {\n"
//" gl_Position = proj * view * model * vec4(att_position, 1.0);\n"
" gl_Position = u_mvp * vec4(att_position, 1.0);\n"
" v_normal = att_normal;\n"
" v_texcoord = att_texcoord;\n"
"}";
static const char* const fragment_shader_32_4 =
""
"uniform mat4 M;\n"
"uniform sampler2D u_texture2d;\n"
"uniform vec3 u_coefficients_sh[9];\n"
"uniform bool u_textured = true;\n"
"uniform bool u_lit = false;\n"
"#ifdef RIM\n"
"in vec3 v_position;\n"
"#endif\n"
"in vec3 v_normal;\n"
"in vec2 v_texcoord;\n"
"out vec4 fragcolor;\n"
"void main() {\n"
" vec3 n = /*normalize*/(v_normal);\n"
" vec3 SHLightResult[9];\n"
" SHLightResult[0] = 0.282095f * u_coefficients_sh[0];\n"
" SHLightResult[1] = -0.488603f * u_coefficients_sh[1] * n.y;\n"
" SHLightResult[2] = 0.488603f * u_coefficients_sh[2] * n.z;\n"
" SHLightResult[3] = -0.488603f * u_coefficients_sh[3] * n.x;\n"
" SHLightResult[4] = 1.092548f * u_coefficients_sh[4] * n.x * n.y;\n"
" SHLightResult[5] = -1.092548f * u_coefficients_sh[5] * n.y * n.z;\n"
" SHLightResult[6] = 0.315392f * u_coefficients_sh[6] * (3.0f * n.z * n.z - 1.0f);\n"
" SHLightResult[7] = -1.092548f * u_coefficients_sh[7] * n.x * n.z;\n"
" SHLightResult[8] = 0.546274f * u_coefficients_sh[8] * (n.x * n.x - n.y * n.y);\n"
" vec3 result = vec3(0.0);\n"
" for (int i = 0; i < 9; ++i)\n"
" result += SHLightResult[i];\n"
// lighting
" if(u_textured && u_lit) fragcolor = texture(u_texture2d, v_texcoord) * vec4(result, 1.0);\n" // diffuse + lit
" else if(u_textured) fragcolor = texture(u_texture2d, v_texcoord);\n" // diffuse only
" else fragcolor = vec4(result, 1.0);\n" // lit only
// rimlight
"#ifdef RIM\n"
" {vec3 n = normalize(mat3(M) * v_normal); // convert normal to view space\n"
" vec3 p = (M * vec4(v_position,1.0)).xyz; // convert position to view space\n"
" vec3 v = normalize(-p); // eye vector\n"
" float rim = 1.0 - max(dot(v, n), 0.0); // rimlight\n"
" rim = smoothstep(1.0-0.01, 1.0, rim); // intensity (0.01)\n"
" fragcolor += vec4(0.0, 0.0, rim, 1.0);} // blue\n"
"#endif\n"
"}\n";
static const char * const skybox_vs_3_3 =
""
"uniform mat4 u_mvp;\n"
"in vec3 att_position;\n"
"out vec3 v_direction;\n"
"void main() {\n"
" vec4 position = u_mvp * vec4(att_position, 0.0);\n"
" gl_Position = position.xyww;\n"
" v_direction = att_position;\n"
"}\n";
static const char * const skybox_fs_3_4 =
""
"uniform samplerCube u_cubemap;\n"
"in vec3 v_direction;\n"
"out vec4 fragcolor;\n"
"void main() {\n"
" fragcolor = vec4(texture(u_cubemap, v_direction).rgb, 1.0);\n"
"}\n";
// ----------------------------------------------------------------------------
// shaders
void shader_print(const char *source) {
for(int line = 0, i = 0; source[i] > 0; ) {
printf("\t%03d: ", line+1);
while( source[i] >= 32 || source[i] == '\t' ) fputc(source[i++], stdout);
while( source[i] > 0 && source[i] < 32 ) line += source[i++] == '\n';
puts("");
}
}
static
GLuint shader_compile( GLenum type, const char *source ) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, (const char **)&source, NULL);
glCompileShader(shader);
GLint status = GL_FALSE, length;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if( status == GL_FALSE ) {
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
ASSERT(length < 2048);
char buf[2048] = { 0 };
glGetShaderInfoLog(shader, length, NULL, buf);
// dump log with line numbers
shader_print( source );
PANIC("ERROR: shader_compile(): %s\n%s\n", type == GL_VERTEX_SHADER ? "Vertex" : "Fragment", buf);
return 0;
}
return shader;
}
unsigned shader(const char *vs, const char *fs, const char *attribs, const char *fragcolor) {
PRINTF("Compiling shader\n");
fs = fs[0] == '#' && fs[1] == 'v' ? fs : stringf("#version 130\n%s", fs);
vs = vs[0] == '#' && vs[1] == 'v' ? vs : stringf("#version 130\n%s", vs);
GLuint vert = shader_compile(GL_VERTEX_SHADER, vs);
GLuint frag = shader_compile(GL_FRAGMENT_SHADER, fs);
//GLuint geom = shader_compile(GL_GEOMETRY_SHADER, gs);
GLuint program = 0;
if( vert && frag ) {
program = glCreateProgram();
glAttachShader(program, vert);
glAttachShader(program, frag);
// glAttachShader(program, geom);
for( int i = 0; attribs && attribs[0]; ++i ) {
char attrib[128] = {0};
sscanf(attribs, "%127[^,]", attrib);
while( attribs[0] && attribs[0] != ',' ) { attribs++; }
while( attribs[0] && attribs[0] == ',' ) { attribs++; break; }
if(!attrib[0]) continue;
glBindAttribLocation(program, i, attrib);
PRINTF("Shader.attribute[%d]=%s\n", i, attrib);
}
glBindFragDataLocation(program, 0, fragcolor);
glLinkProgram(program);
GLint status = GL_FALSE, length;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
ASSERT(length < 2048);
char buf[2048] = { 0 };
glGetProgramInfoLog(program, length, NULL, buf);
shader_print(vs);
shader_print(fs);
PANIC("ERROR: shader(): Shader/program link: %s\n", buf);
return 0;
}
// glDetachShader(program, vert);
// glDetachShader(program, frag);
// glDetachShader(program, geom);
glDeleteShader(vert);
glDeleteShader(frag);
// glDeleteShader(geom);
#ifdef DEBUG_SHADER
PRINTF("Shader #%d:\n", program);
shader_print(vs);
shader_print(fs);
#endif
}
return program;
}
void shader_destroy(unsigned program){
glDeleteProgram(program);
}
unsigned last_shader = -1;
static
int shader_uniform(const char *name) {
int ret = glGetUniformLocation(last_shader, name);
if( ret < 0 ) fprintf(stderr, "cannot find uniform '%s' in shader program %d\n", name, (int)last_shader );
return ret;
}
unsigned shader_get_active() { return last_shader; }
unsigned shader_bind(unsigned program) { unsigned ret = last_shader; return glUseProgram(last_shader = program), ret; }
void shader_int(const char *uniform, int i) { glUniform1i(shader_uniform(uniform), i); }
void shader_float(const char *uniform, float f) { glUniform1f(shader_uniform(uniform), f); }
void shader_vec2(const char *uniform, vec2 v) { glUniform2fv(shader_uniform(uniform), 1, &v.x); }
void shader_vec3(const char *uniform, vec3 v) { glUniform3fv(shader_uniform(uniform), 1, &v.x); }
void shader_vec4(const char *uniform, vec4 v) { glUniform4fv(shader_uniform(uniform), 1, &v.x); }
void shader_mat44(const char *uniform, mat44 m) { glUniformMatrix4fv(shader_uniform(uniform), 1, GL_FALSE/*GL_TRUE*/, m); }
void shader_texture(const char *sampler, unsigned texture, unsigned unit) { glBindTexture(GL_TEXTURE_2D, texture); glActiveTexture(GL_TEXTURE0 + unit); glUniform1i(shader_uniform(sampler), unit); }
void shader_cubemap(const char *sampler, unsigned texture) { glUniform1i(shader_uniform(sampler), 0); glBindTexture(GL_TEXTURE_CUBE_MAP, texture); }
// -----------------------------------------------------------------------------
// colors
uint32_t rgba( uint8_t r, uint8_t g, uint8_t b, uint8_t a ) {
return r << 24 | g << 16 | b << 8 | a;
}
float alpha( uint32_t rgba ) {
return ( rgba & 255 ) / 255.f;
}
// -----------------------------------------------------------------------------
// images
image_t image_create(int x, int y, int flags) {
int n = 3; // defaults to RGB
if(flags & IMAGE_R) n = 1;
if(flags & IMAGE_RG) n = 2;
if(flags & IMAGE_RGB) n = 3;
if(flags & IMAGE_RGBA) n = 4;
image_t img; img.x = x; img.y = y; img.n = n;
img.pixels = REALLOC(0, x * y * n ); // @fixme: image_destroy() requires stbi allocator to match REALLOC
return img;
}
image_t image_from_mem(const char *data, int size, int flags) {
image_t img = {0};
if( data && size ) {
stbi_set_flip_vertically_on_load(flags & IMAGE_FLIP ? 1 : 0);
int n = 0;
if(flags & IMAGE_R) n = 1;
if(flags & IMAGE_RG) n = 2;
if(flags & IMAGE_RGB) n = 3;
if(flags & IMAGE_RGBA) n = 4;
img.pixels = stbi_load_from_memory(data, size, &img.x,&img.y,&img.n, n);
if( img.pixels ) {
PRINTF("Loaded image (%dx%d %.*s->%.*s)\n",img.w,img.h,img.n,"RGBA",n?n:img.n,"RGBA");
} else {
// PANIC("Error loading image (%s)\n", pathfile);
}
img.n = n ? n : img.n;
}
return img;
}
image_t image(const char *pathfile, int flags) {
int size = 0;
char *data = file_load(file_find(pathfile/*stringf("%s", pathfile)*/), &size);
#if 1
if( !size ) data = file_load(file_find(stringf("%s.png",pathfile)), &size);
if( !size ) data = file_load(file_find(stringf("%s.jpg",pathfile)), &size);
if( !size ) data = file_load(file_find(stringf("%s.tga",pathfile)), &size);
if( !size ) data = file_load(file_find(stringf("%s.jpg.png",pathfile)), &size);
if( !size ) data = file_load(file_find(stringf("%s.tga.png",pathfile)), &size);
if( !size ) data = file_load(file_find(stringf("%s.png.jpg",pathfile)), &size);
if( !size ) data = file_load(file_find(stringf("%s.tga.jpg",pathfile)), &size);
#endif
return image_from_mem(data, size, flags);
}
void image_destroy(image_t *img) {
if(img->pixels) stbi_image_free(img->pixels);
img->pixels = 0; // *img = (image_t){0}; // do not clear fields yet. might be useful in the future.
}
// bilinear interpolation (uv must be in image coords, range [0..w-1,0..h-1])
static
vec3 bilinear(image_t in, vec2 uv) {
float w = in.x, h = in.y, u = uv.x, v = uv.y;
float u1 = (int)u, v1 = (int)v, u2 = minf(u1+1, w-1), v2 = minf(v1+1, h-1);
float c1 = u - u1, c2 = v - v1;
uint8_t *p1 = &in.pixels8[ in.n * (int)(u1 + v1 * in.w) ];
uint8_t *p2 = &in.pixels8[ in.n * (int)(u2 + v1 * in.w) ];
uint8_t *p3 = &in.pixels8[ in.n * (int)(u1 + v2 * in.w) ];
uint8_t *p4 = &in.pixels8[ in.n * (int)(u2 + v2 * in.w) ];
vec3 A = vec3( p1[0], p1[1], p1[2] );
vec3 B = vec3( p2[0], p2[1], p2[2] );
vec3 C = vec3( p3[0], p3[1], p3[2] );
vec3 D = vec3( p4[0], p4[1], p4[2] );
return mix3(mix3(A, B, c1), mix3(C, D, c1), c2);
}
// -----------------------------------------------------------------------------
// textures
unsigned texture_update(texture_t *t, unsigned w, unsigned h, unsigned n, void *pixels, int flags) {
ASSERT( t && t->id );
ASSERT( n <= 4 );
GLuint pixel_types[] = { GL_RED, GL_RED, GL_RG, GL_RGB, GL_RGBA, GL_R32F, GL_R32F, GL_RG32F, GL_RGB32F, GL_RGBA32F };
GLenum pixel_storage = flags & TEXTURE_FLOAT ? GL_FLOAT : GL_UNSIGNED_BYTE;
GLuint pixel_type = pixel_types[ n ];
GLuint texel_type = pixel_types[ n + 5 * !!(flags & TEXTURE_FLOAT) ];
GLenum wrap = GL_CLAMP_TO_EDGE;
GLenum min_filter = GL_NEAREST, mag_filter = GL_NEAREST;
// GLfloat color = (flags&7)/7.f, border_color[4] = { color, color, color, 1.f };
if( flags & TEXTURE_BGR ) if( pixel_type == GL_RGB ) pixel_type = GL_BGR;
if( flags & TEXTURE_BGR ) if( pixel_type == GL_RGBA ) pixel_type = GL_BGRA;
if( flags & TEXTURE_SRGB ) if( texel_type == GL_RGB ) texel_type = GL_SRGB;
if( flags & TEXTURE_SRGB ) if( texel_type == GL_RGBA ) texel_type = GL_SRGB_ALPHA;
if( flags & TEXTURE_BC1 ) texel_type = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
if( flags & TEXTURE_BC2 ) texel_type = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
if( flags & TEXTURE_BC3 ) texel_type = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
if( flags & TEXTURE_DEPTH ) texel_type = pixel_type = GL_DEPTH_COMPONENT; // GL_DEPTH_COMPONENT32
if( flags & TEXTURE_REPEAT ) wrap = GL_REPEAT;
if( flags & TEXTURE_BORDER ) wrap = GL_CLAMP_TO_BORDER;
if( flags & TEXTURE_LINEAR ) min_filter = GL_LINEAR, mag_filter = GL_LINEAR;
if( flags & TEXTURE_MIPMAPS ) min_filter = flags & TEXTURE_LINEAR ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_LINEAR;
if( flags & TEXTURE_MIPMAPS ) mag_filter = flags & TEXTURE_LINEAR ? GL_LINEAR : GL_NEAREST;
if( 0 ) { // flags & TEXTURE_PREMULTIPLY_ALPHA )
uint8_t *p = pixels;
if(n == 2) for( unsigned i = 0; i < 2*w*h; i += 2 ) {
p[i] = (p[i] * p[i+1] + 128) >> 8;
}
if(n == 4) for( unsigned i = 0; i < 4*w*h; i += 4 ) {
p[i+0] = (p[i+0] * p[i+3] + 128) >> 8;
p[i+1] = (p[i+1] * p[i+3] + 128) >> 8;
p[i+2] = (p[i+2] * p[i+3] + 128) >> 8;
}
}
GLenum texture_type = t->flags & TEXTURE_ARRAY ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D; // @fixme: test GL_TEXTURE_2D_ARRAY
//glPixelStorei( GL_UNPACK_ALIGNMENT, n < 4 ? 1 : 4 ); // for framebuffer reading
//glActiveTexture(GL_TEXTURE0 + (flags&7));
glBindTexture(texture_type, t->id);
glTexImage2D(texture_type, 0, texel_type, w, h, 0, pixel_type, pixel_storage, pixels);
glTexParameteri(texture_type, GL_TEXTURE_WRAP_S, wrap);
glTexParameteri(texture_type, GL_TEXTURE_WRAP_T, wrap);
glTexParameteri(texture_type, GL_TEXTURE_MIN_FILTER, min_filter);
glTexParameteri(texture_type, GL_TEXTURE_MAG_FILTER, mag_filter);
#if 0
if( flags & TEXTURE_DEPTH ) glTexParameteri(texture_type, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
if( flags & TEXTURE_DEPTH ) glTexParameteri(texture_type, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
#endif
// if( flags & TEXTURE_BORDER ) glTexParameterfv(texture_type, GL_TEXTURE_BORDER_COLOR, border_color);
if( flags & TEXTURE_MIPMAPS ) glGenerateMipmap(texture_type);
if( flags & TEXTURE_MIPMAPS ) {
GLfloat max_aniso = 0;
// glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &max_aniso);
max_aniso = 4;
// glTexParameterf(texture_type, GL_TEXTURE_MAX_ANISOTROPY, max_aniso);
}
// glBindTexture(texture_type, 0); // do not unbind. current code expects texture to be bound at function exit
t->w = w;
t->h = h;
t->n = n;
t->flags = flags;
return t->id;
}
texture_t texture_create(unsigned w, unsigned h, unsigned n, void *pixels, int flags) {
texture_t texture = {0};
glGenTextures( 1, &texture.id );
texture_update( &texture, w, h, n, pixels, flags );
return texture;
}
texture_t texture_checker() {
static texture_t texture = {0};
if( !texture.id ) {
#if 0
float pixels[] = { 1,0.5,0.5,1 };
texture = texture_create(2,2,1, pixels, TEXTURE_FLOAT|TEXTURE_MIPMAPS|TEXTURE_REPEAT|TEXTURE_BORDER);
#else
unsigned char *pixels = REALLOC(0, 256*256*3);
for (int y = 0, i = 0; y < 256; y++) {
for (int x = 0; x < 256; x++) {
int v = 255 * !!((x ^ y) & 0x8);
pixels[i++] = v * (x > 127);
pixels[i++] = v * (y > 127);
pixels[i++] = v * (x > y);
}
}
texture = texture_create(256,256,3, pixels, TEXTURE_RGB|TEXTURE_MIPMAPS|TEXTURE_REPEAT|TEXTURE_BORDER);
FREE(pixels);
#endif
}
return texture;
}
texture_t texture_from_mem(const char *ptr, int len, int flags) {
image_t img = image_from_mem(ptr, len, flags);
if( img.pixels ) {
texture_t t = texture_create(img.x, img.y, img.n, img.pixels, flags);
image_destroy(&img);
return t;
}
return texture_checker();
}
texture_t texture(const char *pathfile, int flags) {
// PRINTF("Loading file %s\n", pathfile);
image_t img = image(pathfile, flags);
if( img.pixels ) {
texture_t t = texture_create(img.x, img.y, img.n, img.pixels, flags);
image_destroy(&img);
return t;
}
return texture_checker();
}
void texture_destroy( texture_t *t ) {
if(t->id) glDeleteTextures(1, &t->id);
t->id = 0;
}
unsigned shadowmap( unsigned w, unsigned h, int flags ) {
unsigned id = texture_create(w, h, 1, NULL, TEXTURE_DEPTH | TEXTURE_FLOAT | TEXTURE_LINEAR | TEXTURE_BORDER ).id;
return id;
}
// usage: bind empty vao & commit call for 6 (quad) or 3 vertices (tri).
// ie, glBindVertexArray(empty_vao); glDrawArrays(GL_TRIANGLES, 0, 3);
const char *fullscreen_quad_vertex_shader(int flip);
const char *fullscreen_triangle_vertex_shader();
#if 1
const char *fullscreen_quad_vertex_shader(int flip) {
static threadlocal char buf[512] = {0};
snprintf(buf, 512,
""
"out vec2 uv;\n"
"void main() {\n"
" float x = float(((uint(gl_VertexID) + 2u) / 3u)%%2u); \n"
" float y = float(((uint(gl_VertexID) + 1u) / 3u)%%2u); \n"
" gl_Position = vec4(-1.0 + x*2.0, 0.0%c(-1.0+y*2.0), 0.0, 1.0);\n" // normal(0+),flipped(0-)
" uv = vec2(x, y);\n" // normal(y),flipped(1.0-y)
"}\n", flip ? '-':'+'
);
return buf;
}
#else
const char *fullscreen_quad_vertex_shader() {
return
""
"out vec2 uv;\n"
"void main() {\n"
" float x = gl_VertexID / 2;\n"
" float y = gl_VertexID % 2;\n"
" uv = vec2(x, y);\n"
" gl_Position = vec4(2.0*uv - 1.0, 0.0, 1.0);\n"
"}\n";
}
#endif
const char *fullscreen_triangle_vertex_shader() {
return
""
"out vec2 texcoord;\n"
"void main() {\n"
" texcoord = vec2( (gl_VertexID << 1) & 2, gl_VertexID & 2 );\n"
" gl_Position = vec4( texCoord * 2.0 - 1.0, 0.0, 1.0 );\n"
"}\n";
}
void fullscreen_rgb_quad( texture_t texture, float gamma ) {
static int program = -1, vao = -1, u_inv_gamma = -1;
if( program < 0 ) {
const char* vs = fullscreen_quad_vertex_shader(1);
const char* fs =
""
"in vec2 uv;\n"
"out vec4 fragcolor;\n"
"uniform sampler2D texture0; /*unit0*/\n"
"uniform float u_inv_gamma;\n"
"void main() {\n"
" vec4 texel = texture( texture0, uv );\n"
" fragcolor = texel;\n"
" fragcolor.rgb = pow( fragcolor.rgb, vec3( u_inv_gamma ) );\n" // defaults: 1.0/2.2 gamma
"}\n";
program = shader(vs, fs, "", "fragcolor" );
u_inv_gamma = glGetUniformLocation(program, "u_inv_gamma");
glGenVertexArrays( 1, &vao );
}
GLenum texture_type = texture.flags & TEXTURE_ARRAY ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D;
// glEnable( GL_BLEND );
glUseProgram( program );
glUniform1f( u_inv_gamma, 1.0f / (gamma + !gamma) );
glBindVertexArray( vao );
glActiveTexture( GL_TEXTURE0 );
glBindTexture( texture_type, texture.id );
glDrawArrays( GL_TRIANGLES, 0, 6 );
profile_incstat("drawcalls", +1);
profile_incstat("triangles", +2);
glBindTexture( texture_type, 0 );
glBindVertexArray( 0 );
glUseProgram( 0 );
// glDisable( GL_BLEND );
}
void fullscreen_ycbcr_quad( texture_t textureYCbCr[3], float gamma ) {
static int program = -1, vao = -1, u_gamma = -1, uy = -1, ucb = -1, ucr = -1;
if( program < 0 ) {
const char* vs = fullscreen_quad_vertex_shader(1);
const char* fs =
""
"in vec2 uv;\n"
"out vec4 fragcolor;\n"
"uniform sampler2D u_texture_y; /*unit0*/\n"
"uniform sampler2D u_texture_cb; /*unit1*/\n"
"uniform sampler2D u_texture_cr; /*unit2*/\n"
"uniform float u_gamma;\n"
"void main() {\n"
" float y = texture(u_texture_y, uv).r;\n"
" float cb = texture(u_texture_cb, uv).r;\n"
" float cr = texture(u_texture_cr, uv).r;\n"
" const mat4 to_rgb = mat4(\n"
" 1.0000, 1.0000, 1.0000, 0.0000,\n"
" 0.0000, -0.3441, 1.7720, 0.0000,\n"
" 1.4020, -0.7141, 0.0000, 0.0000,\n"
" -0.7010, 0.5291, -0.8860, 1.0000\n"
" );\n"
" vec4 texel = to_rgb * vec4(y, cb, cr, 1.0);\n"
/* same as:
" vec3 yCbCr = vec3(y,cb-0.5,cr-0.5);\n"
" vec4 texel = vec4( dot( vec3( 1.0, 0.0, 1.402 ), yCbCr ),\n"
" dot( vec3( 1.0 , -0.34414 , -0.71414 ), yCbCr ),\n"
" dot( vec3( 1.0, 1.772, 0.0 ), yCbCr ), 1.0);\n"
*/
" // gamma correction\n"
" texel.rgb = pow(texel.rgb, vec3(1.0 / u_gamma));\n"
" // saturation (algorithm from Chapter 16 of OpenGL Shading Language)\n"
" { float saturation = 2.0; const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n"
" vec3 intensity = vec3(dot(texel.rgb, W));\n"
" texel.rgb = mix(intensity, texel.rgb, saturation); }\n"
" fragcolor = vec4(texel.rgb, 1.0);\n"
"}\n";
program = shader(vs, fs, "", "fragcolor" );
u_gamma = glGetUniformLocation(program, "u_gamma");
uy = glGetUniformLocation(program, "u_texture_y");
ucb = glGetUniformLocation(program, "u_texture_cb");
ucr = glGetUniformLocation(program, "u_texture_cr");
glGenVertexArrays( 1, &vao );
}
// glEnable( GL_BLEND );
glUseProgram( program );
glUniform1f( u_gamma, gamma );
glBindVertexArray( vao );
glUniform1i(uy, 0);
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, textureYCbCr[0].id );
glUniform1i(ucb, 1);
glActiveTexture( GL_TEXTURE1 );
glBindTexture( GL_TEXTURE_2D, textureYCbCr[1].id );
glUniform1i(ucr, 2);
glActiveTexture( GL_TEXTURE2 );
glBindTexture( GL_TEXTURE_2D, textureYCbCr[2].id );
glDrawArrays( GL_TRIANGLES, 0, 6 );
profile_incstat("drawcalls", +1);
profile_incstat("triangles", +2);
glBindTexture( GL_TEXTURE_2D, 0 );
glBindVertexArray( 0 );
glUseProgram( 0 );
// glDisable( GL_BLEND );
}
// ----------------------------------------------------------------------------
// sprites
typedef struct sprite_t {
int cellw, cellh; // dimensions of any cell in spritesheet
int frame, ncx, ncy; // frame in a (num cellx, num celly) spritesheet
float px, py, pz; // origin x, y, depth
float ox, oy, cos, sin; // offset x, offset y, cos/sin of rotation degree
float sx, sy; // scale x,y
uint32_t rgba; // vertex color
} sprite_t;
// sprite batching
typedef struct batch_t { array(sprite_t) sprites; mesh_t mesh; int dirty; } batch_t;
typedef map(int, batch_t) batch_group_t; // mapkey is anything that forces a flush. texture_id for now, might be texture_id+program_id soon
// sprite stream
typedef struct sprite_vertex { vec3 pos; vec2 uv; uint32_t rgba; } sprite_vertex;
typedef struct sprite_index { GLuint triangle[3]; } sprite_index;
#define sprite_vertex(...) M_CAST(sprite_vertex, __VA_ARGS__)
#define sprite_index(...) M_CAST(sprite_index, __VA_ARGS__)
// sprite impl
static int sprite_count = 0;
static int sprite_program = -1;
static array(sprite_index) sprite_indices = 0;
static array(sprite_vertex) sprite_vertices = 0;
static batch_group_t sprite_additive_group = {0};
static batch_group_t sprite_translucent_group = {0};
void sprite( texture_t texture, float px, float py, float pz, float rot ) {
sprite_ex( texture,
px,py,pz, rot, // position (x,y,depth), rotation angle
0,0, 1,1, // offset (x,y), scale (x,y),
0,~0u, // is_additive, tint color
0, 0,0 // frame num(x) in a (y,z) spritesheet
);
}
void sprite_ex( texture_t texture,
float px, float py, float pz, float rotation,
float ox, float oy, float sx, float sy,
int additive, uint32_t rgba,
float frame, float xcells, float ycells
) {
if (frame < 0) return;
if (frame > 0 && frame >= (xcells * ycells)) return;
// no need to queue if alpha or scale are zero
if( sx && sy && alpha(rgba) ) {
sprite_t s;
s.px = px;
s.py = py;
s.pz = pz;
s.frame = frame;
s.ncx = xcells ? xcells : 1;
s.ncy = ycells ? ycells : 1;
s.sx = sx;
s.sy = sy;
s.ox = ox * sx;
s.oy = oy * sy;
s.cellw = texture.x * sx / s.ncx;
s.cellh = texture.y * sy / s.ncy;
s.rgba = rgba;
s.cos = 1;
s.sin = 0;
if(rotation) {
rotation = (rotation + 0) * ((float)C_PI / 180);
s.cos = cosf(rotation);
s.sin = sinf(rotation);
}
batch_group_t *batches = additive == 1 ? &sprite_additive_group : &sprite_translucent_group;
#if 0
batch_t *found = map_find(*batches, texture.id);
if( !found ) found = map_insert(*batches, texture.id, (batch_t){0});
#else
batch_t *found = map_find_or_add(*batches, texture.id, (batch_t){0});
#endif
array_push(found->sprites, s);
}
}
static void sprite_rebuild_meshes() {
sprite_count = 0;
batch_group_t* list[] = { &sprite_additive_group, &sprite_translucent_group };
for( int l = 0; l < countof(list); ++l) {
for each_map_ptr(*list[l], int,_, batch_t,bt) {
bt->dirty = array_count(bt->sprites) ? 1 : 0;
if( !bt->dirty ) continue;
int index = 0;
array_clear(sprite_indices);
array_clear(sprite_vertices);
array_foreach_ptr(bt->sprites, sprite_t,it ) {
float x0 = it->ox - it->cellw/2, x3 = x0 + it->cellw;
float y0 = it->oy - it->cellh/2, y3 = y0;
float x1 = x0, x2 = x3;
float y1 = y0 + it->cellh, y2 = y1;
// @todo: move this affine transform into glsl shader
vec3 v0 = { it->px + ( x0 * it->cos - y0 * it->sin ), it->py + ( x0 * it->sin + y0 * it->cos ), it->pz };
vec3 v1 = { it->px + ( x1 * it->cos - y1 * it->sin ), it->py + ( x1 * it->sin + y1 * it->cos ), it->pz };
vec3 v2 = { it->px + ( x2 * it->cos - y2 * it->sin ), it->py + ( x2 * it->sin + y2 * it->cos ), it->pz };
vec3 v3 = { it->px + ( x3 * it->cos - y3 * it->sin ), it->py + ( x3 * it->sin + y3 * it->cos ), it->pz };
float cx = (1.0f / it->ncx) - 1e-9f;
float cy = (1.0f / it->ncy) - 1e-9f;
int idx = (int)it->frame;
int px = idx % it->ncx;
int py = idx / it->ncx;
float ux = px * cx, uy = py * cy;
float vx = ux + cx, vy = uy + cy;
vec2 uv0 = vec2(ux, uy);
vec2 uv1 = vec2(ux, vy);
vec2 uv2 = vec2(vx, vy);
vec2 uv3 = vec2(vx, uy);
array_push( sprite_vertices, sprite_vertex(v0, uv0, it->rgba) ); // Vertex 0 (A)
array_push( sprite_vertices, sprite_vertex(v1, uv1, it->rgba) ); // Vertex 1 (B)
array_push( sprite_vertices, sprite_vertex(v2, uv2, it->rgba) ); // Vertex 2 (C)
array_push( sprite_vertices, sprite_vertex(v3, uv3, it->rgba) ); // Vertex 3 (D)
// A--B A A-B
// quad | | becomes triangle |\ and triangle \|
// D--C D-C C
GLuint A = (index+0), B = (index+1), C = (index+2), D = (index+3); index += 4;
array_push( sprite_indices, sprite_index(C, D, A) ); // Triangle 1
array_push( sprite_indices, sprite_index(C, A, B) ); // Triangle 2
}
mesh_upgrade(&bt->mesh, "p3 t2 c4b", 0,array_count(sprite_vertices),sprite_vertices, 3*array_count(sprite_indices),sprite_indices, MESH_STATIC);
// clear elements from queue
sprite_count += array_count(bt->sprites);
array_clear(bt->sprites);
}
}
}
static void sprite_render_meshes() {
if( sprite_program < 0 ) {
sprite_program = shader(
""
"in vec3 att_Position;\n"
"in vec2 att_TexCoord;\n"
"in vec4 att_Color;\n"
"out vec2 vTexCoord;\n"
"out vec4 vColor;\n"
"\n"
"uniform mat4 u_mvp;\n"
"\n"
"void main() {\n"
" vColor = att_Color;\n"
" vTexCoord = att_TexCoord;\n"
" gl_Position = u_mvp * vec4(att_Position, 1.0);\n"
"}\n",
""
"in vec2 vTexCoord;\n"
"in vec4 vColor;\n"
"out vec4 fragColor;\n"
"\n"
"uniform sampler2D u_texture;\n"
"\n"
"void main() {\n"
" vec4 texColor = texture(u_texture, vTexCoord);\n"
"texColor = vColor * texColor;\n"
"if(texColor.a < 0.5) discard;"
" fragColor = texColor;\n"
"}\n",
"att_Position,att_TexCoord,att_Color",
"fragColor"
);
}
// use the shader and bind the texture @ unit 0
shader_bind(sprite_program);
glActiveTexture(GL_TEXTURE0);
// setup rendering state
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glDepthFunc(GL_LEQUAL); // try to help with zfighting
// update camera and set mvp in the uniform
mat44 mvp2d;
float zdepth_max = window_height(); // 1;
ortho44(mvp2d, 0, window_width(), window_height(), 0, -zdepth_max, +zdepth_max);
shader_mat44("u_mvp", mvp2d);
// set (unit 0) in the uniform texture sampler, and render batch
// for all additive then translucent groups
if( map_count(sprite_additive_group) > 0 ) {
glBlendFunc( GL_SRC_ALPHA, GL_ONE );
for each_map_ptr(sprite_additive_group, int,texture_id, batch_t,bt) {
if( bt->dirty ) {
shader_texture("u_texture", *texture_id, 0);
mesh_render(&bt->mesh);
}
}
// map_clear(sprite_additive_group);
}
if( map_count(sprite_translucent_group) > 0 ) {
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
for each_map_ptr(sprite_translucent_group, int,texture_id, batch_t,bt) {
if( bt->dirty ) {
shader_texture("u_texture", *texture_id, 0);
mesh_render(&bt->mesh);
}
}
// map_clear(sprite_translucent_group);
}
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glDepthFunc(GL_LESS);
glUseProgram(0);
}
static void sprite_init() {
map_init(sprite_translucent_group, less_int, hash_int);
map_init(sprite_additive_group, less_int, hash_int);
}
static void sprite_update() {
profile(Sprite rebuild) {
sprite_rebuild_meshes();
}
profile(Sprite render) {
sprite_render_meshes();
}
}
// -----------------------------------------------------------------------------
// cubemaps
// project cubemap coords into sphere normals
static
vec3 cubemap2polar(int face, int x, int y, int texture_width) {
float u = (x / (texture_width - 1.f)) * 2 - 1;
float v = (y / (texture_width - 1.f)) * 2 - 1;
/**/ if( face == 0 ) return vec3( u, -1, -v);
else if( face == 1 ) return vec3(-v, -u, 1);
else if( face == 2 ) return vec3(-1, -u, -v);
else if( face == 3 ) return vec3(-u, 1, -v);
else if( face == 4 ) return vec3( v, -u, -1);
else return vec3( 1, u, -v);
}
// project normal in a sphere as 2d texcoord
static
vec2 polar2uv(vec3 n) {
n = norm3(n);
float theta = atan2(n.y, n.x);
float phi = atan2(n.z, hypot(n.x, n.y));
float u = (theta + C_PI) / C_PI;
float v = (C_PI/2 - phi) / C_PI;
return vec2(u, v);
}
// equirectangular panorama (2:1) to cubemap - in RGB, out RGB
static
void panorama2cubemap_(image_t out[6], const image_t in, int width){
int face;
#pragma omp parallel for
for( face = 0; face < 6; ++face ) {
out[face] = image_create(width, width, IMAGE_RGB);
for (int j=0; j < width; ++j) {
uint32_t *line = &out[ face ].pixels32[ 0 + j * width ];
for (int i=0; i < width; ++i) {
vec3 polar = cubemap2polar(face, i, j, width);
vec2 uv = polar2uv(polar);
uv = scale2(uv, in.h-1); // source coords (assumes 2:1, 2*h == w)
vec3 rgb = bilinear(in, uv);
union color {
struct { uint8_t r,g,b,a; };
uint32_t rgba;
} c = { rgb.x, rgb.y, rgb.z, 255 };
line[i] = c.rgba;
}
}
}
}
// equirectangular panorama (2:1) to cubemap - in RGB, out RGBA
void panorama2cubemap(image_t out[6], const image_t in, int width) {
int face;
#pragma omp parallel for
for( face = 0; face < 6; ++face ) {
out[face] = image_create(width, width, IMAGE_RGBA);
for (int j=0; j < width; ++j) {
uint32_t *line = &out[ face ].pixels32[ 0 + j * width ];
for (int i=0; i < width; ++i) {
vec3 polar = cubemap2polar(face, i, j, width);
vec2 uv = polar2uv(polar);
uv = scale2(uv, in.h-1); // source coords (assumes 2:1, 2*h == w)
vec3 rgb = bilinear(in, uv);
union color {
struct { uint8_t r,g,b,a; };
uint32_t rgba;
} c = { rgb.x, rgb.y, rgb.z, 255 };
line[i] = c.rgba;
}
}
}
}
cubemap_t cubemap6( const image_t images[6], int flags ) {
cubemap_t c = {0}, z = {0};
glGenTextures(1, &c.id);
glBindTexture(GL_TEXTURE_CUBE_MAP, c.id);
int samples = 0;
for (int i = 0; i < 6; i++) {
image_t img = images[i]; //image(textures[i], IMAGE_RGB);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, img.w, img.h, 0, img.n == 3 ? GL_RGB : GL_RGBA, GL_UNSIGNED_BYTE, img.pixels);
// calculate SH coefficients (@ands)
const vec3 skyDir[] = {{ 1, 0, 0},{-1, 0, 0},{ 0, 1, 0},{ 0,-1, 0},{ 0, 0, 1},{ 0, 0,-1}};
const vec3 skyX[] = {{ 0, 0,-1},{ 0, 0, 1},{ 1, 0, 0},{ 1, 0, 0},{ 1, 0, 0},{-1, 0, 0}};
const vec3 skyY[] = {{ 0, 1, 0},{ 0, 1, 0},{ 0, 0,-1},{ 0, 0, 1},{ 0, 1, 0},{ 0, 1, 0}};
int step = 16;
for (int y = 0; y < img.h; y += step) {
unsigned char *p = (unsigned char*)img.pixels + y * img.w * img.n;
for (int x = 0; x < img.w; x += step) {
vec3 n = add3(
add3(
scale3(skyX[i], 2.0f * (x / (img.w - 1.0f)) - 1.0f),
scale3(skyY[i], -2.0f * (y / (img.h - 1.0f)) + 1.0f)),
skyDir[i]); // texelDirection;
float l = len3(n);
vec3 light = div3(vec3(p[0], p[1], p[2]), 255.0f * l * l * l); // texelSolidAngle * texel_radiance;
n = norm3(n);
c.sh[0] = add3(c.sh[0], scale3(light, 0.282095f));
c.sh[1] = add3(c.sh[1], scale3(light, -0.488603f * n.y * 2.0 / 3.0));
c.sh[2] = add3(c.sh[2], scale3(light, 0.488603f * n.z * 2.0 / 3.0));
c.sh[3] = add3(c.sh[3], scale3(light, -0.488603f * n.x * 2.0 / 3.0));
c.sh[4] = add3(c.sh[4], scale3(light, 1.092548f * n.x * n.y / 4.0));
c.sh[5] = add3(c.sh[5], scale3(light, -1.092548f * n.y * n.z / 4.0));
c.sh[6] = add3(c.sh[6], scale3(light, 0.315392f * (3.0f * n.z * n.z - 1.0f) / 4.0));
c.sh[7] = add3(c.sh[7], scale3(light, -1.092548f * n.x * n.z / 4.0));
c.sh[8] = add3(c.sh[8], scale3(light, 0.546274f * (n.x * n.x - n.y * n.y) / 4.0));
p += img.n * step;
samples++;
}
}
}
for (int s = 0; s < 9; s++) {
c.sh[s] = scale3(c.sh[s], 32.f / samples);
}
if( glGenerateMipmap )
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, glGenerateMipmap ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
return c;
}
cubemap_t cubemap( const image_t in, int flags ) {
ASSERT( in.n == 4 );
image_t out[6];
panorama2cubemap(out, in, in.h);
image_t swap[6] = { out[0],out[3],out[1],out[4],out[2],out[5] };
cubemap_t c = cubemap6(swap, flags);
int i;
#pragma omp parallel for
for( i = 0; i < 6; ++i) image_destroy(&out[i]);
return c;
}
void cubemap_destroy(cubemap_t *c) {
glDeleteTextures(1, &c->id);
c->id = 0; // do not destroy SH coefficients still. they might be useful in the future.
}
static cubemap_t *last_cubemap;
cubemap_t* cubemap_get_active() {
return last_cubemap;
}
// -----------------------------------------------------------------------------
skybox_t skybox(const char *asset, int flags) {
skybox_t sky = {0};
// sky mesh
vec3 vertices[] = {{+1,-1,+1},{+1,+1,+1},{+1,+1,-1},{-1,+1,-1},{+1,-1,-1},{-1,-1,-1},{-1,-1,+1},{-1,+1,+1}};
unsigned indices[] = { 0, 1, 2, 3, 4, 5, 6, 3, 7, 1, 6, 0, 4, 2 };
sky.geometry = mesh_create("p3", 0,countof(vertices),vertices, countof(indices),indices, MESH_TRIANGLE_STRIP);
// sky program
sky.program = shader(skybox_vs_3_3, skybox_fs_3_4, "att_position", "fragcolor");
// sky cubemap & SH
if( asset ) {
int is_panorama = vfs_size( asset );
if( is_panorama ) {
stbi_hdr_to_ldr_gamma(1.2f);
image_t panorama = image( asset, IMAGE_RGBA );
sky.cubemap = cubemap( panorama, 0 ); // RGBA required
image_destroy(&panorama);
} else {
image_t images[6] = {0};
images[0] = image( stringf("%s/posx", asset), IMAGE_RGB ); // cubepx
images[1] = image( stringf("%s/negx", asset), IMAGE_RGB ); // cubenx
images[2] = image( stringf("%s/posy", asset), IMAGE_RGB ); // cubepy
images[3] = image( stringf("%s/negy", asset), IMAGE_RGB ); // cubeny
images[4] = image( stringf("%s/posz", asset), IMAGE_RGB ); // cubepz
images[5] = image( stringf("%s/negz", asset), IMAGE_RGB ); // cubenz
sky.cubemap = cubemap6( images, 0 );
for( int i = 0; i < countof(images); ++i ) image_destroy(&images[i]);
}
}
return sky;
}
int skybox_push_state(skybox_t *sky, float mvp[16]) {
last_cubemap = &sky->cubemap;
//glClear(GL_DEPTH_BUFFER_BIT);
//glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
//glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
//glDepthMask(GL_FALSE);
shader_bind(sky->program);
shader_mat44("u_mvp", mvp);
shader_cubemap("u_cubemap", sky->cubemap.id);
return 0; // @fixme: return sortable hash here?
}
int skybox_pop_state(skybox_t *sky) {
//glDepthMask(GL_TRUE);
//glClear(GL_DEPTH_BUFFER_BIT);
return 0;
}
void skybox_destroy(skybox_t *sky) {
glDeleteProgram(sky->program);
cubemap_destroy(&sky->cubemap);
mesh_destroy(&sky->geometry);
}
// -----------------------------------------------------------------------------
mesh_t mesh_create(const char *format, int vertex_stride,int vertex_count,const void *vertex_data, int index_count,const void *index_data, int flags) {
mesh_t z = {0};
mesh_upgrade(&z, format, vertex_stride,vertex_count,vertex_data, index_count,index_data, flags);
return z;
}
void mesh_upgrade(mesh_t *m, const char *format, int vertex_stride,int vertex_count,const void *vertex_data, int index_count,const void *index_data, int flags) {
m->flags = flags;
// setup
unsigned sizeof_index = sizeof(GLuint);
unsigned sizeof_vertex = 0;
m->index_count = index_count;
m->vertex_count = vertex_count;
// iterate vertex attributes { position, normal + uv + tangent + bitangent + ... }
struct vertex_descriptor {
int vertex_type, num_attribute, num_components, alt_normalized;
int stride, offset;
} descriptor[16] = {0}, *dc = &descriptor[0];
do switch( *format ) {
break; case '*': dc->alt_normalized = 1;
break; case '0': dc->num_components = 0;
break; case '1': dc->num_components = 1;
break; case '2': dc->num_components = 2;
break; case '3': dc->num_components = 3;
break; case '4': dc->num_components = 4;
break; case 'f': dc->vertex_type = GL_FLOAT;
break; case 'u': case 'i': dc->vertex_type = GL_UNSIGNED_INT;
break; case 'b': if(format[-1] >= '0' && format[-1] <= '9') dc->vertex_type = GL_UNSIGNED_BYTE; //else bitangent.
break; case ' ': while (format[1] == ' ') format++; case '\0':
if (!dc->vertex_type) dc->vertex_type = GL_FLOAT;
dc->offset = sizeof_vertex;
sizeof_vertex += (dc->stride = dc->num_components * (dc->vertex_type == GL_UNSIGNED_BYTE ? 1 : 4));
++dc;
break; default: if( !strchr("pntcwai", *format) ) PANIC("unsupported vertex type '%c'", *format);
} while (*format++);
if(vertex_stride > 0) sizeof_vertex = vertex_stride;
// layout
if(!m->vao) glGenVertexArrays(1, &m->vao);
glBindVertexArray(m->vao);
// index data
if( index_data && index_count ) {
m->index_count = index_count;
if(!m->ibo) glGenBuffers(1, &m->ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m->ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m->index_count * sizeof_index, index_data, flags & MESH_STREAM ? GL_STREAM_DRAW : GL_STATIC_DRAW);
}
// vertex data
if( vertex_data && vertex_count ) {
m->vertex_count = vertex_count;
if(!m->vbo) glGenBuffers(1, &m->vbo);
glBindBuffer(GL_ARRAY_BUFFER, m->vbo);
glBufferData(GL_ARRAY_BUFFER, m->vertex_count * sizeof_vertex, vertex_data, flags & MESH_STREAM ? GL_STREAM_DRAW : GL_STATIC_DRAW);
}
for( int i = 0; i < 8; ++i ) {
// glDisableVertexAttribArray(i);
}
// vertex setup: iterate descriptors
for( int i = 0; i < countof(descriptor); ++i ) {
if( descriptor[i].num_components ) {
glDisableVertexAttribArray(i);
glVertexAttribPointer(i,
descriptor[i].num_components, descriptor[i].vertex_type, (descriptor[i].vertex_type == GL_UNSIGNED_BYTE ? GL_TRUE : GL_FALSE) ^ (descriptor[i].alt_normalized ? GL_TRUE : GL_FALSE),
sizeof_vertex, (GLchar*)NULL + descriptor[i].offset);
glEnableVertexAttribArray(i);
} else {
glDisableVertexAttribArray(i);
}
}
glBindVertexArray(0);
}
void mesh_pop_state(mesh_t *sm) {
}
void mesh_push_state(mesh_t *sm, unsigned program, unsigned texture_id, float model[16], float view[16], float proj[16], unsigned billboard) {
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glActiveTexture(GL_TEXTURE0);
shader_bind(program);
mat44 mv; multiply44x2(mv, view, model);
if( billboard ) {
float d = sqrt(mv[4*0+0] * mv[4*0+0] + mv[4*1+1] * mv[4*1+1] + mv[4*2+2] * mv[4*2+2]);
if(billboard & 4) mv[4*0+0] = d, mv[4*0+1] = 0, mv[4*0+2] = 0;
if(billboard & 2) mv[4*1+0] = 0, mv[4*1+1] = d, mv[4*1+2] = 0;
if(billboard & 1) mv[4*2+0] = 0, mv[4*2+1] = 0, mv[4*2+2] = d;
}
mat44 mvp; multiply44x2(mvp, proj, mv); // multiply44x3(mvp, proj, view, model);
shader_mat44("u_mvp", mvp);
if (cubemap_get_active()) {
GLuint uniform_loc = glGetUniformLocation(program, "u_coefficients_sh");
glUniform3fv(uniform_loc, 9, &cubemap_get_active()->sh[0].x);
}
shader_texture("u_texture2d", texture_id, 0);
}
void mesh_render(mesh_t *sm) {
glBindVertexArray(sm->vao);
if( sm->ibo ) { // with indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sm->ibo); // <-- why intel?
glDrawElements(sm->flags & MESH_TRIANGLE_STRIP ? GL_TRIANGLE_STRIP : GL_TRIANGLES, sm->index_count, GL_UNSIGNED_INT, (char*)0);
profile_incstat("drawcalls", +1);
profile_incstat("triangles", sm->index_count/3);
} else { // with vertices only
glDrawArrays(sm->flags & MESH_TRIANGLE_STRIP ? GL_TRIANGLE_STRIP : GL_TRIANGLES, 0, sm->vertex_count /* / 3 */);
profile_incstat("drawcalls", +1);
profile_incstat("triangles", sm->vertex_count/3);
}
}
void mesh_destroy(mesh_t *m) {
// @todo
}
// -----------------------------------------------------------------------------
// screenshot
void* screenshot( unsigned n ) {
int w = window_width(), h = window_height();
int mode = n == 3 ? GL_RGB : n == -3 ? GL_BGR : n == 4 ? GL_RGBA : GL_BGRA;
static uint8_t *pixels = 0;
pixels = (uint8_t*)REALLOC(pixels, w * h * 4 );
#if 0
// sync, 10 ms
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); // disable any pbo, in case somebody did for us
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, w, h, mode, GL_UNSIGNED_BYTE, pixels);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
return pixels;
#else
// async
enum { NUM_PBOS = 16 };
static GLuint pbo[NUM_PBOS] = {0}, lastw, lasth;
static int frame = 0, bound = 0;
if( lastw != w || lasth != h ) {
lastw = w, lasth = h;
frame = 0;
bound = 0;
// @fixme: delete previous pbos
for( int i = 0; i < NUM_PBOS; ++i ) {
glGenBuffers(1, &pbo[i]);
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[i]);
glBufferData(GL_PIXEL_PACK_BUFFER, w * h * 4, NULL, GL_STREAM_READ); // GL_STATIC_READ);
}
}
if (frame < NUM_PBOS) {
// do setup during initial frames
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[bound]);
glReadPixels(0, 0, w, h, mode, GL_UNSIGNED_BYTE, (GLvoid*)((GLchar*)NULL+0));
} else {
// read from oldest bound pbo
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[bound]);
void *ptr = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
memcpy(pixels, ptr, w * h * abs(n));
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
// trigger next read
glReadPixels(0, 0, w, h, mode, GL_UNSIGNED_BYTE, (GLvoid*)((GLchar*)NULL+0));
}
bound = (bound + 1) % NUM_PBOS;
frame += frame >= 0 && frame < NUM_PBOS;
frame *= frame == NUM_PBOS ? -1 : +1;
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
return pixels;
#endif
}
// -----------------------------------------------------------------------------
// viewport
void viewport_color(vec3 color3) {
glClearColor(color3.x, color3.y, color3.z, 1);
}
void viewport_clear(bool color, bool depth) {
glClearDepthf(1);
glClearStencil(0);
glClear((color ? GL_COLOR_BUFFER_BIT : 0) | (depth ? GL_DEPTH_BUFFER_BIT : 0));
}
void viewport_clip(vec2 from, vec2 to) {
float x = from.x, y = from.y, w = to.x-from.x, h = to.y-from.y;
y = window_height()-y-h;
glViewport(x, y, w, h);
glScissor(x, y, w, h);
}
// -----------------------------------------------------------------------------
unsigned fbo(unsigned color_texture_id, unsigned depth_texture_id, int flags) {
GLuint fbo;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
if( color_texture_id ) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color_texture_id, 0);
if( depth_texture_id ) glFramebufferTexture/*2D*/(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, /*GL_TEXTURE_2D,*/ depth_texture_id, 0); // GL_DEPTH_STENCIL_ATTACHMENT
#if 0 // this is working; it's just not enabled for now
else {
// create a non-sampleable renderbuffer object for depth and stencil attachments
unsigned int rbo;
glGenRenderbuffers(1, &rbo);
glBindRenderbuffer(GL_RENDERBUFFER, rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, color.width, color.height); // use a single renderbuffer object for both a depth AND stencil buffer.
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); // now actually attach it
}
#endif
if(flags) glDrawBuffer(GL_NONE);
if(flags) glReadBuffer(GL_NONE);
#if 0
GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if( GL_FRAMEBUFFER_COMPLETE != result ) {
PANIC("ERROR: Framebuffer not complete.");
}
#else
switch (glCheckFramebufferStatus(GL_FRAMEBUFFER)) {
case GL_FRAMEBUFFER_COMPLETE: break;
case GL_FRAMEBUFFER_UNDEFINED: PANIC("GL_FRAMEBUFFER_UNDEFINED");
case GL_FRAMEBUFFER_UNSUPPORTED: PANIC("GL_FRAMEBUFFER_UNSUPPORTED");
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: PANIC("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT");
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: PANIC("GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER");
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: PANIC("GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER");
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: PANIC("GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE");
// case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: PANIC("GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT");
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: PANIC("GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS");
// case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: PANIC("GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT");
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: PANIC("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");
default: PANIC("ERROR: Framebuffer not complete. glCheckFramebufferStatus returned %x", glCheckFramebufferStatus(GL_FRAMEBUFFER));
}
#endif
glBindFramebuffer (GL_FRAMEBUFFER, 0);
return fbo;
}
void fbo_bind(unsigned id) {
glBindFramebuffer(GL_FRAMEBUFFER, id);
}
void fbo_unbind() {
fbo_bind(0);
}
void fbo_destroy(unsigned id) {
#if 0
glDeleteRenderbuffers(1, &renderbuffer);
#endif
glDeleteFramebuffers(1, &id);
}
// -----------------------------------------------------------------------------
// post-effects swap chain.
// - rlyeh, public domain.
typedef struct passfx passfx;
typedef struct postfx postfx;
void postfx_create(postfx *fx, int flags);
void postfx_destroy(postfx *fx);
bool postfx_load(postfx *fx, const char *name, const char *fragment);
bool postfx_begin(postfx *fx, int width, int height);
bool postfx_end(postfx *fx);
bool postfx_enabled(postfx *fx, int pass_number);
bool postfx_enable(postfx *fx, int pass_number, bool enabled);
// bool postfx_toggle(postfx *fx, int pass_number);
void postfx_clear(postfx *fx);
char* postfx_name(postfx *fx, int slot);
struct passfx {
mesh_t m;
char *name;
unsigned program;
int uniforms[16];
};
struct postfx {
// renderbuffers: color & depth textures
unsigned fb[2];
texture_t diffuse[2], depth[2];
// shader passes
passfx pass[64];
uint64_t mask;
// global enable flag
bool enabled;
//
int num_loaded;
};
enum {
u_color,
u_depth,
u_time,
u_frame,
u_width, u_height,
u_mousex, u_mousey,
u_channelres0x, u_channelres0y,
u_channelres1x, u_channelres1y,
};
void postfx_create(postfx *fx, int flags) {
postfx z = {0};
*fx = z;
fx->enabled = 1;
}
void postfx_destroy( postfx *fx ) {
for( int i = 0; i < 64; ++i ) {
FREE(fx->pass[i].name);
}
texture_destroy(&fx->diffuse[0]);
texture_destroy(&fx->diffuse[1]);
texture_destroy(&fx->depth[0]);
texture_destroy(&fx->depth[1]);
fbo_destroy(fx->fb[0]);
fbo_destroy(fx->fb[1]);
postfx z = {0};
*fx = z;
}
char* postfx_name(postfx *fx, int slot) {
return fx->pass[ slot & 63 ].name;
}
bool postfx_load_from_mem( postfx *fx, const char *name, const char *fs ) {
if(!fs || !fs[0]) PANIC("!invalid fragment shader");
int slot = fx->num_loaded++;
passfx *p = &fx->pass[ slot & 63 ];
p->name = STRDUP(name);
const char *vs = fullscreen_quad_vertex_shader(0);
// patch fragment
char *fs2 = (char*)CALLOC(1, 64*1024);
strcat(fs2,
""
"#define texture2D texture\n"
"#define texture2DLod textureLod\n"
"#define FRAGCOLOR fragColor\n"
"#define texcoord uv\n"
"#define TEXCOORD uv\n"
"uniform sampler2D iChannel0;\n"
"uniform sampler2D/*Shadow*/ iChannel1;\n"
"uniform float iWidth, iHeight, iTime, iFrame, iMousex, iMousey;\n"
"uniform float iChannelRes0x, iChannelRes0y;\n"
"uniform float iChannelRes1x, iChannelRes1y;\n"
"vec2 iResolution = vec2(iWidth, iHeight);\n"
"vec2 iMouse = vec2(iMousex, iMousey);\n"
"vec2 iChannelResolution[2] = vec2[2]( vec2(iChannelRes0x, iChannelRes0y),vec2(iChannelRes1x, iChannelRes1y) );\n"
"float iGlobalTime = iTime;\n"
"in vec2 texcoord;\n"
"out vec4 fragColor;\n"
);
if( strstr(fs, "mainImage") ) {
strcat(fs2,
"void mainImage( out vec4 fragColor, in vec2 fragCoord );\n"
"void main() {\n"
" mainImage(fragColor, texcoord.xy * iResolution);\n"
"}\n");
}
strcat(fs2, fs);
p->program = shader(vs, fs2, "vtexcoord", "fragColor" );
FREE(fs2);
glUseProgram(p->program); // needed?
for( int i = 0; i < countof(p->uniforms); ++i ) p->uniforms[i] = -1;
if( p->uniforms[u_time] == -1 ) p->uniforms[u_time] = glGetUniformLocation(p->program, "iTime");
if( p->uniforms[u_frame] == -1 ) p->uniforms[u_frame] = glGetUniformLocation(p->program, "iFrame");
if( p->uniforms[u_width] == -1 ) p->uniforms[u_width] = glGetUniformLocation(p->program, "iWidth");
if( p->uniforms[u_height] == -1 ) p->uniforms[u_height] = glGetUniformLocation(p->program, "iHeight");
if( p->uniforms[u_mousex] == -1 ) p->uniforms[u_mousex] = glGetUniformLocation(p->program, "iMousex");
if( p->uniforms[u_mousey] == -1 ) p->uniforms[u_mousey] = glGetUniformLocation(p->program, "iMousey");
if( p->uniforms[u_color] == -1 ) p->uniforms[u_color] = glGetUniformLocation(p->program, "tex");
if( p->uniforms[u_color] == -1 ) p->uniforms[u_color] = glGetUniformLocation(p->program, "tex0");
if( p->uniforms[u_color] == -1 ) p->uniforms[u_color] = glGetUniformLocation(p->program, "tColor");
if( p->uniforms[u_color] == -1 ) p->uniforms[u_color] = glGetUniformLocation(p->program, "tDiffuse");
if( p->uniforms[u_color] == -1 ) p->uniforms[u_color] = glGetUniformLocation(p->program, "iChannel0");
if( p->uniforms[u_depth] == -1 ) p->uniforms[u_depth] = glGetUniformLocation(p->program, "tex1");
if( p->uniforms[u_depth] == -1 ) p->uniforms[u_depth] = glGetUniformLocation(p->program, "tDepth");
if( p->uniforms[u_depth] == -1 ) p->uniforms[u_depth] = glGetUniformLocation(p->program, "iChannel1");
if( p->uniforms[u_channelres0x] == -1 ) p->uniforms[u_channelres0x] = glGetUniformLocation(p->program, "iChannelRes0x");
if( p->uniforms[u_channelres0y] == -1 ) p->uniforms[u_channelres0y] = glGetUniformLocation(p->program, "iChannelRes0y");
if( p->uniforms[u_channelres1x] == -1 ) p->uniforms[u_channelres1x] = glGetUniformLocation(p->program, "iChannelRes1x");
if( p->uniforms[u_channelres1y] == -1 ) p->uniforms[u_channelres1y] = glGetUniformLocation(p->program, "iChannelRes1y");
// set quad
glGenVertexArrays(1, &p->m.vao);
return true;
}
uint64_t postfx_count_ones(uint64_t x) {
// [src] https://en.wikipedia.org/wiki/Hamming_weight
x -= (x >> 1) & 0x5555555555555555ULL; //put count of each 2 bits into those 2 bits
x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL); //put count of each 4 bits into those 4 bits
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0fULL; //put count of each 8 bits into those 8 bits
return (x * 0x0101010101010101ULL) >> 56; //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ...
}
bool postfx_enable(postfx *fx, int pass, bool enabled) {
fx->mask = enabled ? fx->mask | (1ull << pass) : fx->mask & ~(1ull << pass);
fx->enabled = !!postfx_count_ones(fx->mask);
return fx->enabled;
}
bool postfx_enabled(postfx *fx, int pass) {
return (!!(fx->mask & (1ull << pass)));
}
bool postfx_toggle(postfx *fx, int pass) {
return postfx_enable(fx, pass, 1 ^ postfx_enabled(fx, pass));
}
void postfx_clear(postfx *fx) {
fx->mask = fx->enabled = 0;
}
bool postfx_begin(postfx *fx, int width, int height) {
width += !width;
height += !height;
// resize if needed
if( fx->diffuse[0].w != width || fx->diffuse[0].h != height ) {
texture_destroy(&fx->diffuse[0]);
texture_destroy(&fx->diffuse[1]);
texture_destroy(&fx->depth[0]);
texture_destroy(&fx->depth[1]);
fbo_destroy(fx->fb[0]);
fbo_destroy(fx->fb[1]);
// create texture, set texture parameters and content
fx->diffuse[0] = texture_create(width, height, 4, NULL, TEXTURE_RGBA);
fx->depth[0] = texture_create(width, height, 0/*1*/, NULL, TEXTURE_DEPTH|TEXTURE_FLOAT);
fx->fb[0] = fbo(fx->diffuse[0].id, fx->depth[0].id, 0);
// create texture, set texture parameters and content
fx->diffuse[1] = texture_create(width, height, 4, NULL, TEXTURE_RGBA);
fx->depth[1] = texture_create(width, height, 0/*1*/, NULL, TEXTURE_DEPTH|TEXTURE_FLOAT);
fx->fb[1] = fbo(fx->diffuse[1].id, fx->depth[1].id, 0);
}
uint64_t num_active_passes = postfx_count_ones(fx->mask);
bool active = fx->enabled && num_active_passes;
if( !active ) {
fbo_unbind();
return false;
}
fbo_bind(fx->fb[1]);
viewport_clip(vec2(0,0), vec2(width, height));
//viewport_clear(true, true);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
fbo_bind(fx->fb[0]);
viewport_clip(vec2(0,0), vec2(width, height));
//viewport_clear(true, true);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
return true;
}
bool postfx_end(postfx *fx) {
uint64_t num_active_passes = postfx_count_ones(fx->mask);
bool active = fx->enabled && num_active_passes;
if( !active ) {
return false;
}
fbo_unbind();
// disable depth test in 2d rendering
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE); // no such thing: glDisable(GL_DEPTH_WRITE);
int frame = 0;
float t = time_ms() / 1000.f;
float w = fx->diffuse[0].w;
float h = fx->diffuse[0].h;
float mx = input(MOUSE_X);
float my = input(MOUSE_Y);
for(int i = 0, e = countof(fx->pass); i < e; ++i) {
if( fx->mask & (1ull << i) ) {
passfx *pass = &fx->pass[i];
if( !pass->program ) { --num_active_passes; continue; }
glUseProgram(pass->program);
// bind texture to texture unit 0
// shader_texture(fx->diffuse[frame], 0);
glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, fx->diffuse[frame].id);
glUniform1i(pass->uniforms[u_color], 0);
glUniform1f(pass->uniforms[u_channelres0x], fx->diffuse[frame].w);
glUniform1f(pass->uniforms[u_channelres0y], fx->diffuse[frame].h);
// bind depth to texture unit 1
// shader_texture(fx->depth[frame], 1);
glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, fx->depth[frame].id);
glUniform1i(pass->uniforms[u_depth], 1);
// bind uniforms
static unsigned f = 0; ++f;
glUniform1f(pass->uniforms[u_time], t);
glUniform1f(pass->uniforms[u_frame], f-1);
glUniform1f(pass->uniforms[u_width], w);
glUniform1f(pass->uniforms[u_height], h);
glUniform1f(pass->uniforms[u_mousex], mx);
glUniform1f(pass->uniforms[u_mousey], my);
// bind the vao
int bound = --num_active_passes;
if( bound ) fbo_bind(fx->fb[frame ^= 1]);
// fullscreen quad
glBindVertexArray(pass->m.vao);
glDrawArrays(GL_TRIANGLES, 0, 6);
profile_incstat("drawcalls", +1);
profile_incstat("triangles", +2);
glBindVertexArray(0);
if( bound ) fbo_unbind();
else glUseProgram(0);
}
}
glDepthMask(GL_TRUE); // no such thing: glEnable(GL_DEPTH_WRITE);
return true;
}
static postfx fx;
void fx_load_from_mem(const char *nameid, const char *content) {
ONCE postfx_create(&fx, 0);
postfx_load_from_mem(&fx, nameid, content);
}
void fx_load(const char *file) {
postfx_load_from_mem(&fx, file_name(file), vfs_read(file));
}
void fx_begin() {
postfx_begin(&fx, window_width(), window_height());
}
void fx_end() {
postfx_end(&fx);
}
int fx_enabled(int pass) {
return postfx_enabled(&fx, pass);
}
void fx_enable(int pass, int enabled) {
postfx_enable(&fx, pass, enabled);
}
void fx_enable_all(int enabled) {
for( int i = 0; i < fx.num_loaded; ++i ) fx_enable(i, enabled);
}
char *fx_name(int pass) {
return postfx_name(&fx, pass);
}
// -----------------------------------------------------------------------------
#define IQM_MAGIC "INTERQUAKEMODEL"
#define IQM_VERSION 2
struct iqmheader {
char magic[16];
unsigned version;
unsigned filesize;
unsigned flags;
unsigned num_text, ofs_text;
unsigned num_meshes, ofs_meshes;
unsigned num_vertexarrays, num_vertexes, ofs_vertexarrays;
unsigned num_triangles, ofs_triangles, ofs_adjacency;
unsigned num_joints, ofs_joints;
unsigned num_poses, ofs_poses;
unsigned num_anims, ofs_anims;
unsigned num_frames, num_framechannels, ofs_frames, ofs_bounds;
unsigned num_comment, ofs_comment;
unsigned num_extensions, ofs_extensions;
};
struct iqmmesh {
unsigned name;
unsigned material;
unsigned first_vertex, num_vertexes;
unsigned first_triangle, num_triangles;
};
enum {
IQM_POSITION,
IQM_TEXCOORD,
IQM_NORMAL,
IQM_TANGENT,
IQM_BLENDINDEXES,
IQM_BLENDWEIGHTS,
IQM_COLOR,
IQM_CUSTOM = 0x10
};
enum {
IQM_BYTE,
IQM_UBYTE,
IQM_SHORT,
IQM_USHORT,
IQM_INT,
IQM_UINT,
IQM_HALF,
IQM_FLOAT,
IQM_DOUBLE,
};
struct iqmtriangle {
unsigned vertex[3];
};
struct iqmadjacency {
unsigned triangle[3];
};
struct iqmjoint {
unsigned name;
int parent;
float translate[3], rotate[4], scale[3];
};
struct iqmpose {
int parent;
unsigned mask;
float channeloffset[10];
float channelscale[10];
};
struct iqmanim {
unsigned name;
unsigned first_frame, num_frames;
float framerate;
unsigned flags;
};
enum {
IQM_LOOP = 1<<0
};
struct iqmvertexarray {
unsigned type;
unsigned flags;
unsigned format;
unsigned size;
unsigned offset;
};
struct iqmbounds {
union {
struct { float bbmin[3], bbmax[3]; };
struct { vec3 min3, max3; };
aabb box;
};
float xyradius, radius;
};
// -----------------------------------------------------------------------------
typedef struct iqm_vertex {
GLfloat position[3];
GLfloat texcoord[2];
GLfloat normal[3];
GLfloat tangent[4];
GLubyte blendindexes[4];
GLubyte blendweights[4];
GLubyte color[4];
} iqm_vertex;
typedef struct iqm_t {
int nummeshes, numtris, numverts, numjoints, numframes, numanims;
GLuint program;
GLuint vao, ibo, vbo;
GLuint *textures;
uint8_t *buf, *meshdata, *animdata;
struct iqmmesh *meshes;
struct iqmjoint *joints;
struct iqmpose *poses;
struct iqmanim *anims;
struct iqmbounds *bounds;
mat34 *baseframe, *inversebaseframe, *outframe, *frames;
GLint bonematsoffset;
} iqm_t;
#define program (q->program)
#define meshdata (q->meshdata)
#define animdata (q->animdata)
#define nummeshes (q->nummeshes)
#define numtris (q->numtris)
#define numverts (q->numverts)
#define numjoints (q->numjoints)
#define numframes (q->numframes)
#define numanims (q->numanims)
#define meshes (q->meshes)
#define textures (q->textures)
#define joints (q->joints)
#define poses (q->poses)
#define anims (q->anims)
#define baseframe (q->baseframe)
#define inversebaseframe (q->inversebaseframe)
#define outframe (q->outframe)
#define frames (q->frames)
#define vao (q->vao)
#define ibo (q->ibo)
#define vbo (q->vbo)
#define bonematsoffset (q->bonematsoffset)
#define buf (q->buf)
#define bounds (q->bounds)
static
bool model_load_meshes(iqm_t *q, const struct iqmheader *hdr) {
if(meshdata) return false;
lil32p(&buf[hdr->ofs_vertexarrays], hdr->num_vertexarrays*sizeof(struct iqmvertexarray)/sizeof(uint32_t));
lil32p(&buf[hdr->ofs_triangles], hdr->num_triangles*sizeof(struct iqmtriangle)/sizeof(uint32_t));
lil32p(&buf[hdr->ofs_meshes], hdr->num_meshes*sizeof(struct iqmmesh)/sizeof(uint32_t));
lil32p(&buf[hdr->ofs_joints], hdr->num_joints*sizeof(struct iqmjoint)/sizeof(uint32_t));
meshdata = buf;
nummeshes = hdr->num_meshes;
numtris = hdr->num_triangles;
numverts = hdr->num_vertexes;
numjoints = hdr->num_joints;
outframe = CALLOC(hdr->num_joints, sizeof(mat34));
float *inposition = NULL, *innormal = NULL, *intangent = NULL, *intexcoord = NULL;
uint8_t *inblendindex8 = NULL, *inblendweight8 = NULL;
int *inblendindexi = NULL; float *inblendweightf = NULL;
struct iqmvertexarray *vas = (struct iqmvertexarray *)&buf[hdr->ofs_vertexarrays];
for(int i = 0; i < (int)hdr->num_vertexarrays; i++) {
struct iqmvertexarray *va = &vas[i];
switch(va->type) {
default: continue; // return PANIC("unknown iqm vertex type (%d)", va->type), false;
break; case IQM_POSITION: if(va->format != IQM_FLOAT || va->size != 3) return PANIC("!"); false; inposition = (float *)&buf[va->offset]; lil32pf(inposition, 3*hdr->num_vertexes);
break; case IQM_NORMAL: if(va->format != IQM_FLOAT || va->size != 3) return PANIC("!"); false; innormal = (float *)&buf[va->offset]; lil32pf(innormal, 3*hdr->num_vertexes);
break; case IQM_TANGENT: if(va->format != IQM_FLOAT || va->size != 4) return PANIC("!"); false; intangent = (float *)&buf[va->offset]; lil32pf(intangent, 4*hdr->num_vertexes);
break; case IQM_TEXCOORD: if(va->format != IQM_FLOAT || va->size != 2) return PANIC("!"); false; intexcoord = (float *)&buf[va->offset]; lil32pf(intexcoord, 2*hdr->num_vertexes);
break; case IQM_BLENDINDEXES: if(va->size != 4) return PANIC("!"); false; if(va->format != IQM_UBYTE && va->format != IQM_INT) return PANIC("!"); false;
if(va->format == IQM_UBYTE) inblendindex8 = (uint8_t *)&buf[va->offset];
else inblendindexi = (int *)&buf[va->offset];
break; case IQM_BLENDWEIGHTS: if(va->size != 4) return PANIC("!"); false; if(va->format != IQM_UBYTE && va->format != IQM_FLOAT) return PANIC("!"); false;
if(va->format == IQM_UBYTE) inblendweight8 = (uint8_t *)&buf[va->offset];
else inblendweightf = (float *)&buf[va->offset];
}
}
if (hdr->ofs_bounds) lil32p(buf + hdr->ofs_bounds, hdr->num_frames * sizeof(struct iqmbounds));
if (hdr->ofs_bounds) bounds = (struct iqmbounds *) &buf[hdr->ofs_bounds];
meshes = (struct iqmmesh *)&buf[hdr->ofs_meshes];
joints = (struct iqmjoint *)&buf[hdr->ofs_joints];
baseframe = CALLOC(hdr->num_joints, sizeof(mat34));
inversebaseframe = CALLOC(hdr->num_joints, sizeof(mat34));
for(int i = 0; i < (int)hdr->num_joints; i++) {
struct iqmjoint *j = &joints[i];
compose34(baseframe[i], ptr3(j->translate), normq(ptrq(j->rotate)), ptr3(j->scale));
invert34(inversebaseframe[i], baseframe[i]);
if(j->parent >= 0) {
multiply34x2(baseframe[i], baseframe[j->parent], baseframe[i]);
multiply34(inversebaseframe[i], inversebaseframe[j->parent]);
}
}
struct iqmtriangle *tris = (struct iqmtriangle *)&buf[hdr->ofs_triangles];
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
if(!ibo) glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, hdr->num_triangles*sizeof(struct iqmtriangle), tris, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
iqm_vertex *verts = CALLOC(hdr->num_vertexes, sizeof(iqm_vertex));
for(int i = 0; i < (int)hdr->num_vertexes; i++) {
iqm_vertex *v = &verts[i];
if(inposition) memcpy(v->position, &inposition[i*3], sizeof(v->position));
if(innormal) memcpy(v->normal, &innormal[i*3], sizeof(v->normal));
if(intangent) memcpy(v->tangent, &intangent[i*4], sizeof(v->tangent));
if(intexcoord) memcpy(v->texcoord, &intexcoord[i*2], sizeof(v->texcoord));
if(inblendindex8) memcpy(v->blendindexes, &inblendindex8[i*4], sizeof(v->blendindexes));
if(inblendweight8) memcpy(v->blendweights, &inblendweight8[i*4], sizeof(v->blendweights));
if(inblendindexi) {
uint8_t conv[4] = { inblendindexi[i*4], inblendindexi[i*4+1], inblendindexi[i*4+2], inblendindexi[i*4+3] };
memcpy(v->blendindexes, conv, sizeof(v->blendindexes));
}
if(inblendweightf) {
uint8_t conv[4] = { inblendweightf[i*4] * 255, inblendweightf[i*4+1] * 255, inblendweightf[i*4+2] * 255, inblendweightf[i*4+3] * 255 };
memcpy(v->blendweights, conv, sizeof(v->blendweights));
}
}
if(!vbo) glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, hdr->num_vertexes*sizeof(iqm_vertex), verts, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
FREE(verts);
const char *str = hdr->ofs_text ? (char *)&buf[hdr->ofs_text] : "";
for(int i = 0; i < (int)hdr->num_meshes; i++) {
struct iqmmesh *m = &meshes[i];
PRINTF("loaded mesh: %s\n", &str[m->name]);
}
return true;
}
static
bool model_load_anims(iqm_t *q, const struct iqmheader *hdr) {
if((int)hdr->num_poses != numjoints) return false;
if(animdata) {
if(animdata != meshdata) FREE(animdata);
FREE(frames);
animdata = NULL;
anims = NULL;
frames = 0;
numframes = 0;
numanims = 0;
}
lil32p(&buf[hdr->ofs_poses], hdr->num_poses*sizeof(struct iqmpose)/sizeof(uint32_t));
lil32p(&buf[hdr->ofs_anims], hdr->num_anims*sizeof(struct iqmanim)/sizeof(uint32_t));
lil16p((uint16_t *)&buf[hdr->ofs_frames], hdr->num_frames*hdr->num_framechannels);
animdata = buf;
numanims = hdr->num_anims;
numframes = hdr->num_frames;
anims = (struct iqmanim *)&buf[hdr->ofs_anims];
poses = (struct iqmpose *)&buf[hdr->ofs_poses];
frames = CALLOC(hdr->num_frames * hdr->num_poses, sizeof(mat34));
uint16_t *framedata = (uint16_t *)&buf[hdr->ofs_frames];
for(int i = 0; i < (int)hdr->num_frames; i++) {
for(int j = 0; j < (int)hdr->num_poses; j++) {
struct iqmpose *p = &poses[j];
quat rotate;
vec3 translate, scale;
translate.x = p->channeloffset[0]; if(p->mask&0x01) translate.x += *framedata++ * p->channelscale[0];
translate.y = p->channeloffset[1]; if(p->mask&0x02) translate.y += *framedata++ * p->channelscale[1];
translate.z = p->channeloffset[2]; if(p->mask&0x04) translate.z += *framedata++ * p->channelscale[2];
rotate.x = p->channeloffset[3]; if(p->mask&0x08) rotate.x += *framedata++ * p->channelscale[3];
rotate.y = p->channeloffset[4]; if(p->mask&0x10) rotate.y += *framedata++ * p->channelscale[4];
rotate.z = p->channeloffset[5]; if(p->mask&0x20) rotate.z += *framedata++ * p->channelscale[5];
rotate.w = p->channeloffset[6]; if(p->mask&0x40) rotate.w += *framedata++ * p->channelscale[6];
scale.x = p->channeloffset[7]; if(p->mask&0x80) scale.x += *framedata++ * p->channelscale[7];
scale.y = p->channeloffset[8]; if(p->mask&0x100) scale.y += *framedata++ * p->channelscale[8];
scale.z = p->channeloffset[9]; if(p->mask&0x200) scale.z += *framedata++ * p->channelscale[9];
// Concatenate each pose with the inverse base pose to avoid doing this at animation time.
// If the joint has a parent, then it needs to be pre-concatenated with its parent's base pose.
// Thus it all negates at animation time like so:
// (parentPose * parentInverseBasePose) * (parentBasePose * childPose * childInverseBasePose) =>
// parentPose * (parentInverseBasePose * parentBasePose) * childPose * childInverseBasePose =>
// parentPose * childPose * childInverseBasePose
mat34 m; compose34(m, translate, normq(rotate), scale);
if(p->parent >= 0) multiply34x3(frames[i*hdr->num_poses + j], baseframe[p->parent], m, inversebaseframe[j]);
else multiply34x2(frames[i*hdr->num_poses + j], m, inversebaseframe[j]);
}
}
const char *str = hdr->ofs_text ? (char *)&buf[hdr->ofs_text] : "";
for(int i = 0; i < (int)hdr->num_anims; i++) {
struct iqmanim *a = &anims[i];
PRINTF("loaded anim[%d]: %s\n", i, &str[a->name]);
}
return true;
}
static
bool model_load_textures(iqm_t *q, const struct iqmheader *hdr) {
textures = CALLOC(hdr->num_meshes, sizeof(GLuint));
for(int i = 0; i < (int)hdr->num_meshes; i++) {
struct iqmmesh *m = &meshes[i];
textures[i] = 0;
const char *str = hdr->ofs_text ? (char *)&buf[hdr->ofs_text] : "";
#if 0
// diffuse+translucency,normal,specular+emissive,metallic+smoothness,ao/cavity or subdermis
const char *pf = file_pathdir(pathfile);
const char *suffixes[] = { "", "_d", "_n", "_s", "_m", "_a", 0};
const char *extensions[] = { "", ".jpg", ".png", ".tga", ".ktx", ".dds", 0 };
const char *directories[] = { "", pf, 0 };
for( int dir = 0; directories[dir] && !textures[i]; ++dir ) {
for( int ext = 0; extensions[ext] && !textures[i]; ++ext ) {
for( int suf = 0; suffixes[suf] && !textures[i]; ++suf ) {
textures[i] = texture(stringf("%s%s%s%s", directories[dir], &str[m->material], suffixes[suf], extensions[ext]), TEXTURE_FLIP ).id;
}
}
}
#else
// remove any +unknown or unknown+ from materials (.fbx)
char *material_name = stringf("%s", &str[m->material]);
strcut(material_name, "unknown+");
strcut(material_name, "+unknown");
textures[i] = texture( file_find(material_name), 0 ).id;
#endif
if( textures[i] != texture_checker().id) {
PRINTF("loaded material[%d]: %s\n", i, &str[m->material]);
} else {
PRINTF("fail: material[%d] not found: %s\n", i, &str[m->material]);
PRINTF("warn: using placeholder material[%d]=texture_checker\n", i);
textures[i] = texture_checker().id; // placeholder
}
}
return true;
}
model_t model(const char *filename, int flags) {
int len; // vfs_pushd(filedir(filename))
char *ptr = vfs_load(filename, &len); // + vfs_popd
return model_from_mem( ptr, len, flags );
}
model_t model_from_mem(const void *mem, int len, int flags) {
const char *ptr = (const char *)mem;
static int shaderprog = -1;
if( shaderprog < 0 ) {
const char* vs =
""
"#ifndef MAX_BONES\n"
"#define MAX_BONES 110\n"
"#endif\n"
"uniform mat3x4 vsBoneMatrix[MAX_BONES];\n"
"uniform bool SKINNED = false;\n"
"in vec3 att_position;\n"
"in vec2 att_texcoord;\n"
"in vec3 att_normal;\n"
"in vec4 att_tangent;\n"
"in vec4 att_indexes;\n"
"in vec4 att_weights;\n"
"in vec4 att_color;\n"
"in vec3 att_bitangent;\n"
"out vec3 v_position;\n"
"out vec3 v_normal;\n"
"out vec2 v_texcoord;\n"
// "uniform mat4 M;\n" // RIM
"uniform mat4 MVP;\n"
"void main() {\n"
" vec3 objPos;\n"
" if(!SKINNED) {\n"
" objPos = att_position;\n"
" v_normal = att_normal;\n"
" } else {\n"
" mat3x4 m = vsBoneMatrix[int(att_indexes.x)] * att_weights.x;\n"
" m += vsBoneMatrix[int(att_indexes.y)] * att_weights.y;\n"
" m += vsBoneMatrix[int(att_indexes.z)] * att_weights.z;\n"
" m += vsBoneMatrix[int(att_indexes.w)] * att_weights.w;\n"
" objPos = vec4(att_position, 1.0) * m;\n"
" v_normal = vec4(att_normal, 0.0) * m;\n"
" //@todo: tangents\n"
" }\n"
" v_position = att_position;\n"
" v_texcoord = att_texcoord;\n"
" gl_Position = MVP * vec4( objPos, 1.0 );\n"
"}\n";
const char* fs =
""
"in vec3 v_normal;\n"
"in vec2 v_texcoord;\n"
"out vec4 fragColor;\n"
"uniform sampler2D fsDiffTex;\n"
"uniform sampler2D fsNormalTex;\n"
"uniform sampler2D fsPositionTex;\n"
"uniform mat4 MVP;\n"
"void main() {\n"
" vec4 diff = texture(fsDiffTex, v_texcoord).rgba;\n"
" vec3 n = normalize(mat3(MVP) * v_normal); // transform normal to eye space\n"
" fragColor = diff;// * vec4(v_normal.xyz, 1);\n"
"}\n";
shaderprog = shader(vs,stringf(/*"#define RIM\n"*/ "%s", fragment_shader_32_4), //fs,
"att_position,att_texcoord,att_normal,att_tangent,att_indexes,att_weights,att_color,att_bitangent","fragColor");
}
iqm_t *q = CALLOC(1, sizeof(iqm_t));
program = shaderprog;
int error = 1;
if( ptr && len ) {
struct iqmheader hdr; memcpy(&hdr, ptr, sizeof(hdr)); ptr += sizeof(hdr);
if( !memcmp(hdr.magic, IQM_MAGIC, sizeof(hdr.magic))) {
lil32p(&hdr.version, (sizeof(hdr) - sizeof(hdr.magic))/sizeof(uint32_t));
if(hdr.version == IQM_VERSION) {
buf = CALLOC(hdr.filesize, sizeof(uint8_t));
memcpy(buf + sizeof(hdr), ptr, hdr.filesize - sizeof(hdr));
error = 0;
if( hdr.num_meshes > 0 && !(flags & MODEL_NO_MESHES) ) error |= !model_load_meshes(q, &hdr);
if( hdr.num_meshes > 0 && !(flags & MODEL_NO_TEXTURES) ) error |= !model_load_textures(q, &hdr);
if( hdr.num_anims > 0 && !(flags & MODEL_NO_ANIMATIONS) ) error |= !model_load_anims(q, &hdr);
if( buf != meshdata && buf != animdata ) FREE(buf);
}
}
}
model_t m = {0};
if( error ) {
PRINTF("Error: cannot load %s", "model");
FREE(q), q = 0;
} else {
// m.boxes = bounds; // <@todo
m.num_meshes = nummeshes;
m.num_triangles = numtris;
m.num_joints = numjoints;
//m.num_poses = numposes;
m.num_anims = numanims;
m.num_frames = numframes;
m.iqm = q;
m.curframe = model_animate(m, 0);
id44(m.pivot);
}
return m;
}
void model_get_bone_pose(model_t m, float curframe, int joint, vec3 *pos, vec3 *from) {
if(!m.iqm) return;
iqm_t *q = m.iqm;
// mat34 *mat = &frames[(int)curframe * numjoints];
float *a = outframe[joint];
#if 0
mat34 m34 = {0};
muladd34(m34, outframe[int(att_indexes.x)], att_weights.x);
muladd34(m34, outframe[int(att_indexes.y)], att_weights.y);
muladd34(m34, outframe[int(att_indexes.z)], att_weights.z);
muladd34(m34, outframe[int(att_indexes.w)], att_weights.w);
objPos = vec4(att_position, 1.0) * m34;
#endif
*pos = vec3(a[12], a[13], a[14]);
if (joints[joint].parent >= 0) {
float *b = outframe[joints[joint].parent];
/*
@fixme: do as above
*/
*from = vec3(b[12], b[13], b[14]);
} else {
*from = vec3(0, 0, 0);
}
}
float model_animate_clip(model_t m, float curframe, int minframe, int maxframe, bool loop) {
if(!m.iqm) return -1;
iqm_t *q = m.iqm;
float retframe = -1;
if( numframes > 0 ) {
int frame1 = (int)/*floor*/(curframe);
int frame2 = frame1 + (curframe >= m.curframe ? 1 : -1);
float frameoffset = curframe - frame1;
if( loop ) {
int distance = (maxframe - minframe);
frame1 = frame1 >= maxframe ? minframe : frame1 < minframe ? maxframe - clampf(minframe - frame1, 0, distance) : frame1;
frame2 = frame2 >= maxframe ? minframe : frame2 < minframe ? maxframe - clampf(minframe - frame2, 0, distance) : frame2;
retframe = frame1 + frameoffset;
} else {
frame1 = clampf(frame1, minframe, maxframe);
frame2 = clampf(frame2, minframe, maxframe);
retframe = minf(frame1 + frameoffset, maxframe); // clamp to maxframe
}
mat34 *mat1 = &frames[frame1 * numjoints];
mat34 *mat2 = &frames[frame2 * numjoints];
// @todo: add animation blending and inter-frame blending here
// Interpolate matrixes between the two closest frames and concatenate with
// parent matrix if necessary. Concatenate the result with the inverse of the base pose.
for(int i = 0; i < numjoints; i++) {
mat34 mat; lerp34(mat, mat1[i], mat2[i], frameoffset);
if(joints[i].parent >= 0) multiply34x2(outframe[i], outframe[joints[i].parent], mat);
else copy34(outframe[i], mat);
}
// model_render_skeleton
if(0)
for( int i = 0; i < numjoints; i++ ) {
vec3 pos, from;
model_get_bone_pose(m, curframe, i, &pos, &from);
ddraw_line(pos, from);
}
}
return retframe;
}
float model_animate(model_t m, float curframe) {
if(!m.iqm) return -1;
iqm_t *q = m.iqm;
return model_animate_clip(m, curframe, 0, numframes-1, true);
}
void model_render(model_t m, mat44 mvp) {
if(!m.iqm) return;
iqm_t *q = m.iqm;
glBindVertexArray( vao );
glUseProgram(program);
// glUniformMatrix4fv( glGetUniformLocation(program, "M"), 1, GL_FALSE/*GL_TRUE*/, m); // RIM
glUniformMatrix4fv( glGetUniformLocation(program, "MVP"), 1, GL_FALSE/*GL_TRUE*/, mvp);
glUniformMatrix3x4fv( glGetUniformLocation(program, "vsBoneMatrix"), numjoints, GL_FALSE, outframe[0]);
glUniform1i( glGetUniformLocation(program, "SKINNED"), numanims ? GL_TRUE : GL_FALSE);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(iqm_vertex), (GLvoid*)offsetof(iqm_vertex, position) );
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(iqm_vertex), (GLvoid*)offsetof(iqm_vertex, texcoord) );
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(iqm_vertex), (GLvoid*)offsetof(iqm_vertex, normal) );
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(iqm_vertex), (GLvoid*)offsetof(iqm_vertex, tangent) );
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
if(numframes > 0) {
glVertexAttribPointer(4, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(iqm_vertex), (GLvoid*)offsetof(iqm_vertex,blendindexes) );
glVertexAttribPointer(5, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(iqm_vertex), (GLvoid*)offsetof(iqm_vertex,blendweights) );
glEnableVertexAttribArray(4);
glEnableVertexAttribArray(5);
}
// 6 color
// 7 bitangent? into texcoord.z?
struct iqmtriangle *tris = NULL;
for(int i = 0; i < nummeshes; i++) {
struct iqmmesh *m = &meshes[i];
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[i] );
glUseProgram(program);
glUniform1i(glGetUniformLocation(program, "fsDiffTex"), 0 /*<-- unit!*/ );
glDrawElements(GL_TRIANGLES, 3*m->num_triangles, GL_UNSIGNED_INT, &tris[m->first_triangle]);
profile_incstat("drawcalls", +1);
profile_incstat("triangles", +m->num_triangles);
}
glDisableVertexAttribArray(1);
if(numframes > 0) {
glDisableVertexAttribArray(4);
glDisableVertexAttribArray(5);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
static
aabb aabb_transform( aabb A, mat44 M) {
// Based on "Transforming Axis-Aligned Bounding Boxes" by Jim Arvo, 1990
aabb B = { {M[12],M[13],M[14]}, {M[12],M[13],M[14]} }; // extract translation from mat44
for( int i = 0; i < 3; i++ )
for( int j = 0; j < 3; j++ ) {
float a = M[i*4+j] * j[&A.min.x]; // use mat33 from mat44
float b = M[i*4+j] * j[&A.max.x]; // use mat33 from mat44
if( a < b ) {
i[&B.min.x] += a;
i[&B.max.x] += b;
} else {
i[&B.min.x] += b;
i[&B.max.x] += a;
}
}
return B;
}
aabb model_aabb(model_t m, mat44 transform) {
iqm_t *q = m.iqm;
if( q && bounds ) {
int f = ( (int)m.curframe ) % (numframes + !numframes);
vec3 bbmin = ptr3(bounds[f].bbmin);
vec3 bbmax = ptr3(bounds[f].bbmax);
return aabb_transform(aabb(bbmin,bbmax), transform);
}
return aabb(vec3(0,0,0),vec3(0,0,0));
}
void model_destroy(model_t m) {
iqm_t *q = m.iqm;
// if(m.mesh) mesh_destroy(m.mesh);
FREE(outframe);
FREE(textures);
FREE(baseframe);
FREE(inversebaseframe);
if(animdata != meshdata) FREE(animdata);
//FREE(meshdata);
FREE(frames);
FREE(buf);
FREE(q);
}
#undef program
#undef meshdata
#undef animdata
#undef nummeshes
#undef numtris
#undef numverts
#undef numjoints
#undef numframes
#undef numanims
#undef meshes
#undef textures
#undef joints
#undef poses
#undef anims
#undef baseframe
#undef inversebaseframe
#undef outframe
#undef frames
#undef vao
#undef ibo
#undef vbo
#undef bonematsoffset
#undef buf
#undef bounds
#endif // RENDER_C
|
hist.c | /*
* hist.c: Example of histogram calculation in OpenMP.
*
* (C) 2015 Mikhail Kurnosov <mkurnosov@gmail.com>
*/
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <limits.h>
#include <omp.h>
const uint64_t width = 32 * 1024;
const uint64_t height = 32 * 1024;
void *xmalloc(size_t size)
{
void *p = malloc(size);
if (p == NULL) {
fprintf(stderr, "No enough memory\n");
exit(EXIT_FAILURE);
}
return p;
}
void hist_serial(uint8_t *pixels, int height, int width)
{
uint64_t npixels = height * width;
// Number of an occurrence of an each pixel in the image
int *h = xmalloc(sizeof(*h) * 256);
for (int i = 0; i < 256; i++)
h[i] = 0;
for (int i = 0; i < npixels; i++)
h[pixels[i]]++;
int mini, maxi;
for (mini = 0; mini < 256 && h[mini] == 0; mini++);
for (maxi = 255; maxi >= 0 && h[maxi] == 0; maxi--);
int q = 255 / (maxi - mini);
for (int i = 0; i < npixels; i++)
pixels[i] = (pixels[i] - mini) * q;
free(h);
}
void hist_omp(uint8_t *pixels, int height, int width)
{
//
// TODO
//
uint64_t npixels = height * width;
// Number of an occurrence of an each pixel in the image
int *h = xmalloc(sizeof(*h) * 256);
for (int i = 0; i < 256; i++)
h[i] = 0;
for (int i = 0; i < npixels; i++)
h[pixels[i]]++;
int mini, maxi;
for (mini = 0; mini < 256 && h[mini] == 0; mini++);
for (maxi = 255; maxi >= 0 && h[maxi] == 0; maxi--);
int q = 255 / (maxi - mini);
for (int i = 0; i < npixels; i++)
pixels[i] = (pixels[i] - mini) * q;
free(h);
}
void hist_omp2(uint8_t *pixels, int height, int width)
{
uint64_t npixels = height * width;
// Number of an occurrence of an each pixel in the image
int *h = xmalloc(sizeof(*h) * 256);
for (int i = 0; i < 256; i++)
h[i] = 0;
int mini = 256, maxi = -1;
#pragma omp parallel
{
int *hloc = xmalloc(sizeof(*hloc) * 256);
for (int i = 0; i < 256; i++)
hloc[i] = 0;
#pragma omp for nowait
for (int i = 0; i < npixels; i++)
hloc[pixels[i]]++;
int mini_loc, maxi_loc;
for (mini_loc = 0; mini_loc < 256 && hloc[mini_loc] == 0; mini_loc++);
for (maxi_loc = 255; maxi_loc >= 0 && hloc[maxi_loc] == 0; maxi_loc--);
#pragma omp critical
{
if (mini > mini_loc)
mini = mini_loc;
if (maxi < maxi_loc)
maxi = maxi_loc;
}
int q = 255 / (maxi - mini);
#pragma omp for
for (int i = 0; i < npixels; i++)
pixels[i] = (pixels[i] - mini) * q;
free(hloc);
}
free(h);
}
int main(int argc, char *argv[])
{
printf("Histogram (image %dx%d ~ %" PRIu64 " MiB)\n", height, width, height * width / (1 << 20));
uint64_t npixels = width * height;
uint8_t *pixels1, *pixels2;
// Run serial version
pixels1 = xmalloc(sizeof(*pixels1) * npixels);
srand(0);
for (int i = 0; i < npixels; i++)
pixels1[i] = rand() % 256;
//pixels1[i] = (i / width) * (i % width);
double tser = omp_get_wtime();
hist_serial(pixels1, height, width);
tser = omp_get_wtime() - tser;
printf("Elapsed time (serial): %.6f\n", tser);
// Run parallel version
pixels2 = xmalloc(sizeof(*pixels2) * npixels);
srand(0);
for (int i = 0; i < npixels; i++)
pixels2[i] = rand() % 256;
//pixels2[i] = (i / width) * (i % width);
double tpar = omp_get_wtime();
hist_omp(pixels2, height, width);
tpar = omp_get_wtime() - tpar;
printf("Elapsed time (parallel): %.6f\n", tpar);
printf("Speedup: %.2f\n", tser / tpar);
for (int i = 0; i < npixels; i++) {
if (pixels1[i] != pixels2[i]) {
printf("Verification failed: %i %d %d \n", i, pixels1[i], pixels2[i]);
break;
}
}
free(pixels1);
free(pixels2);
return 0;
}
|
GB_unop__acos_fc32_fc32.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 GBCUDA_DEV
#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__acos_fc32_fc32)
// op(A') function: GB (_unop_tran__acos_fc32_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// cast: GxB_FC32_t cij = aij
// unaryop: cij = cacosf (aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = cacosf (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = aij ; \
Cx [pC] = cacosf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ACOS || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__acos_fc32_fc32)
(
GxB_FC32_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_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++)
{
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = cacosf (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 ;
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = cacosf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__acos_fc32_fc32)
(
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
|
ParFriends.h | /****************************************************************/
/* Parallel Combinatorial BLAS Library (for Graph Computations) */
/* version 1.4 -------------------------------------------------*/
/* date: 1/17/2014 ---------------------------------------------*/
/* authors: Aydin Buluc (abuluc@lbl.gov), Adam Lugowski --------*/
/****************************************************************/
/*
Copyright (c) 2010-2014, The Regents of the University of California
Permission is hereby granted, free of charge, to any person obtaining a std::copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, std::copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef _PAR_FRIENDS_H_
#define _PAR_FRIENDS_H_
#include <cstdarg>
#include<iostream>
#include "Friends.h"
#include "MPIType.h"
#include "OptBuf.h"
#include "SpParHelper.h"
#include "SpParMat.h"
#include "mpi.h"
namespace combblas {
template <class IT, class NT, class DER>
class SpParMat;
/*************************************************************************************************/
/**************************** FRIEND FUNCTIONS FOR PARALLEL CLASSES
* ******************************/
/*************************************************************************************************/
/**
** Concatenate all the FullyDistVec<IT,NT> objects into a single one
**/
template <typename IT, typename NT>
FullyDistVec<IT, NT> Concatenate(std::vector<FullyDistVec<IT, NT>>& vecs) {
if (vecs.size() < 1) {
SpParHelper::Print("Warning: Nothing to concatenate, returning empty ");
return FullyDistVec<IT, NT>();
} else if (vecs.size() < 2) {
return vecs[1];
} else {
typename std::vector<FullyDistVec<IT, NT>>::iterator it = vecs.begin();
std::shared_ptr<CommGrid> commGridPtr = it->getcommgrid();
MPI_Comm World = commGridPtr->GetWorld();
IT nglen = it->TotalLength(); // new global length
IT cumloclen = it->MyLocLength(); // existing cumulative local lengths
++it;
for (; it != vecs.end(); ++it) {
if (*(commGridPtr) != *(it->getcommgrid())) {
SpParHelper::Print(
"Grids are not comparable for FullyDistVec<IT,NT>::EWiseApply\n");
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
}
nglen += it->TotalLength();
cumloclen += it->MyLocLength();
}
FullyDistVec<IT, NT> ConCat(commGridPtr, nglen, NT());
int nprocs = commGridPtr->GetSize();
std::vector<std::vector<NT>> data(nprocs);
std::vector<std::vector<IT>> inds(nprocs);
IT gloffset = 0;
for (it = vecs.begin(); it != vecs.end(); ++it) {
IT loclen = it->LocArrSize();
for (IT i = 0; i < loclen; ++i) {
IT locind;
IT loffset = it->LengthUntil();
int owner = ConCat.Owner(gloffset + loffset + i, locind);
data[owner].push_back(it->arr[i]);
inds[owner].push_back(locind);
}
gloffset += it->TotalLength();
}
int* sendcnt = new int[nprocs];
int* sdispls = new int[nprocs];
for (int i = 0; i < nprocs; ++i) sendcnt[i] = (int)data[i].size();
int* rdispls = new int[nprocs];
int* recvcnt = new int[nprocs];
MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT,
World); // share the request counts
sdispls[0] = 0;
rdispls[0] = 0;
for (int i = 0; i < nprocs - 1; ++i) {
sdispls[i + 1] = sdispls[i] + sendcnt[i];
rdispls[i + 1] = rdispls[i] + recvcnt[i];
}
IT totrecv = std::accumulate(recvcnt, recvcnt + nprocs, static_cast<IT>(0));
NT* senddatabuf = new NT[cumloclen];
for (int i = 0; i < nprocs; ++i) {
std::copy(data[i].begin(), data[i].end(), senddatabuf + sdispls[i]);
std::vector<NT>().swap(data[i]); // delete data std::vectors
}
NT* recvdatabuf = new NT[totrecv];
MPI_Alltoallv(senddatabuf, sendcnt, sdispls, MPIType<NT>(), recvdatabuf,
recvcnt, rdispls, MPIType<NT>(), World); // send data
delete[] senddatabuf;
IT* sendindsbuf = new IT[cumloclen];
for (int i = 0; i < nprocs; ++i) {
std::copy(inds[i].begin(), inds[i].end(), sendindsbuf + sdispls[i]);
std::vector<IT>().swap(inds[i]); // delete inds std::vectors
}
IT* recvindsbuf = new IT[totrecv];
MPI_Alltoallv(sendindsbuf, sendcnt, sdispls, MPIType<IT>(), recvindsbuf,
recvcnt, rdispls, MPIType<IT>(), World); // send new inds
DeleteAll(sendindsbuf, sendcnt, sdispls);
for (int i = 0; i < nprocs; ++i) {
for (int j = rdispls[i]; j < rdispls[i] + recvcnt[i]; ++j) {
ConCat.arr[recvindsbuf[j]] = recvdatabuf[j];
}
}
DeleteAll(recvindsbuf, recvcnt, rdispls);
return ConCat;
}
}
template <typename MATRIXA, typename MATRIXB>
bool CheckSpGEMMCompliance(const MATRIXA& A, const MATRIXB& B) {
if (A.getncol() != B.getnrow()) {
std::ostringstream outs;
outs << "Can not multiply, dimensions does not match" << std::endl;
outs << A.getncol() << " != " << B.getnrow() << std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
return false;
}
if ((void*)&A == (void*)&B) {
std::ostringstream outs;
outs << "Can not multiply, inputs alias (make a temporary std::copy of one of "
"them first)"
<< std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, MATRIXALIAS);
return false;
}
return true;
}
/**
* Parallel C = A*B routine that uses a double buffered broadcasting scheme
* @pre { Input matrices, A and B, should not alias }
* Most memory efficient version available. Total stages: 2*sqrt(p)
* Memory requirement during first sqrt(p) stages: <=
*(3/2)*(nnz(A)+nnz(B))+(1/2)*nnz(C)
* Memory requirement during second sqrt(p) stages: <= nnz(A)+nnz(B)+nnz(C)
* Final memory requirement: nnz(C) if clearA and clearB are true
**/
template <typename SR, typename NUO, typename UDERO, typename IU, typename NU1,
typename NU2, typename UDERA, typename UDERB>
SpParMat<IU, NUO, UDERO> Mult_AnXBn_DoubleBuff(SpParMat<IU, NU1, UDERA>& A,
SpParMat<IU, NU2, UDERB>& B,
bool clearA = false,
bool clearB = false)
{
if (!CheckSpGEMMCompliance(A, B)) {
return SpParMat<IU, NUO, UDERO>();
}
int stages, dummy; // last two parameters of ProductGrid are ignored for
// Synch multiplication
std::shared_ptr<CommGrid> GridC =
ProductGrid((A.commGrid).get(), (B.commGrid).get(), stages, dummy, dummy);
IU C_m = A.spSeq->getnrow();
IU C_n = B.spSeq->getncol();
UDERA* A1seq = new UDERA();
UDERA* A2seq = new UDERA();
UDERB* B1seq = new UDERB();
UDERB* B2seq = new UDERB();
(A.spSeq)->Split(*A1seq, *A2seq);
const_cast<UDERB*>(B.spSeq)->Transpose();
(B.spSeq)->Split(*B1seq, *B2seq);
MPI_Barrier(GridC->GetWorld());
IU** ARecvSizes = SpHelper::allocate2D<IU>(UDERA::esscount, stages);
IU** BRecvSizes = SpHelper::allocate2D<IU>(UDERB::esscount, stages);
SpParHelper::GetSetSizes(*A1seq, ARecvSizes, (A.commGrid)->GetRowWorld());
SpParHelper::GetSetSizes(*B1seq, BRecvSizes, (B.commGrid)->GetColWorld());
// Remotely fetched matrices are stored as pointers
UDERA* ARecv;
UDERB* BRecv;
std::vector<SpTuples<IU, NUO>*> tomerge;
int Aself = (A.commGrid)->GetRankInProcRow();
int Bself = (B.commGrid)->GetRankInProcCol();
for (int i = 0; i < stages; ++i) {
std::vector<IU> ess;
if (i == Aself) {
ARecv = A1seq; // shallow-std::copy
} else {
ess.resize(UDERA::esscount);
for (int j = 0; j < UDERA::esscount; ++j) {
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDERA(); // first, create the object
}
SpParHelper::BCastMatrix(GridC->GetRowWorld(), *ARecv, ess,
i); // then, receive its elements
ess.clear();
if (i == Bself) {
BRecv = B1seq; // shallow-std::copy
} else {
ess.resize(UDERB::esscount);
for (int j = 0; j < UDERB::esscount; ++j) {
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDERB();
}
SpParHelper::BCastMatrix(GridC->GetColWorld(), *BRecv, ess,
i); // then, receive its elements
SpTuples<IU, NUO>* C_cont = MultiplyReturnTuples<SR, NUO>(
*ARecv, *BRecv, // parameters themselves
false, true, // transpose information (B is transposed)
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
if (!C_cont->isZero())
tomerge.push_back(C_cont);
else
delete C_cont;
}
if (clearA) delete A1seq;
if (clearB) delete B1seq;
// Set the new dimensions
SpParHelper::GetSetSizes(*A2seq, ARecvSizes, (A.commGrid)->GetRowWorld());
SpParHelper::GetSetSizes(*B2seq, BRecvSizes, (B.commGrid)->GetColWorld());
// Start the second round
for (int i = 0; i < stages; ++i) {
std::vector<IU> ess;
if (i == Aself) {
ARecv = A2seq; // shallow-std::copy
} else {
ess.resize(UDERA::esscount);
for (int j = 0; j < UDERA::esscount; ++j) {
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDERA(); // first, create the object
}
SpParHelper::BCastMatrix(GridC->GetRowWorld(), *ARecv, ess,
i); // then, receive its elements
ess.clear();
if (i == Bself) {
BRecv = B2seq; // shallow-std::copy
} else {
ess.resize(UDERB::esscount);
for (int j = 0; j < UDERB::esscount; ++j) {
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDERB();
}
SpParHelper::BCastMatrix(GridC->GetColWorld(), *BRecv, ess,
i); // then, receive its elements
SpTuples<IU, NUO>* C_cont = MultiplyReturnTuples<SR, NUO>(
*ARecv, *BRecv, // parameters themselves
false, true, // transpose information (B is transposed)
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
if (!C_cont->isZero())
tomerge.push_back(C_cont);
else
delete C_cont;
}
SpHelper::deallocate2D(ARecvSizes, UDERA::esscount);
SpHelper::deallocate2D(BRecvSizes, UDERB::esscount);
if (clearA) {
delete A2seq;
delete A.spSeq;
A.spSeq = NULL;
} else {
(A.spSeq)->Merge(*A1seq, *A2seq);
delete A1seq;
delete A2seq;
}
if (clearB) {
delete B2seq;
delete B.spSeq;
B.spSeq = NULL;
} else {
(B.spSeq)->Merge(*B1seq, *B2seq);
delete B1seq;
delete B2seq;
const_cast<UDERB*>(B.spSeq)->Transpose(); // transpose back to original
}
UDERO* C = new UDERO(MergeAll<SR>(tomerge, C_m, C_n, true), false);
// First std::get the result in SpTuples, then convert to UDER
return SpParMat<IU, NUO, UDERO>(C, GridC); // return the result object
}
/**
* Parallel A = B*C routine that uses only MPI-1 features
* Relies on simple blocking broadcast
* @pre { Input matrices, A and B, should not alias }
**/
template <typename SR, typename NUO, typename UDERO, typename IU, typename NU1,
typename NU2, typename UDERA, typename UDERB>
SpParMat<IU, NUO, UDERO> Mult_AnXBn_Synch(SpParMat<IU, NU1, UDERA>& A,
SpParMat<IU, NU2, UDERB>& B,
bool clearA = false,
bool clearB = false)
{
if (!CheckSpGEMMCompliance(A, B)) {
return SpParMat<IU, NUO, UDERO>();
}
int stages, dummy; // last two parameters of ProductGrid are ignored for
// Synch multiplication
std::shared_ptr<CommGrid> GridC =
ProductGrid((A.commGrid).get(), (B.commGrid).get(), stages, dummy, dummy);
IU C_m = A.spSeq->getnrow();
IU C_n = B.spSeq->getncol();
const_cast<UDERB*>(B.spSeq)->Transpose();
MPI_Barrier(GridC->GetWorld());
IU** ARecvSizes = SpHelper::allocate2D<IU>(UDERA::esscount, stages);
IU** BRecvSizes = SpHelper::allocate2D<IU>(UDERB::esscount, stages);
SpParHelper::GetSetSizes(*(A.spSeq), ARecvSizes, (A.commGrid)->GetRowWorld());
SpParHelper::GetSetSizes(*(B.spSeq), BRecvSizes, (B.commGrid)->GetColWorld());
// Remotely fetched matrices are stored as pointers
UDERA* ARecv;
UDERB* BRecv;
std::vector<SpTuples<IU, NUO>*> tomerge;
int Aself = (A.commGrid)->GetRankInProcRow();
int Bself = (B.commGrid)->GetRankInProcCol();
for (int i = 0; i < stages; ++i) {
std::vector<IU> ess;
if (i == Aself) {
ARecv = A.spSeq; // shallow-std::copy
} else {
ess.resize(UDERA::esscount);
for (int j = 0; j < UDERA::esscount; ++j) {
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDERA(); // first, create the object
}
SpParHelper::BCastMatrix(GridC->GetRowWorld(), *ARecv, ess,
i); // then, receive its elements
ess.clear();
if (i == Bself) {
BRecv = B.spSeq; // shallow-std::copy
} else {
ess.resize(UDERB::esscount);
for (int j = 0; j < UDERB::esscount; ++j) {
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDERB();
}
SpParHelper::BCastMatrix(GridC->GetColWorld(), *BRecv, ess,
i); // then, receive its elements
SpTuples<IU, NUO>* C_cont = MultiplyReturnTuples<SR, NUO>(
*ARecv, *BRecv, // parameters themselves
false, true, // transpose information (B is transposed)
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
if (!C_cont->isZero()) tomerge.push_back(C_cont);
}
if (clearA && A.spSeq != NULL) {
delete A.spSeq;
A.spSeq = NULL;
}
if (clearB && B.spSeq != NULL) {
delete B.spSeq;
B.spSeq = NULL;
}
SpHelper::deallocate2D(ARecvSizes, UDERA::esscount);
SpHelper::deallocate2D(BRecvSizes, UDERB::esscount);
UDERO* C = new UDERO(MergeAll<SR>(tomerge, C_m, C_n, true), false);
// First std::get the result in SpTuples, then convert to UDER
// the last parameter to MergeAll deletes tomerge arrays
if (!clearB)
const_cast<UDERB*>(B.spSeq)->Transpose(); // transpose back to original
return SpParMat<IU, NUO, UDERO>(C, GridC); // return the result object
}
template <typename MATRIX, typename VECTOR>
void CheckSpMVCompliance(const MATRIX& A, const VECTOR& x) {
if (A.getncol() != x.TotalLength()) {
std::ostringstream outs;
outs << "Can not multiply, dimensions does not match" << std::endl;
outs << A.getncol() << " != " << x.TotalLength() << std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
}
if (!(*(A.getcommgrid()) == *(x.getcommgrid()))) {
std::cout << "Grids are not comparable for SpMV" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
}
}
template <typename SR, typename IU, typename NUM, typename UDER>
FullyDistSpVec<IU, typename promote_trait<NUM, IU>::T_promote> SpMV(
const SpParMat<IU, NUM, UDER>& A, const FullyDistSpVec<IU, IU>& x,
bool indexisvalue,
OptBuf<int32_t, typename promote_trait<NUM, IU>::T_promote>& optbuf);
template <typename SR, typename IU, typename NUM, typename UDER>
FullyDistSpVec<IU, typename promote_trait<NUM, IU>::T_promote> SpMV(
const SpParMat<IU, NUM, UDER>& A, const FullyDistSpVec<IU, IU>& x,
bool indexisvalue) {
typedef typename promote_trait<NUM, IU>::T_promote T_promote;
OptBuf<int32_t, T_promote> optbuf = OptBuf<int32_t, T_promote>();
return SpMV<SR>(A, x, indexisvalue, optbuf);
}
/**
* Step 1 of the sparse SpMV algorithm
* @param[in,out] trxlocnz, lenuntil,trxinds,trxnums { set or allocated }
* @param[in] indexisvalue
**/
template <typename IU, typename NV>
void TransposeVector(MPI_Comm& World, const FullyDistSpVec<IU, NV>& x,
int32_t& trxlocnz, IU& lenuntil, int32_t*& trxinds,
NV*& trxnums, bool indexisvalue) {
int32_t xlocnz = (int32_t)x.getlocnnz();
int32_t roffst = (int32_t)x.RowLenUntil(); // since trxinds is int32_t
int32_t roffset;
IU luntil = x.LengthUntil();
int diagneigh = x.commGrid->GetComplementRank();
MPI_Status status;
MPI_Sendrecv(&roffst, 1, MPIType<int32_t>(), diagneigh, TROST, &roffset, 1,
MPIType<int32_t>(), diagneigh, TROST, World, &status);
MPI_Sendrecv(&xlocnz, 1, MPIType<int32_t>(), diagneigh, TRNNZ, &trxlocnz, 1,
MPIType<int32_t>(), diagneigh, TRNNZ, World, &status);
MPI_Sendrecv(&luntil, 1, MPIType<IU>(), diagneigh, TRLUT, &lenuntil, 1,
MPIType<IU>(), diagneigh, TRLUT, World, &status);
// ABAB: Important observation is that local indices (given by x.ind) is
// 32-bit addressible
// Copy them to 32 bit integers and transfer that to save 50% of off-node
// bandwidth
trxinds = new int32_t[trxlocnz];
int32_t* temp_xind = new int32_t[xlocnz];
for (int i = 0; i < xlocnz; ++i) temp_xind[i] = (int32_t)x.ind[i];
MPI_Sendrecv(temp_xind, xlocnz, MPIType<int32_t>(), diagneigh, TRI, trxinds,
trxlocnz, MPIType<int32_t>(), diagneigh, TRI, World, &status);
delete[] temp_xind;
if (!indexisvalue) {
trxnums = new NV[trxlocnz];
MPI_Sendrecv(const_cast<NV*>(SpHelper::p2a(x.num)), xlocnz, MPIType<NV>(),
diagneigh, TRX, trxnums, trxlocnz, MPIType<NV>(), diagneigh,
TRX, World, &status);
}
std::transform(trxinds, trxinds + trxlocnz, trxinds,
bind2nd(std::plus<int32_t>(), roffset)); // fullydist indexing (p
// pieces) -> matrix indexing
// (sqrt(p) pieces)
}
/**
* Step 2 of the sparse SpMV algorithm
* @param[in,out] trxinds, trxnums { deallocated }
* @param[in,out] indacc, numacc { allocated }
* @param[in,out] accnz { set }
* @param[in] trxlocnz, lenuntil, indexisvalue
**/
template <typename IU, typename NV>
void AllGatherVector(MPI_Comm& ColWorld, int trxlocnz, IU lenuntil,
int32_t*& trxinds, NV*& trxnums, int32_t*& indacc,
NV*& numacc, int& accnz, bool indexisvalue) {
int colneighs, colrank;
MPI_Comm_size(ColWorld, &colneighs);
MPI_Comm_rank(ColWorld, &colrank);
int* colnz = new int[colneighs];
colnz[colrank] = trxlocnz;
MPI_Allgather(MPI_IN_PLACE, 1, MPI_INT, colnz, 1, MPI_INT, ColWorld);
int* dpls = new int[colneighs](); // displacements (zero initialized pid)
std::partial_sum(colnz, colnz + colneighs - 1, dpls + 1);
accnz = std::accumulate(colnz, colnz + colneighs, 0);
indacc = new int32_t[accnz];
numacc = new NV[accnz];
// ABAB: Future issues here, colnz is of type int (MPI limitation)
// What if the aggregate std::vector size along the processor row/column is not
// 32-bit addressible?
// This will happen when n/sqrt(p) > 2^31
// Currently we can solve a small problem (scale 32) with 4096 processor
// For a medium problem (scale 35), we'll need 32K processors which gives
// sqrt(p) ~ 180
// 2^35 / 180 ~ 2^29 / 3 which is not an issue !
#ifdef TIMING
double t0 = MPI_Wtime();
#endif
MPI_Allgatherv(trxinds, trxlocnz, MPIType<int32_t>(), indacc, colnz, dpls,
MPIType<int32_t>(), ColWorld);
delete[] trxinds;
if (indexisvalue) {
IU lenuntilcol;
if (colrank == 0) lenuntilcol = lenuntil;
MPI_Bcast(&lenuntilcol, 1, MPIType<IU>(), 0, ColWorld);
for (int i = 0; i < accnz; ++i) // std::fill numerical values from indices
{
numacc[i] = indacc[i] + lenuntilcol;
}
} else {
MPI_Allgatherv(trxnums, trxlocnz, MPIType<NV>(), numacc, colnz, dpls,
MPIType<NV>(), ColWorld);
delete[] trxnums;
}
#ifdef TIMING
double t1 = MPI_Wtime();
cblas_allgathertime += (t1 - t0);
#endif
DeleteAll(colnz, dpls);
}
/**
* Step 3 of the sparse SpMV algorithm, with the semiring
* @param[in,out] optbuf {scratch space for all-to-all (fold) communication}
* @param[in,out] indacc, numacc {index and values of the input std::vector, deleted
*upon exit}
* @param[in,out] sendindbuf, sendnumbuf {index and values of the output
*std::vector, created}
**/
template <typename SR, typename IVT, typename OVT, typename IU, typename NUM,
typename UDER>
void LocalSpMV(const SpParMat<IU, NUM, UDER>& A, int rowneighs,
OptBuf<int32_t, OVT>& optbuf, int32_t*& indacc, IVT*& numacc,
int32_t*& sendindbuf, OVT*& sendnumbuf, int*& sdispls,
int* sendcnt, int accnz, bool indexisvalue) {
if (optbuf.totmax > 0) // graph500 optimization enabled
{
if (A.spSeq->getnsplit() > 0) {
// optbuf.{inds/nums/dspls} and sendcnt are all pre-allocated and only
// filled by dcsc_gespmv_threaded
dcsc_gespmv_threaded_setbuffers<SR>(*(A.spSeq), indacc, numacc, accnz,
optbuf.inds, optbuf.nums, sendcnt,
optbuf.dspls, rowneighs);
} else {
dcsc_gespmv<SR>(*(A.spSeq), indacc, numacc, accnz, optbuf.inds,
optbuf.nums, sendcnt, optbuf.dspls, rowneighs,
indexisvalue);
}
DeleteAll(indacc, numacc);
} else {
if (A.spSeq->getnsplit() > 0) {
// sendindbuf/sendnumbuf/sdispls are all allocated and filled by
// dcsc_gespmv_threaded
int totalsent = generic_gespmv_threaded<SR>(*(A.spSeq), indacc, numacc,
accnz, sendindbuf, sendnumbuf,
sdispls, rowneighs);
DeleteAll(indacc, numacc);
for (int i = 0; i < rowneighs - 1; ++i)
sendcnt[i] = sdispls[i + 1] - sdispls[i];
sendcnt[rowneighs - 1] = totalsent - sdispls[rowneighs - 1];
} else {
// serial SpMV with sparse std::vector
std::vector<int32_t> indy;
std::vector<OVT> numy;
dcsc_gespmv<SR>(*(A.spSeq), indacc, numacc, accnz, indy,
numy); // actual multiplication
DeleteAll(indacc, numacc);
int32_t bufsize = indy.size(); // as compact as possible
sendindbuf = new int32_t[bufsize];
sendnumbuf = new OVT[bufsize];
int32_t perproc = A.getlocalrows() / rowneighs;
int k = 0; // index to buffer
for (int i = 0; i < rowneighs; ++i) {
int32_t end_this =
(i == rowneighs - 1) ? A.getlocalrows() : (i + 1) * perproc;
while (k < bufsize && indy[k] < end_this) {
sendindbuf[k] = indy[k] - i * perproc;
sendnumbuf[k] = numy[k];
++sendcnt[i];
++k;
}
}
sdispls = new int[rowneighs]();
std::partial_sum(sendcnt, sendcnt + rowneighs - 1, sdispls + 1);
}
}
}
template <typename SR, typename IU, typename OVT>
void MergeContributions(FullyDistSpVec<IU, OVT>& y, int*& recvcnt,
int*& rdispls, int32_t*& recvindbuf, OVT*& recvnumbuf,
int rowneighs) {
// free memory of y, in case it was aliased
std::vector<IU>().swap(y.ind);
std::vector<OVT>().swap(y.num);
#ifndef HEAPMERGE
IU ysize = y.MyLocLength(); // my local length is only O(n/p)
bool* isthere = new bool[ysize];
std::vector<std::pair<IU, OVT>> ts_pairs;
std::fill_n(isthere, ysize, false);
// We don't need to keep a "merger" because minimum will always come from the
// processor
// with the smallest rank; so a linear sweep over the received buffer is
// enough
for (int i = 0; i < rowneighs; ++i) {
for (int j = 0; j < recvcnt[i]; ++j) {
int32_t index = recvindbuf[rdispls[i] + j];
if (!isthere[index])
ts_pairs.push_back(std::make_pair(index, recvnumbuf[rdispls[i] + j]));
}
}
DeleteAll(recvcnt, rdispls);
DeleteAll(isthere, recvindbuf, recvnumbuf);
sort(ts_pairs.begin(), ts_pairs.end());
int nnzy = ts_pairs.size();
y.ind.resize(nnzy);
y.num.resize(nnzy);
for (int i = 0; i < nnzy; ++i) {
y.ind[i] = ts_pairs[i].first;
y.num[i] = ts_pairs[i].second;
}
#else
// Alternative 2: Heap-merge
int32_t hsize = 0;
int32_t inf = std::numeric_limits<int32_t>::min();
int32_t sup = std::numeric_limits<int32_t>::max();
KNHeap<int32_t, int32_t> sHeap(sup, inf);
int* processed = new int[rowneighs]();
for (int i = 0; i < rowneighs; ++i) {
if (recvcnt[i] > 0) {
// key, proc_id
sHeap.insert(recvindbuf[rdispls[i]], i);
++hsize;
}
}
int32_t key, locv;
if (hsize > 0) {
sHeap.deleteMin(&key, &locv);
y.ind.push_back(static_cast<IU>(key));
y.num.push_back(recvnumbuf[rdispls[locv]]); // nothing is processed yet
if ((++(processed[locv])) < recvcnt[locv])
sHeap.insert(recvindbuf[rdispls[locv] + processed[locv]], locv);
else
--hsize;
}
while (hsize > 0) {
sHeap.deleteMin(&key, &locv);
IU deref = rdispls[locv] + processed[locv];
if (y.ind.back() == static_cast<IU>(key)) // y.ind is surely not empty
{
y.num.back() = SR::add(y.num.back(), recvnumbuf[deref]);
// ABAB: Benchmark actually allows us to be non-deterministic in terms of
// parent selection
// We can just skip this addition operator (if it's a max/std::min select)
} else {
y.ind.push_back(static_cast<IU>(key));
y.num.push_back(recvnumbuf[deref]);
}
if ((++(processed[locv])) < recvcnt[locv])
sHeap.insert(recvindbuf[rdispls[locv] + processed[locv]], locv);
else
--hsize;
}
DeleteAll(recvcnt, rdispls, processed);
DeleteAll(recvindbuf, recvnumbuf);
#endif
}
/**
* This version is the most flexible sparse matrix X sparse std::vector [Used in
* KDT]
* It accepts different types for the matrix (NUM), the input std::vector (IVT) and
* the output std::vector (OVT)
* without relying on automatic type promotion
* Input (x) and output (y) std::vectors can be ALIASED because y is not written
* until the algorithm is done with x.
*/
template <typename SR, typename IVT, typename OVT, typename IU, typename NUM,
typename UDER>
void SpMV(const SpParMat<IU, NUM, UDER>& A, const FullyDistSpVec<IU, IVT>& x,
FullyDistSpVec<IU, OVT>& y, bool indexisvalue,
OptBuf<int32_t, OVT>& optbuf) {
CheckSpMVCompliance(A, x);
optbuf.MarkEmpty();
MPI_Comm World = x.commGrid->GetWorld();
MPI_Comm ColWorld = x.commGrid->GetColWorld();
MPI_Comm RowWorld = x.commGrid->GetRowWorld();
int accnz;
int32_t trxlocnz;
IU lenuntil;
int32_t *trxinds, *indacc;
IVT *trxnums, *numacc;
/* char errorstring[PAPI_MAX_STR_LEN+1];
int Events2Add [] = {PAPI_TOT_INS, PAPI_L1_TCM, PAPI_L2_TCM, PAPI_L3_TCM};
std::string EventNames [] = {"PAPI_TOT_INS", "PAPI_L1_TCM", "PAPI_L2_TCM",
"PAPI_L3_TCM"};
int arraysize = sizeof(Events2Add) / sizeof(int);
long long ptr2values[arraysize];
int errorcode = PAPI_start_counters(Events2Add, arraysize);
if (errorcode != PAPI_OK) {
PAPI_perror(errorcode, errorstring, PAPI_MAX_STR_LEN);
fprintf(stderr, "PAPI error (%d): %s\n", errorcode, errorstring);
}
*/
TransposeVector(World, x, trxlocnz, lenuntil, trxinds, trxnums, indexisvalue);
AllGatherVector(ColWorld, trxlocnz, lenuntil, trxinds, trxnums, indacc,
numacc, accnz, indexisvalue);
/*
errorcode = PAPI_read_counters(ptr2values, arraysize);
if (errorcode != PAPI_OK) {
PAPI_perror(errorcode, errorstring, PAPI_MAX_STR_LEN);
fprintf(stderr, "PAPI error (%d): %s\n", errorcode, errorstring);
}
errorcode = PAPI_stop_counters(ptr2values, arraysize);
*/
int rowneighs;
MPI_Comm_size(RowWorld, &rowneighs);
int* sendcnt = new int[rowneighs]();
int32_t* sendindbuf;
OVT* sendnumbuf;
int* sdispls;
LocalSpMV<SR>(A, rowneighs, optbuf, indacc, numacc, sendindbuf, sendnumbuf,
sdispls, sendcnt, accnz,
indexisvalue); // indacc/numacc deallocated,
// sendindbuf/sendnumbuf/sdispls allocated
int* rdispls = new int[rowneighs];
int* recvcnt = new int[rowneighs];
MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT,
RowWorld); // share the request counts
// receive displacements are exact whereas send displacements have slack
rdispls[0] = 0;
for (int i = 0; i < rowneighs - 1; ++i) {
rdispls[i + 1] = rdispls[i] + recvcnt[i];
}
int totrecv = std::accumulate(recvcnt, recvcnt + rowneighs, 0);
int32_t* recvindbuf = new int32_t[totrecv];
OVT* recvnumbuf = new OVT[totrecv];
#ifdef TIMING
double t2 = MPI_Wtime();
#endif
if (optbuf.totmax > 0) // graph500 optimization enabled
{
MPI_Alltoallv(optbuf.inds, sendcnt, optbuf.dspls, MPIType<int32_t>(),
recvindbuf, recvcnt, rdispls, MPIType<int32_t>(), RowWorld);
MPI_Alltoallv(optbuf.nums, sendcnt, optbuf.dspls, MPIType<OVT>(),
recvnumbuf, recvcnt, rdispls, MPIType<OVT>(), RowWorld);
delete[] sendcnt;
} else {
/* std::ofstream oput;
x.commGrid->OpenDebugFile("Send", oput);
oput << "To displacements: "; std::copy(sdispls, sdispls+rowneighs,
std::ostream_iterator<int>(oput, " ")); oput << std::endl;
oput << "To counts: "; std::copy(sendcnt, sendcnt+rowneighs,
std::ostream_iterator<int>(oput, " ")); oput << std::endl;
for(int i=0; i< rowneighs; ++i)
{
oput << "To neighbor: " << i << std::endl;
std::copy(sendindbuf+sdispls[i], sendindbuf+sdispls[i]+sendcnt[i],
std::ostream_iterator<int32_t>(oput, " ")); oput << std::endl;
std::copy(sendnumbuf+sdispls[i], sendnumbuf+sdispls[i]+sendcnt[i],
std::ostream_iterator<OVT>(oput, " ")); oput << std::endl;
}
oput.close(); */
MPI_Alltoallv(sendindbuf, sendcnt, sdispls, MPIType<int32_t>(), recvindbuf,
recvcnt, rdispls, MPIType<int32_t>(), RowWorld);
MPI_Alltoallv(sendnumbuf, sendcnt, sdispls, MPIType<OVT>(), recvnumbuf,
recvcnt, rdispls, MPIType<OVT>(), RowWorld);
DeleteAll(sendindbuf, sendnumbuf);
DeleteAll(sendcnt, sdispls);
}
#ifdef TIMING
double t3 = MPI_Wtime();
cblas_alltoalltime += (t3 - t2);
#endif
// std::ofstream output;
// A.commGrid->OpenDebugFile("Recv", output);
// std::copy(recvindbuf, recvindbuf+totrecv, std::ostream_iterator<IU>(output," "));
//output << std::endl;
// output.close();
MergeContributions<SR>(y, recvcnt, rdispls, recvindbuf, recvnumbuf,
rowneighs);
}
template <typename SR, typename IVT, typename OVT, typename IU, typename NUM,
typename UDER>
void SpMV(const SpParMat<IU, NUM, UDER>& A, const FullyDistSpVec<IU, IVT>& x,
FullyDistSpVec<IU, OVT>& y, bool indexisvalue) {
OptBuf<int32_t, OVT> optbuf = OptBuf<int32_t, OVT>();
SpMV<SR>(A, x, y, indexisvalue, optbuf);
}
/**
* Automatic type promotion is ONLY done here, all the callee functions (in
*Friends.h and below) are initialized with the promoted type
* If indexisvalues = true, then we do not need to transfer values for x
*(happens for BFS iterations with boolean matrices and integer rhs std::vectors)
**/
template <typename SR, typename IU, typename NUM, typename UDER>
FullyDistSpVec<IU, typename promote_trait<NUM, IU>::T_promote> SpMV(
const SpParMat<IU, NUM, UDER>& A, const FullyDistSpVec<IU, IU>& x,
bool indexisvalue,
OptBuf<int32_t, typename promote_trait<NUM, IU>::T_promote>& optbuf) {
typedef typename promote_trait<NUM, IU>::T_promote T_promote;
FullyDistSpVec<IU, T_promote> y(
x.getcommgrid(),
A.getnrow()); // identity doesn't matter for sparse std::vectors
SpMV<SR>(A, x, y, indexisvalue, optbuf);
return y;
}
/**
* Parallel dense SpMV
**/
template <typename SR, typename IU, typename NUM, typename NUV, typename UDER>
FullyDistVec<IU, typename promote_trait<NUM, NUV>::T_promote> SpMV(
const SpParMat<IU, NUM, UDER>& A, const FullyDistVec<IU, NUV>& x) {
typedef typename promote_trait<NUM, NUV>::T_promote T_promote;
CheckSpMVCompliance(A, x);
MPI_Comm World = x.commGrid->GetWorld();
MPI_Comm ColWorld = x.commGrid->GetColWorld();
MPI_Comm RowWorld = x.commGrid->GetRowWorld();
int xsize = (int)x.LocArrSize();
int trxsize = 0;
int diagneigh = x.commGrid->GetComplementRank();
MPI_Status status;
MPI_Sendrecv(&xsize, 1, MPI_INT, diagneigh, TRX, &trxsize, 1, MPI_INT,
diagneigh, TRX, World, &status);
NUV* trxnums = new NUV[trxsize];
MPI_Sendrecv(const_cast<NUV*>(SpHelper::p2a(x.arr)), xsize, MPIType<NUV>(),
diagneigh, TRX, trxnums, trxsize, MPIType<NUV>(), diagneigh, TRX,
World, &status);
int colneighs, colrank;
MPI_Comm_size(ColWorld, &colneighs);
MPI_Comm_rank(ColWorld, &colrank);
int* colsize = new int[colneighs];
colsize[colrank] = trxsize;
MPI_Allgather(MPI_IN_PLACE, 1, MPI_INT, colsize, 1, MPI_INT, ColWorld);
int* dpls = new int[colneighs](); // displacements (zero initialized pid)
std::partial_sum(colsize, colsize + colneighs - 1, dpls + 1);
int accsize = std::accumulate(colsize, colsize + colneighs, 0);
NUV* numacc = new NUV[accsize];
MPI_Allgatherv(trxnums, trxsize, MPIType<NUV>(), numacc, colsize, dpls,
MPIType<NUV>(), ColWorld);
delete[] trxnums;
// serial SpMV with dense std::vector
T_promote id = SR::id();
IU ysize = A.getlocalrows();
T_promote* localy = new T_promote[ysize];
std::fill_n(localy, ysize, id);
dcsc_gespmv<SR>(*(A.spSeq), numacc, localy);
DeleteAll(numacc, colsize, dpls);
// FullyDistVec<IT,NT>(std::shared_ptr<CommGrid> grid, IT globallen, NT initval, NT
// id)
FullyDistVec<IU, T_promote> y(x.commGrid, A.getnrow(), id);
int rowneighs;
MPI_Comm_size(RowWorld, &rowneighs);
IU begptr, endptr;
for (int i = 0; i < rowneighs; ++i) {
begptr = y.RowLenUntil(i);
if (i == rowneighs - 1) {
endptr = ysize;
} else {
endptr = y.RowLenUntil(i + 1);
}
MPI_Reduce(localy + begptr, SpHelper::p2a(y.arr), endptr - begptr,
MPIType<T_promote>(), SR::mpi_op(), i, RowWorld);
}
delete[] localy;
return y;
}
/**
* Old version that is no longer considered optimal
* Kept for legacy purposes
* To be removed when other functionals are fully tested.
**/
template <typename SR, typename IU, typename NUM, typename NUV, typename UDER>
FullyDistSpVec<IU, typename promote_trait<NUM, NUV>::T_promote> SpMV(
const SpParMat<IU, NUM, UDER>& A, const FullyDistSpVec<IU, NUV>& x) {
typedef typename promote_trait<NUM, NUV>::T_promote T_promote;
CheckSpMVCompliance(A, x);
MPI_Comm World = x.commGrid->GetWorld();
MPI_Comm ColWorld = x.commGrid->GetColWorld();
MPI_Comm RowWorld = x.commGrid->GetRowWorld();
int xlocnz = (int)x.getlocnnz();
int trxlocnz = 0;
int roffst = x.RowLenUntil();
int offset;
int diagneigh = x.commGrid->GetComplementRank();
MPI_Status status;
MPI_Sendrecv(&xlocnz, 1, MPI_INT, diagneigh, TRX, &trxlocnz, 1, MPI_INT,
diagneigh, TRX, World, &status);
MPI_Sendrecv(&roffst, 1, MPI_INT, diagneigh, TROST, &offset, 1, MPI_INT,
diagneigh, TROST, World, &status);
IU* trxinds = new IU[trxlocnz];
NUV* trxnums = new NUV[trxlocnz];
MPI_Sendrecv(const_cast<IU*>(SpHelper::p2a(x.ind)), xlocnz, MPIType<IU>(),
diagneigh, TRX, trxinds, trxlocnz, MPIType<IU>(), diagneigh, TRX,
World, &status);
MPI_Sendrecv(const_cast<NUV*>(SpHelper::p2a(x.num)), xlocnz, MPIType<NUV>(),
diagneigh, TRX, trxnums, trxlocnz, MPIType<NUV>(), diagneigh,
TRX, World, &status);
std::transform(trxinds, trxinds + trxlocnz, trxinds,
bind2nd(std::plus<IU>(), offset)); // fullydist indexing (n pieces) ->
// matrix indexing (sqrt(p) pieces)
int colneighs, colrank;
MPI_Comm_size(ColWorld, &colneighs);
MPI_Comm_rank(ColWorld, &colrank);
int* colnz = new int[colneighs];
colnz[colrank] = trxlocnz;
MPI_Allgather(MPI_IN_PLACE, 1, MPI_INT, colnz, 1, MPI_INT, ColWorld);
int* dpls = new int[colneighs](); // displacements (zero initialized pid)
std::partial_sum(colnz, colnz + colneighs - 1, dpls + 1);
int accnz = std::accumulate(colnz, colnz + colneighs, 0);
IU* indacc = new IU[accnz];
NUV* numacc = new NUV[accnz];
// ABAB: Future issues here, colnz is of type int (MPI limitation)
// What if the aggregate std::vector size along the processor row/column is not
// 32-bit addressible?
MPI_Allgatherv(trxinds, trxlocnz, MPIType<IU>(), indacc, colnz, dpls,
MPIType<IU>(), ColWorld);
MPI_Allgatherv(trxnums, trxlocnz, MPIType<NUV>(), numacc, colnz, dpls,
MPIType<NUV>(), ColWorld);
DeleteAll(trxinds, trxnums);
// serial SpMV with sparse std::vector
std::vector<int32_t> indy;
std::vector<T_promote> numy;
int32_t* tmpindacc = new int32_t[accnz];
for (int i = 0; i < accnz; ++i) tmpindacc[i] = indacc[i];
delete[] indacc;
dcsc_gespmv<SR>(*(A.spSeq), tmpindacc, numacc, accnz, indy,
numy); // actual multiplication
DeleteAll(tmpindacc, numacc);
DeleteAll(colnz, dpls);
FullyDistSpVec<IU, T_promote> y(
x.commGrid, A.getnrow()); // identity doesn't matter for sparse std::vectors
IU yintlen = y.MyRowLength();
int rowneighs;
MPI_Comm_size(RowWorld, &rowneighs);
std::vector<std::vector<IU>> sendind(rowneighs);
std::vector<std::vector<T_promote>> sendnum(rowneighs);
typename std::vector<int32_t>::size_type outnz = indy.size();
for (typename std::vector<IU>::size_type i = 0; i < outnz; ++i) {
IU locind;
int rown = y.OwnerWithinRow(yintlen, static_cast<IU>(indy[i]), locind);
sendind[rown].push_back(locind);
sendnum[rown].push_back(numy[i]);
}
IU* sendindbuf = new IU[outnz];
T_promote* sendnumbuf = new T_promote[outnz];
int* sendcnt = new int[rowneighs];
int* sdispls = new int[rowneighs];
for (int i = 0; i < rowneighs; ++i) sendcnt[i] = sendind[i].size();
int* rdispls = new int[rowneighs];
int* recvcnt = new int[rowneighs];
MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT,
RowWorld); // share the request counts
sdispls[0] = 0;
rdispls[0] = 0;
for (int i = 0; i < rowneighs - 1; ++i) {
sdispls[i + 1] = sdispls[i] + sendcnt[i];
rdispls[i + 1] = rdispls[i] + recvcnt[i];
}
int totrecv = std::accumulate(recvcnt, recvcnt + rowneighs, 0);
IU* recvindbuf = new IU[totrecv];
T_promote* recvnumbuf = new T_promote[totrecv];
for (int i = 0; i < rowneighs; ++i) {
std::copy(sendind[i].begin(), sendind[i].end(), sendindbuf + sdispls[i]);
std::vector<IU>().swap(sendind[i]);
}
for (int i = 0; i < rowneighs; ++i) {
std::copy(sendnum[i].begin(), sendnum[i].end(), sendnumbuf + sdispls[i]);
std::vector<T_promote>().swap(sendnum[i]);
}
MPI_Alltoallv(sendindbuf, sendcnt, sdispls, MPIType<IU>(), recvindbuf,
recvcnt, rdispls, MPIType<IU>(), RowWorld);
MPI_Alltoallv(sendnumbuf, sendcnt, sdispls, MPIType<T_promote>(), recvnumbuf,
recvcnt, rdispls, MPIType<T_promote>(), RowWorld);
DeleteAll(sendindbuf, sendnumbuf);
DeleteAll(sendcnt, recvcnt, sdispls, rdispls);
// define a SPA-like data structure
IU ysize = y.MyLocLength();
T_promote* localy = new T_promote[ysize];
bool* isthere = new bool[ysize];
std::vector<IU> nzinds; // nonzero indices
std::fill_n(isthere, ysize, false);
for (int i = 0; i < totrecv; ++i) {
if (!isthere[recvindbuf[i]]) {
localy[recvindbuf[i]] = recvnumbuf[i]; // initial assignment
nzinds.push_back(recvindbuf[i]);
isthere[recvindbuf[i]] = true;
} else {
localy[recvindbuf[i]] = SR::add(localy[recvindbuf[i]], recvnumbuf[i]);
}
}
DeleteAll(isthere, recvindbuf, recvnumbuf);
sort(nzinds.begin(), nzinds.end());
int nnzy = nzinds.size();
y.ind.resize(nnzy);
y.num.resize(nnzy);
for (int i = 0; i < nnzy; ++i) {
y.ind[i] = nzinds[i];
y.num[i] = localy[nzinds[i]];
}
delete[] localy;
return y;
}
template <typename IU, typename NU1, typename NU2, typename UDERA,
typename UDERB>
SpParMat<IU, typename promote_trait<NU1, NU2>::T_promote,
typename promote_trait<UDERA, UDERB>::T_promote>
EWiseMult(const SpParMat<IU, NU1, UDERA>& A, const SpParMat<IU, NU2, UDERB>& B,
bool exclude) {
typedef typename promote_trait<NU1, NU2>::T_promote N_promote;
typedef typename promote_trait<UDERA, UDERB>::T_promote DER_promote;
if (*(A.commGrid) == *(B.commGrid)) {
DER_promote* result =
new DER_promote(EWiseMult(*(A.spSeq), *(B.spSeq), exclude));
return SpParMat<IU, N_promote, DER_promote>(result, A.commGrid);
} else {
std::cout << "Grids are not comparable elementwise multiplication" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return SpParMat<IU, N_promote, DER_promote>();
}
}
template <typename RETT, typename RETDER, typename IU, typename NU1,
typename NU2, typename UDERA, typename UDERB,
typename _BinaryOperation>
SpParMat<IU, RETT, RETDER> EWiseApply(const SpParMat<IU, NU1, UDERA>& A,
const SpParMat<IU, NU2, UDERB>& B,
_BinaryOperation __binary_op, bool notB,
const NU2& defaultBVal) {
if (*(A.commGrid) == *(B.commGrid)) {
RETDER* result = new RETDER(EWiseApply<RETT>(
*(A.spSeq), *(B.spSeq), __binary_op, notB, defaultBVal));
return SpParMat<IU, RETT, RETDER>(result, A.commGrid);
} else {
std::cout << "Grids are not comparable elementwise apply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return SpParMat<IU, RETT, RETDER>();
}
}
template <typename RETT, typename RETDER, typename IU, typename NU1,
typename NU2, typename UDERA, typename UDERB,
typename _BinaryOperation, typename _BinaryPredicate>
SpParMat<IU, RETT, RETDER> EWiseApply(
const SpParMat<IU, NU1, UDERA>& A, const SpParMat<IU, NU2, UDERB>& B,
_BinaryOperation __binary_op, _BinaryPredicate do_op, bool allowANulls,
bool allowBNulls, const NU1& ANullVal, const NU2& BNullVal,
const bool allowIntersect, const bool useExtendedBinOp) {
if (*(A.commGrid) == *(B.commGrid)) {
RETDER* result = new RETDER(EWiseApply<RETT>(
*(A.spSeq), *(B.spSeq), __binary_op, do_op, allowANulls, allowBNulls,
ANullVal, BNullVal, allowIntersect));
return SpParMat<IU, RETT, RETDER>(result, A.commGrid);
} else {
std::cout << "Grids are not comparable elementwise apply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return SpParMat<IU, RETT, RETDER>();
}
}
// plain adapter
template <typename RETT, typename RETDER, typename IU, typename NU1,
typename NU2, typename UDERA, typename UDERB,
typename _BinaryOperation, typename _BinaryPredicate>
SpParMat<IU, RETT, RETDER> EWiseApply(const SpParMat<IU, NU1, UDERA>& A,
const SpParMat<IU, NU2, UDERB>& B,
_BinaryOperation __binary_op,
_BinaryPredicate do_op, bool allowANulls,
bool allowBNulls, const NU1& ANullVal,
const NU2& BNullVal,
const bool allowIntersect = true) {
return EWiseApply<RETT, RETDER>(
A, B,
EWiseExtToPlainAdapter<RETT, NU1, NU2, _BinaryOperation>(__binary_op),
EWiseExtToPlainAdapter<bool, NU1, NU2, _BinaryPredicate>(do_op),
allowANulls, allowBNulls, ANullVal, BNullVal, allowIntersect, true);
}
// end adapter
/**
* if exclude is true, then we prune all entries W[i] != zero from V
* if exclude is false, then we perform a proper elementwise multiplication
**/
template <typename IU, typename NU1, typename NU2>
SpParVec<IU, typename promote_trait<NU1, NU2>::T_promote> EWiseMult(
const SpParVec<IU, NU1>& V, const DenseParVec<IU, NU2>& W, bool exclude,
NU2 zero) {
typedef typename promote_trait<NU1, NU2>::T_promote T_promote;
if (*(V.commGrid) == *(W.commGrid)) {
SpParVec<IU, T_promote> Product(V.commGrid);
Product.length = V.length;
if (Product.diagonal) {
if (exclude) {
IU size = V.ind.size();
for (IU i = 0; i < size; ++i) {
if (W.arr.size() <= V.ind[i] ||
W.arr[V.ind[i]] == zero) // keep only those
{
Product.ind.push_back(V.ind[i]);
Product.num.push_back(V.num[i]);
}
}
} else {
IU size = V.ind.size();
for (IU i = 0; i < size; ++i) {
if (W.arr.size() > V.ind[i] &&
W.arr[V.ind[i]] != zero) // keep only those
{
Product.ind.push_back(V.ind[i]);
Product.num.push_back(V.num[i] * W.arr[V.ind[i]]);
}
}
}
}
return Product;
} else {
std::cout << "Grids are not comparable elementwise multiplication" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return SpParVec<IU, T_promote>();
}
}
/**
* if exclude is true, then we prune all entries W[i] != zero from V
* if exclude is false, then we perform a proper elementwise multiplication
**/
template <typename IU, typename NU1, typename NU2>
FullyDistSpVec<IU, typename promote_trait<NU1, NU2>::T_promote> EWiseMult(
const FullyDistSpVec<IU, NU1>& V, const FullyDistVec<IU, NU2>& W,
bool exclude, NU2 zero) {
typedef typename promote_trait<NU1, NU2>::T_promote T_promote;
if (*(V.commGrid) == *(W.commGrid)) {
FullyDistSpVec<IU, T_promote> Product(V.commGrid);
if (V.glen != W.glen) {
std::cerr << "Vector dimensions don't match for EWiseMult\n";
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
} else {
Product.glen = V.glen;
IU size = V.getlocnnz();
if (exclude) {
#if defined(_OPENMP) && defined(CBLAS_EXPERIMENTAL) // not faster than serial
int actual_splits = cblas_splits * 1; // 1 is the parallel slackness
std::vector<IU> tlosizes(actual_splits, 0);
std::vector<std::vector<IU>> tlinds(actual_splits);
std::vector<std::vector<T_promote>> tlnums(actual_splits);
IU tlsize = size / actual_splits;
#pragma omp parallel for // schedule(dynamic, 1)
for (IU t = 0; t < actual_splits; ++t) {
IU tlbegin = t * tlsize;
IU tlend = (t == actual_splits - 1) ? size : (t + 1) * tlsize;
for (IU i = tlbegin; i < tlend; ++i) {
if (W.arr[V.ind[i]] == zero) // keep only those
{
tlinds[t].push_back(V.ind[i]);
tlnums[t].push_back(V.num[i]);
tlosizes[t]++;
}
}
}
std::vector<IU> prefix_sum(actual_splits + 1, 0);
std::partial_sum(tlosizes.begin(), tlosizes.end(), prefix_sum.begin() + 1);
Product.ind.resize(prefix_sum[actual_splits]);
Product.num.resize(prefix_sum[actual_splits]);
#pragma omp parallel for // schedule(dynamic, 1)
for (IU t = 0; t < actual_splits; ++t) {
std::copy(tlinds[t].begin(), tlinds[t].end(),
Product.ind.begin() + prefix_sum[t]);
std::copy(tlnums[t].begin(), tlnums[t].end(),
Product.num.begin() + prefix_sum[t]);
}
#else
for (IU i = 0; i < size; ++i) {
if (W.arr[V.ind[i]] == zero) // keep only those
{
Product.ind.push_back(V.ind[i]);
Product.num.push_back(V.num[i]);
}
}
#endif
} else {
for (IU i = 0; i < size; ++i) {
if (W.arr[V.ind[i]] != zero) // keep only those
{
Product.ind.push_back(V.ind[i]);
Product.num.push_back(V.num[i] * W.arr[V.ind[i]]);
}
}
}
}
return Product;
} else {
std::cout << "Grids are not comparable elementwise multiplication" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return FullyDistSpVec<IU, T_promote>();
}
}
/**
Threaded EWiseApply
**/
template <typename RET, typename IU, typename NU1, typename NU2,
typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU, RET> EWiseApply_threaded(const FullyDistSpVec<IU, NU1>& V,
const FullyDistVec<IU, NU2>& W,
_BinaryOperation _binary_op,
_BinaryPredicate _doOp,
bool allowVNulls, NU1 Vzero,
const bool useExtendedBinOp) {
typedef RET T_promote; // typedef typename promote_trait<NU1,NU2>::T_promote
// T_promote;
if (*(V.commGrid) == *(W.commGrid)) {
FullyDistSpVec<IU, T_promote> Product(V.commGrid);
if (V.TotalLength() != W.TotalLength()) {
std::ostringstream outs;
outs << "Vector dimensions don't match (" << V.TotalLength() << " vs "
<< W.TotalLength() << ") for EWiseApply (short version)\n";
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
} else {
int nthreads = 1;
#pragma omp parallel
#ifdef THREADED
{ nthreads = omp_get_num_threads(); }
#endif
Product.glen = V.glen;
IU size = W.LocArrSize();
IU spsize = V.getlocnnz();
// temporary result std::vectors per thread
std::vector<std::vector<IU>> tProductInd(nthreads);
std::vector<std::vector<T_promote>> tProductVal(nthreads);
IU perthread; // chunk of tProductInd or tProductVal allocated to each
// thread
if (allowVNulls)
perthread = size / nthreads;
else
perthread = spsize / nthreads;
#pragma omp parallel
{
#ifdef THREADED
int curthread = omp_get_thread_num();
#else
int curthread = 0;
#endif
IU tStartIdx = perthread * curthread;
IU tNextIdx = perthread * (curthread + 1);
if (allowVNulls) {
if (curthread == nthreads - 1) tNextIdx = size;
// std::get sparse part for the current thread
auto it = std::lower_bound(V.ind.begin(), V.ind.end(), tStartIdx);
IU tSpIdx = (IU)std::distance(V.ind.begin(), it);
// iterate over the dense std::vector
for (IU tIdx = tStartIdx; tIdx < tNextIdx; ++tIdx) {
if (tSpIdx < spsize && V.ind[tSpIdx] < tNextIdx &&
V.ind[tSpIdx] == tIdx) {
if (_doOp(V.num[tSpIdx], W.arr[tIdx], false, false)) {
tProductInd[curthread].push_back(tIdx);
tProductVal[curthread].push_back(
_binary_op(V.num[tSpIdx], W.arr[tIdx], false, false));
}
tSpIdx++;
} else {
if (_doOp(Vzero, W.arr[tIdx], true, false)) {
tProductInd[curthread].push_back(tIdx);
tProductVal[curthread].push_back(
_binary_op(Vzero, W.arr[tIdx], true, false));
}
}
}
} else // iterate over the sparse std::vector
{
if (curthread == nthreads - 1) tNextIdx = spsize;
for (IU tSpIdx = tStartIdx; tSpIdx < tNextIdx; ++tSpIdx) {
if (_doOp(V.num[tSpIdx], W.arr[V.ind[tSpIdx]], false, false)) {
tProductInd[curthread].push_back(V.ind[tSpIdx]);
tProductVal[curthread].push_back(_binary_op(
V.num[tSpIdx], W.arr[V.ind[tSpIdx]], false, false));
}
}
}
}
std::vector<IU> tdisp(nthreads + 1);
tdisp[0] = 0;
for (int i = 0; i < nthreads; ++i) {
tdisp[i + 1] = tdisp[i] + tProductInd[i].size();
}
// std::copy results from temporary std::vectors
Product.ind.resize(tdisp[nthreads]);
Product.num.resize(tdisp[nthreads]);
#pragma omp parallel
{
#ifdef THREADED
int curthread = omp_get_thread_num();
#else
int curthread = 0;
#endif
std::copy(tProductInd[curthread].begin(), tProductInd[curthread].end(),
Product.ind.data() + tdisp[curthread]);
std::copy(tProductVal[curthread].begin(), tProductVal[curthread].end(),
Product.num.data() + tdisp[curthread]);
}
}
return Product;
} else {
std::cout << "Grids are not comparable for EWiseApply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return FullyDistSpVec<IU, T_promote>();
}
}
/**
* Performs an arbitrary binary operation _binary_op on the corresponding
*elements of two std::vectors with the result stored in a return std::vector ret.
* The binary operatiation is only performed if the binary predicate _doOp
*returns true for those elements. Otherwise the binary operation is not
* performed and ret does not contain an element at that position.
* More formally the operation is defined as:
* if (_doOp(V[i], W[i]))
* ret[i] = _binary_op(V[i], W[i])
* else
* // ret[i] is not set
* Hence _doOp can be used to implement a filter on either of the std::vectors.
*
* The above is only defined if both V[i] and W[i] exist (i.e. an intersection).
*To allow a union operation (ex. when V[i] doesn't exist but W[i] does)
* the allowVNulls flag is set to true and the Vzero argument is used as the
*missing V[i] value.
*
* The type of each element of ret must not necessarily be related to the types
*of V or W, so the return type must be explicitly specified as a template
*parameter:
* FullyDistSpVec<int, double> r = EWiseApply<double>(V, W, std::plus, retTrue,
*false, 0)
**/
template <typename RET, typename IU, typename NU1, typename NU2,
typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU, RET> EWiseApply(const FullyDistSpVec<IU, NU1>& V,
const FullyDistVec<IU, NU2>& W,
_BinaryOperation _binary_op,
_BinaryPredicate _doOp, bool allowVNulls,
NU1 Vzero, const bool useExtendedBinOp) {
typedef RET T_promote; // typedef typename promote_trait<NU1,NU2>::T_promote
// T_promote;
if (*(V.commGrid) == *(W.commGrid)) {
FullyDistSpVec<IU, T_promote> Product(V.commGrid);
// FullyDistVec< IU, NU1> DV (V); // Ariful: I am not sure why it was
// there??
if (V.TotalLength() != W.TotalLength()) {
std::ostringstream outs;
outs << "Vector dimensions don't match (" << V.TotalLength() << " vs "
<< W.TotalLength() << ") for EWiseApply (short version)\n";
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
} else {
Product.glen = V.glen;
IU size = W.LocArrSize();
IU spsize = V.getlocnnz();
IU sp_iter = 0;
if (allowVNulls) {
// iterate over the dense std::vector
for (IU i = 0; i < size; ++i) {
if (sp_iter < spsize && V.ind[sp_iter] == i) {
if (_doOp(V.num[sp_iter], W.arr[i], false, false)) {
Product.ind.push_back(i);
Product.num.push_back(
_binary_op(V.num[sp_iter], W.arr[i], false, false));
}
sp_iter++;
} else {
if (_doOp(Vzero, W.arr[i], true, false)) {
Product.ind.push_back(i);
Product.num.push_back(_binary_op(Vzero, W.arr[i], true, false));
}
}
}
} else {
// iterate over the sparse std::vector
for (sp_iter = 0; sp_iter < spsize; ++sp_iter) {
if (_doOp(V.num[sp_iter], W.arr[V.ind[sp_iter]], false, false)) {
Product.ind.push_back(V.ind[sp_iter]);
Product.num.push_back(_binary_op(
V.num[sp_iter], W.arr[V.ind[sp_iter]], false, false));
}
}
}
}
return Product;
} else {
std::cout << "Grids are not comparable for EWiseApply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return FullyDistSpVec<IU, T_promote>();
}
}
/**
* Performs an arbitrary binary operation _binary_op on the corresponding
*elements of two std::vectors with the result stored in a return std::vector ret.
* The binary operatiation is only performed if the binary predicate _doOp
*returns true for those elements. Otherwise the binary operation is not
* performed and ret does not contain an element at that position.
* More formally the operation is defined as:
* if (_doOp(V[i], W[i]))
* ret[i] = _binary_op(V[i], W[i])
* else
* // ret[i] is not set
* Hence _doOp can be used to implement a filter on either of the std::vectors.
*
* The above is only defined if both V[i] and W[i] exist (i.e. an intersection).
*To allow a union operation (ex. when V[i] doesn't exist but W[i] does)
* the allowVNulls flag is set to true and the Vzero argument is used as the
*missing V[i] value.
* !allowVNulls && !allowWNulls => intersection
* !allowVNulls && allowWNulls => operate on all elements of V
* allowVNulls && !allowWNulls => operate on all elements of W
* allowVNulls && allowWNulls => union
*
* The type of each element of ret must not necessarily be related to the types
*of V or W, so the return type must be explicitly specified as a template
*parameter:
* FullyDistSpVec<int, double> r = EWiseApply<double>(V, W, std::plus, ...)
* For intersection, Vzero and Wzero are irrelevant
* ABAB: \todo: Should allowIntersect be "false" for all SetDifference uses?
**/
template <typename RET, typename IU, typename NU1, typename NU2,
typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU, RET> EWiseApply(const FullyDistSpVec<IU, NU1>& V,
const FullyDistSpVec<IU, NU2>& W,
_BinaryOperation _binary_op,
_BinaryPredicate _doOp, bool allowVNulls,
bool allowWNulls, NU1 Vzero, NU2 Wzero,
const bool allowIntersect,
const bool useExtendedBinOp) {
typedef RET
T_promote; // typename promote_trait<NU1,NU2>::T_promote T_promote;
if (*(V.commGrid) == *(W.commGrid)) {
FullyDistSpVec<IU, T_promote> Product(V.commGrid);
if (V.glen != W.glen) {
std::ostringstream outs;
outs << "Vector dimensions don't match (" << V.glen << " vs " << W.glen
<< ") for EWiseApply (full version)\n";
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
} else {
Product.glen = V.glen;
typename std::vector<IU>::const_iterator indV = V.ind.begin();
typename std::vector<NU1>::const_iterator numV = V.num.begin();
typename std::vector<IU>::const_iterator indW = W.ind.begin();
typename std::vector<NU2>::const_iterator numW = W.num.begin();
while (indV < V.ind.end() && indW < W.ind.end()) {
if (*indV == *indW) {
// overlap
if (allowIntersect) {
if (_doOp(*numV, *numW, false, false)) {
Product.ind.push_back(*indV);
Product.num.push_back(_binary_op(*numV, *numW, false, false));
}
}
indV++;
numV++;
indW++;
numW++;
} else if (*indV < *indW) {
// V has value but W does not
if (allowWNulls) {
if (_doOp(*numV, Wzero, false, true)) {
Product.ind.push_back(*indV);
Product.num.push_back(_binary_op(*numV, Wzero, false, true));
}
}
indV++;
numV++;
} else //(*indV > *indW)
{
// W has value but V does not
if (allowVNulls) {
if (_doOp(Vzero, *numW, true, false)) {
Product.ind.push_back(*indW);
Product.num.push_back(_binary_op(Vzero, *numW, true, false));
}
}
indW++;
numW++;
}
}
// clean up
while (allowWNulls && indV < V.ind.end()) {
if (_doOp(*numV, Wzero, false, true)) {
Product.ind.push_back(*indV);
Product.num.push_back(_binary_op(*numV, Wzero, false, true));
}
indV++;
numV++;
}
while (allowVNulls && indW < W.ind.end()) {
if (_doOp(Vzero, *numW, true, false)) {
Product.ind.push_back(*indW);
Product.num.push_back(_binary_op(Vzero, *numW, true, false));
}
indW++;
numW++;
}
}
return Product;
} else {
std::cout << "Grids are not comparable for EWiseApply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return FullyDistSpVec<IU, T_promote>();
}
}
// plain callback versions
template <typename RET, typename IU, typename NU1, typename NU2,
typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU, RET> EWiseApply(const FullyDistSpVec<IU, NU1>& V,
const FullyDistVec<IU, NU2>& W,
_BinaryOperation _binary_op,
_BinaryPredicate _doOp, bool allowVNulls,
NU1 Vzero) {
return EWiseApply<RET>(
V, W, EWiseExtToPlainAdapter<RET, NU1, NU2, _BinaryOperation>(_binary_op),
EWiseExtToPlainAdapter<bool, NU1, NU2, _BinaryPredicate>(_doOp),
allowVNulls, Vzero, true);
}
template <typename RET, typename IU, typename NU1, typename NU2,
typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU, RET> EWiseApply_threaded(const FullyDistSpVec<IU, NU1>& V,
const FullyDistVec<IU, NU2>& W,
_BinaryOperation _binary_op,
_BinaryPredicate _doOp,
bool allowVNulls, NU1 Vzero) {
return EWiseApply_threaded<RET>(
V, W, EWiseExtToPlainAdapter<RET, NU1, NU2, _BinaryOperation>(_binary_op),
EWiseExtToPlainAdapter<bool, NU1, NU2, _BinaryPredicate>(_doOp),
allowVNulls, Vzero, true);
}
template <typename RET, typename IU, typename NU1, typename NU2,
typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU, RET> EWiseApply(const FullyDistSpVec<IU, NU1>& V,
const FullyDistSpVec<IU, NU2>& W,
_BinaryOperation _binary_op,
_BinaryPredicate _doOp, bool allowVNulls,
bool allowWNulls, NU1 Vzero, NU2 Wzero,
const bool allowIntersect = true) {
return EWiseApply<RET>(
V, W, EWiseExtToPlainAdapter<RET, NU1, NU2, _BinaryOperation>(_binary_op),
EWiseExtToPlainAdapter<bool, NU1, NU2, _BinaryPredicate>(_doOp),
allowVNulls, allowWNulls, Vzero, Wzero, allowIntersect, true);
}
}
#endif
|
simd-clones-2.c | /* { dg-options "-fopenmp -fdump-tree-optimized -O" } */
#pragma omp declare simd inbranch uniform(c) linear(b:66)
#pragma omp declare simd notinbranch aligned(c:32)
int addit(int a, int b, int *c)
{
return a + b;
}
#pragma omp declare simd uniform(a) aligned(a:32) linear(k:1) notinbranch
float setArray(float *a, float x, int k)
{
a[k] = a[k] + x;
return a[k];
}
/* { dg-final { scan-tree-dump "_ZGVbN4ua32vl_setArray" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVbN4vvva32_addit" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVbM4vl66u_addit" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVcN8ua32vl_setArray" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVcN4vvva32_addit" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVcM4vl66u_addit" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVdN8ua32vl_setArray" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVdN8vvva32_addit" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVdM8vl66u_addit" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVeN16ua32vl_setArray" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVeN16vvva32_addit" "optimized" { target i?86-*-* x86_64-*-* } } } */
/* { dg-final { scan-tree-dump "_ZGVeM16vl66u_addit" "optimized" { target i?86-*-* x86_64-*-* } } } */
|
pyfr_driver_asp_reg.c | /******************************************************************************
** Copyright (c) 2014-2019, Intel Corporation **
** 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. **
******************************************************************************/
/* Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <sys/time.h>
#define REPS 100
#define REALTYPE double
static double sec(struct timeval start, struct timeval end) {
return ((double)(((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)))) / 1.0e6;
}
int my_csr_reader( const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
REALTYPE** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csr_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_row_idx_id = NULL;
unsigned int l_i = 0;
l_csr_file_handle = fopen( i_csr_file_in, "r" );
if ( l_csr_file_handle == NULL ) {
fprintf( stderr, "cannot open CSR file!\n" );
return -1;
}
while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
fprintf( stderr, "could not read file length!\n" );
return -1;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) &&
0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count)
{
/* allocate CSC datastructure matching mtx file */
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1));
*o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count));
l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_row_idx_id == NULL ) ) {
fprintf( stderr, "could not allocate sp data!\n" );
return -1;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1));
memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count));
memset(*o_values, 0, sizeof(double)*(*o_element_count));
memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count));
/* init column idx */
for ( l_i = 0; l_i < (*o_row_count + 1); l_i++)
(*o_row_idx)[l_i] = (*o_element_count);
/* init */
(*o_row_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
fprintf( stderr, "could not csr description!\n" );
return -1;
}
/* now we read the actual content */
} else {
unsigned int l_row, l_column;
REALTYPE l_value;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
fprintf( stderr, "could not read element!\n" );
return -1;
}
/* adjust numbers to zero termination */
l_row--;
l_column--;
/* add these values to row and value structure */
(*o_column_idx)[l_i] = l_column;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_row_idx_id[l_row] = 1;
(*o_row_idx)[l_row+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csr_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
fprintf( stderr, "we were not able to read all elements!\n" );
return -1;
}
/* let's handle empty rows */
for ( l_i = 0; l_i < (*o_row_count); l_i++) {
if ( l_row_idx_id[l_i] == 0 ) {
(*o_row_idx)[l_i+1] = (*o_row_idx)[l_i];
}
}
/* free helper data structure */
if ( l_row_idx_id != NULL ) {
free( l_row_idx_id );
}
return 0;
}
int main(int argc, char* argv[]) {
char* l_csr_file;
REALTYPE* l_a_sp;
unsigned int* l_rowptr;
unsigned int* l_colidx;
unsigned int l_rowcount, l_colcount, l_elements;
REALTYPE* l_a_dense;
REALTYPE* l_b;
REALTYPE* l_c_betaone;
REALTYPE* l_c_betazero;
REALTYPE* l_c_gold_betaone;
REALTYPE* l_c_gold_betazero;
REALTYPE* l_c_dense_betaone;
REALTYPE* l_c_dense_betazero;
REALTYPE l_max_error = 0.0;
unsigned int l_m;
unsigned int l_n;
unsigned int l_k;
unsigned int l_i;
unsigned int l_j;
unsigned int l_z;
unsigned int l_elems;
unsigned int l_reps;
unsigned int l_n_block;
struct timeval l_start, l_end;
double l_total;
double alpha = 1.0;
double beta = 1.0;
char trans = 'N';
libxsmm_dfsspmdm* gemm_op_betazero = NULL;
libxsmm_dfsspmdm* gemm_op_betaone = NULL;
if (argc != 4 ) {
fprintf( stderr, "need csr-filename N reps!\n" );
exit(-1);
}
/* read sparse A */
l_csr_file = argv[1];
l_n = atoi(argv[2]);
l_reps = atoi(argv[3]);
if (my_csr_reader( l_csr_file,
&l_rowptr,
&l_colidx,
&l_a_sp,
&l_rowcount, &l_colcount, &l_elements ) != 0 )
{
exit(-1);
}
l_m = l_rowcount;
l_k = l_colcount;
printf("CSR matrix data structure we just read:\n");
printf("rows: %u, columns: %u, elements: %u\n", l_rowcount, l_colcount, l_elements);
/* allocate dense matrices */
l_a_dense = (REALTYPE*)_mm_malloc(l_k * l_m * sizeof(REALTYPE), 64);
l_b = (REALTYPE*)_mm_malloc(l_k * l_n * sizeof(REALTYPE), 64);
l_c_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_gold_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_gold_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_dense_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
l_c_dense_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64);
/* touch B */
for ( l_i = 0; l_i < l_k*l_n; l_i++) {
l_b[l_i] = (REALTYPE)libxsmm_rng_f64();
}
/* touch dense A */
for ( l_i = 0; l_i < l_k*l_m; l_i++) {
l_a_dense[l_i] = (REALTYPE)0.0;
}
/* init dense A using sparse A */
for ( l_i = 0; l_i < l_m; l_i++ ) {
l_elems = l_rowptr[l_i+1] - l_rowptr[l_i];
for ( l_z = 0; l_z < l_elems; l_z++ ) {
l_a_dense[(l_i*l_k)+l_colidx[l_rowptr[l_i]+l_z]] = l_a_sp[l_rowptr[l_i]+l_z];
}
}
/* touch C */
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_gold_betaone[l_i] = (REALTYPE)libxsmm_rng_f64();
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_betaone[l_i] = l_c_gold_betaone[l_i];
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_dense_betaone[l_i] = l_c_gold_betaone[l_i];
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_betazero[l_i] = l_c_betaone[l_i];
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_gold_betazero[l_i] = l_c_gold_betaone[l_i];
}
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
l_c_dense_betazero[l_i] = l_c_dense_betaone[l_i];
}
/* setting up fsspmdm */
l_n_block = 48;
beta = 0.0;
gemm_op_betazero = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense );
beta = 1.0;
gemm_op_betaone = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense );
/* compute golden results */
printf("computing golden solution...\n");
for ( l_j = 0; l_j < l_n; l_j++ ) {
for (l_i = 0; l_i < l_m; l_i++ ) {
l_elems = l_rowptr[l_i+1] - l_rowptr[l_i];
l_c_gold_betazero[(l_n*l_i) + l_j] = 0.0;
for (l_z = 0; l_z < l_elems; l_z++) {
l_c_gold_betazero[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j];
}
}
}
for ( l_j = 0; l_j < l_n; l_j++ ) {
for (l_i = 0; l_i < l_m; l_i++ ) {
l_elems = l_rowptr[l_i+1] - l_rowptr[l_i];
for (l_z = 0; l_z < l_elems; l_z++) {
l_c_gold_betaone[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j];
}
}
}
printf("...done!\n");
/* libxsmm generated code */
printf("computing libxsmm (A sparse) solution...\n");
#ifdef _OPENMP
#pragma omp parallel for private(l_z)
#endif
for (l_z = 0; l_z < l_n; l_z+=l_n_block) {
libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z );
}
#ifdef _OPENMP
#pragma omp parallel for private(l_z)
#endif
for (l_z = 0; l_z < l_n; l_z+=l_n_block) {
libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z );
}
printf("...done!\n");
/* BLAS code */
printf("computing BLAS (A dense) solution...\n");
beta = 0.0;
dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n );
beta = 1.0;
dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n );
printf("...done!\n");
/* check for errors */
l_max_error = (REALTYPE)0.0;
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
if (fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) {
l_max_error = fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]);
}
}
printf("max error beta=0 (libxmm vs. gold): %f\n", l_max_error);
l_max_error = (REALTYPE)0.0;
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
if (fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) {
l_max_error = fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]);
}
}
printf("max error beta=1 (libxmm vs. gold): %f\n", l_max_error);
l_max_error = (REALTYPE)0.0;
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
if (fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) {
l_max_error = fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]);
}
}
printf("max error beta=0 (dense vs. gold): %f\n", l_max_error);
l_max_error = (REALTYPE)0.0;
for ( l_i = 0; l_i < l_m*l_n; l_i++) {
if (fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) {
l_max_error = fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]);
}
}
printf("max error beta=1 (dense vs. gold): %f\n", l_max_error);
/* Let's measure performance */
gettimeofday(&l_start, NULL);
for ( l_j = 0; l_j < l_reps; l_j++ ) {
#ifdef _OPENMP
#pragma omp parallel for private(l_z)
#endif
for (l_z = 0; l_z < l_n; l_z+=l_n_block) {
libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z );
}
}
gettimeofday(&l_end, NULL);
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps );
fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total );
gettimeofday(&l_start, NULL);
for ( l_j = 0; l_j < l_reps; l_j++ ) {
#ifdef _OPENMP
#pragma omp parallel for private(l_z)
#endif
for (l_z = 0; l_z < l_n; l_z+=l_n_block) {
libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z );
}
}
gettimeofday(&l_end, NULL);
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps );
fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total );
gettimeofday(&l_start, NULL);
beta = 0.0;
for ( l_j = 0; l_j < l_reps; l_j++ ) {
dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n );
}
gettimeofday(&l_end, NULL);
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps );
fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total );
gettimeofday(&l_start, NULL);
beta = 1.0;
for ( l_j = 0; l_j < l_reps; l_j++ ) {
dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n );
}
gettimeofday(&l_end, NULL);
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps );
fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total );
/* free */
libxsmm_dfsspmdm_destroy( gemm_op_betazero );
libxsmm_dfsspmdm_destroy( gemm_op_betaone );
}
|
engine.h | #pragma once
#ifndef ENGINE_H
#define ENGINE_H
// Node API includes
#include <napi.h>
// STL includes
#include <memory>
#include <unordered_map>
#include <any>
// Eigen includes
#include <Eigen/Core>
// Optimization lib includes
#include <libs/optimization_lib/include/core/core.h>
#include <libs/optimization_lib/include/core/utils.h>
#include <libs/optimization_lib/include/data_providers/mesh_wrapper.h>
#include <libs/optimization_lib/include/data_providers/empty_data_provider.h>
#include <libs/optimization_lib/include/data_providers/plain_data_provider.h>
#include <libs/optimization_lib/include/data_providers/edge_pair_data_provider.h>
#include <libs/optimization_lib/include/objective_functions/summation_objective.h>
#include <libs/optimization_lib/include/objective_functions/position/face_position_objective.h>
#include <libs/optimization_lib/include/objective_functions/separation_objective.h>
#include <libs/optimization_lib/include/objective_functions/symmetric_dirichlet_objective.h>
#include <libs/optimization_lib/include/objective_functions/seamless_objective.h>
#include <libs/optimization_lib/include/objective_functions/singularity/singular_points_position_objective.h>
#include <libs/optimization_lib/include/iterative_methods/newton_method.h>
#include <libs/optimization_lib/include/solvers/eigen_sparse_solver.h>
#include <libs/optimization_lib/include/solvers/pardiso_solver.h>
class Engine : public Napi::ObjectWrap<Engine> {
public:
static Napi::Object Init(Napi::Env env, Napi::Object exports);
Engine(const Napi::CallbackInfo& info);
private:
/**
* Private type definitions
*/
enum class ModelFileType
{
OBJ,
OFF,
UNKNOWN
};
enum class BufferedPrimitiveType : uint32_t
{
VERTEX = 0,
EDGE,
TRIANGLE
};
enum class DataSource
{
DOMAIN_DATA,
IMAGE_DATA
};
enum class FacesSource
{
DOMAIN_FACES,
IMAGE_FACES
};
enum class EdgesSource
{
DOMAIN_EDGES,
IMAGE_EDGES
};
enum class VerticesSource
{
DOMAIN_VERTICES,
IMAGE_VERTICES
};
enum class AlgorithmType
{
AUTOCUTS,
AUTOQUADS
};
static Napi::FunctionReference constructor;
/**
* NAPI private instance setters
*/
void SetPositionWeight(const Napi::CallbackInfo& info, const Napi::Value& value);
void SetSeamlessWeight(const Napi::CallbackInfo& info, const Napi::Value& value);
void SetLambda(const Napi::CallbackInfo& info, const Napi::Value& value);
void SetDelta(const Napi::CallbackInfo& info, const Napi::Value& value);
/**
* NAPI private instance getters
*/
Napi::Value GetPositionWeight(const Napi::CallbackInfo& info);
Napi::Value GetSeamlessWeight(const Napi::CallbackInfo& info);
Napi::Value GetLambda(const Napi::CallbackInfo& info);
Napi::Value GetDelta(const Napi::CallbackInfo& info);
Napi::Value GetObjectiveFunctionsData(const Napi::CallbackInfo& info);
/**
* NAPI private instance methods
*/
Napi::Value GetDomainFacesCount(const Napi::CallbackInfo& info);
Napi::Value GetImageFacesCount(const Napi::CallbackInfo& info);
Napi::Value GetDomainEdgesCount(const Napi::CallbackInfo& info);
Napi::Value GetImageEdgesCount(const Napi::CallbackInfo& info);
Napi::Value GetDomainVerticesCount(const Napi::CallbackInfo& info);
Napi::Value GetImageVerticesCount(const Napi::CallbackInfo& info);
Napi::Value GetDomainFaces(const Napi::CallbackInfo& info);
Napi::Value GetImageFaces(const Napi::CallbackInfo& info);
Napi::Value GetDomainEdges(const Napi::CallbackInfo& info);
Napi::Value GetImageEdges(const Napi::CallbackInfo& info);
Napi::Value GetDomainVertices(const Napi::CallbackInfo& info);
Napi::Value GetImageVertices(const Napi::CallbackInfo& info);
Napi::Value GetDomainBufferedFaces(const Napi::CallbackInfo& info);
Napi::Value GetImageBufferedFaces(const Napi::CallbackInfo& info);
Napi::Value GetDomainBufferedEdges(const Napi::CallbackInfo& info);
Napi::Value GetImageBufferedEdges(const Napi::CallbackInfo& info);
Napi::Value GetDomainBufferedVertices(const Napi::CallbackInfo& info);
Napi::Value GetImageBufferedVertices(const Napi::CallbackInfo& info);
Napi::Value GetDomainBufferedUvs(const Napi::CallbackInfo& info);
Napi::Value GetImageBufferedUvs(const Napi::CallbackInfo& info);
Napi::Value Engine::GetDomainFaceEdgeAdjacency(const Napi::CallbackInfo& info);
Napi::Value Engine::GetDomainEdgeFaceAdjacency(const Napi::CallbackInfo& info);
Napi::Value Engine::GetImageFaceEdgeAdjacency(const Napi::CallbackInfo& info);
Napi::Value Engine::GetImageEdgeFaceAdjacency(const Napi::CallbackInfo& info);
Napi::Value GetObjectiveFunctionProperty(const Napi::CallbackInfo& info);
Napi::Value SetObjectiveFunctionProperty(const Napi::CallbackInfo& info);
Napi::Value LoadModel(const Napi::CallbackInfo& info);
Napi::Value ResumeSolver(const Napi::CallbackInfo& info);
Napi::Value PauseSolver(const Napi::CallbackInfo& info);
Napi::Value SetAlgorithmType(const Napi::CallbackInfo& info);
Napi::Value ConstrainFacePosition(const Napi::CallbackInfo& info);
Napi::Value UpdateConstrainedFacePosition(const Napi::CallbackInfo& info);
Napi::Value UnconstrainFacePosition(const Napi::CallbackInfo& info);
Napi::Value ReconstrainFacePosition(const Napi::CallbackInfo& info);
/**
* Regular private instance methods
*/
ModelFileType GetModelFileType(std::string filename);
void TryUpdateImageVertices();
Napi::Int32Array GetBufferedFaces(const Napi::CallbackInfo& info, const FacesSource faces_source) const;
Napi::Int32Array GetBufferedEdges(const Napi::CallbackInfo& info, const EdgesSource edges_source) const;
Napi::Float32Array GetBufferedVertices(const Napi::CallbackInfo& info, const VerticesSource vertices_source);
Napi::Int32Array CreateBufferedFacesArray(Napi::Env env, const Eigen::MatrixXi& F) const;
Napi::Int32Array CreateBufferedEdgesArray(Napi::Env env, const Eigen::MatrixXi& E) const;
Napi::Array CreateFaces(Napi::Env env, const Eigen::MatrixX3i& F);
Napi::Array CreateEdges(Napi::Env env, const Eigen::MatrixX2i& E);
Napi::Value NativeToJS(Napi::Env env, const std::any& property_value);
Napi::Value NativeToJS(Napi::Env env, const Eigen::VectorXd& property_value);
Napi::Value NativeToJS(Napi::Env env, const std::vector<RDS::VertexIndex>& property_value);
Napi::Value NativeToJS(Napi::Env env, const double property_value);
Napi::Value NativeToJS(Napi::Env env, const std::string& property_value);
std::any JSToNative(Napi::Env env, const Napi::Value& value);
Napi::Value Engine::GetFaceEdgeAdjacency(const Napi::CallbackInfo& info, const DataSource data_source);
Napi::Value Engine::GetEdgeFaceAdjacency(const Napi::CallbackInfo& info, const DataSource data_source);
AlgorithmType StringToAlgorithmType(const std::string& algorithm_type_string);
Napi::Value CreateObjectiveFunctionDataObject(Napi::Env env, std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>> objective_function) const;
std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>> GetObjectiveFunctionByName(const std::string& name);
/**
* Regular private templated instance methods
*/
template <typename Derived>
Napi::Array CreateVerticesArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V)
{
Napi::Array vertices_array = Napi::Array::New(env, V.rows());
auto entries_per_vertex = V.cols();
for (int32_t vertex_index = 0; vertex_index < V.rows(); vertex_index++)
{
Napi::Object vertex_object = Napi::Object::New(env);
float x = V(vertex_index, 0);
float y = V(vertex_index, 1);
vertex_object.Set("x", x);
vertex_object.Set("y", y);
if (entries_per_vertex == 3)
{
float z = V(vertex_index, 2);
vertex_object.Set("z", z);
}
vertices_array[vertex_index] = vertex_object;
}
return vertices_array;
}
template <typename Derived>
Napi::Float32Array CreateBufferedVerticesArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V, const Eigen::MatrixX3i& F)
{
const uint32_t entries_per_face = 9;
const uint32_t entries_per_vertex = V.cols();
Napi::Float32Array buffered_vertices_array = Napi::Float32Array::New(env, entries_per_face * F.rows());
//#pragma omp parallel for
for (int32_t face_index = 0; face_index < F.rows(); face_index++)
{
const int base_index = entries_per_face * face_index;
for (uint32_t i = 0; i < 3; i++)
{
uint32_t vertex_index = F(face_index, i);
const float x = V(vertex_index, 0);
const float y = V(vertex_index, 1);
const float z = entries_per_vertex == 2 ? 0 : V(vertex_index, 2);
const int base_vertex_index = base_index + 3 * i;
buffered_vertices_array[base_vertex_index] = x;
buffered_vertices_array[base_vertex_index + 1] = y;
buffered_vertices_array[base_vertex_index + 2] = z;
}
}
return buffered_vertices_array;
}
template <typename Derived>
Napi::Float32Array CreateBufferedVerticesArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V, const Eigen::MatrixX2i& E)
{
const uint32_t entries_per_edge = 6;
const uint32_t entries_per_vertex = V.cols();
Napi::Float32Array buffered_vertices_array = Napi::Float32Array::New(env, entries_per_edge * E.rows());
//#pragma omp parallel for
for (int32_t edge_index = 0; edge_index < E.rows(); edge_index++)
{
const int base_index = entries_per_edge * edge_index;
for (uint32_t i = 0; i < 2; i++)
{
uint32_t vertex_index = E(edge_index, i);
const float x = V(vertex_index, 0);
const float y = V(vertex_index, 1);
const float z = entries_per_vertex == 2 ? 0 : V(vertex_index, 2);
const int base_vertex_index = base_index + 3 * i;
buffered_vertices_array[base_vertex_index] = x;
buffered_vertices_array[base_vertex_index + 1] = y;
buffered_vertices_array[base_vertex_index + 2] = z;
}
}
return buffered_vertices_array;
}
template <typename Derived>
Napi::Float32Array CreateBufferedVerticesArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V)
{
Napi::Float32Array buffered_vertices_array = Napi::Float32Array::New(env, 3 * V.rows());
const uint32_t entries_per_vertex = V.cols();
//#pragma omp parallel for
for (int32_t vertex_index = 0; vertex_index < V.rows(); vertex_index++)
{
const float x = V(vertex_index, 0);
const float y = V(vertex_index, 1);
const float z = entries_per_vertex == 2 ? 0 : V(vertex_index, 2);
const int base_index = 3 * vertex_index;
buffered_vertices_array[base_index] = x;
buffered_vertices_array[base_index + 1] = y;
buffered_vertices_array[base_index + 2] = z;
}
return buffered_vertices_array;
}
template <typename Derived>
Napi::Float32Array CreateBufferedUvsArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V, const Eigen::MatrixXi& F)
{
const uint32_t entries_per_face = 6;
uint32_t entries_per_vertex = V.cols();
Napi::Float32Array buffered_uvs_array = Napi::Float32Array::New(env, entries_per_face * F.rows());
//#pragma omp parallel for
for (int32_t face_index = 0; face_index < F.rows(); face_index++)
{
const int base_index = entries_per_face * face_index;
for (uint32_t i = 0; i < 3; i++)
{
uint32_t vertex_index = F(face_index, i);
float x = V(vertex_index, 0);
float y = V(vertex_index, 1);
const int base_vertex_index = base_index + 2 * i;
buffered_uvs_array[base_vertex_index] = x;
buffered_uvs_array[base_vertex_index + 1] = y;
}
}
return buffered_uvs_array;
}
/**
* Fields
*/
std::unordered_map<RDS::Face, std::shared_ptr<FacePositionObjective<Eigen::StorageOptions::RowMajor>>, RDS::VectorHash, RDS::VectorEquals> face_to_position_objective_map_;
std::unordered_map<RDS::Face, std::shared_ptr<FaceDataProvider>, RDS::VectorHash, RDS::VectorEquals> face_to_face_data_provider_map_;
std::shared_ptr<MeshWrapper> mesh_wrapper_;
std::shared_ptr<PlainDataProvider> plain_data_provider_;
std::shared_ptr<EmptyDataProvider> empty_data_provider_;
std::vector<std::shared_ptr<EdgePairDataProvider>> edge_pair_data_providers_;
std::vector<std::shared_ptr<FaceFanDataProvider>> face_fan_data_providers_;
std::vector<std::shared_ptr<FaceDataProvider>> face_data_providers_;
std::vector<std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>>> summation_objectives_;
std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>> summation_objective_;
std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>> autoquads_summation_objective_;
std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>> autocuts_summation_objective_;
std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>> position_;
std::shared_ptr<Separation<Eigen::StorageOptions::RowMajor>> separation_;
std::shared_ptr<SymmetricDirichlet<Eigen::StorageOptions::RowMajor>> symmetric_dirichlet_;
std::shared_ptr<SeamlessObjective<Eigen::StorageOptions::RowMajor>> seamless_;
std::shared_ptr<SingularPointsPositionObjective<Eigen::StorageOptions::RowMajor>> singular_points_;
std::vector<std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>>> objective_functions_;
std::vector<std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>>> autocuts_objective_functions_;
std::vector<std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>>> autoquads_objective_functions_;
std::unique_ptr<NewtonMethod<PardisoSolver, Eigen::StorageOptions::RowMajor>> newton_method_;
std::vector<Eigen::DenseIndex> constrained_faces_indices;
Eigen::MatrixX2d image_vertices_;
std::unordered_map<std::string, uint32_t> properties_map_;
std::unordered_map<std::string, uint32_t> property_modifiers_map_;
};
#endif |
LILCSR.h | //*****************************************************************************
//Title :PANSFEM2/LinearAlgebra/Models/LILCSR.h
//Author :Tanabe Yuta
//Date :2019/11/29
//Copyright :(C)2019 TanabeYuta
//*****************************************************************************
#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
#include "CSR.h"
template<class T>
class CSR;
template<class T>
class LILCSR
{
public:
LILCSR();
~LILCSR();
LILCSR(int _rows, int _cols);
LILCSR(CSR<T> _matrix); //Genarate LILCSR matrix from CSR matrix
const int ROWS; //Row number
const int COLS; //Column number
template<class T1, class T2>
friend const std::vector<T1> operator*(const LILCSR<T1>& _m, const std::vector<T2> &_vec); //Operator : Multiple with vector
template<class T1, class T2>
friend const LILCSR<T1> operator+(const LILCSR<T1>& _m1, const LILCSR<T2>& _m2); //Operator : Add with LILCSR matrix
template<class T1, class T2>
friend const LILCSR<T1> operator-(const LILCSR<T1>& _m1, const LILCSR<T2>& _m2); //Operator : Subtruct with LILCSR matrix
template<class T1, class T2>
friend const LILCSR<T2> operator*(T1 _a, const LILCSR<T2>& _m); //Operator : Multiple with real number
template<class T1, class T2>
friend const LILCSR<T1> operator*(const LILCSR<T1>& _m, T2 _a); //Operator : Multiple with real number
template<class T1, class T2>
friend const LILCSR<T1> operator/(const LILCSR<T1>& _m, T2 _a); //Operator :
template<class F>
friend std::ostream& operator << (std::ostream &_out, const LILCSR<F> &_mat); //Operator : to stream
bool set(int _row, int _col, T _data); //Set value
T get(int _row, int _col) const; //Get value
template<class F>
friend class CSR;
private:
std::vector<std::vector<std::pair<int, T> > > data;
};
template<class T>
inline LILCSR<T>::LILCSR() : ROWS(0), COLS(0) {}
template<class T>
inline LILCSR<T>::~LILCSR() {}
template<class T>
inline LILCSR<T>::LILCSR(int _rows, int _cols) : ROWS(_rows), COLS(_cols) {
this->data = std::vector<std::vector<std::pair<int, T> > >(_rows);
}
template<class T>
inline LILCSR<T>::LILCSR(CSR<T> _matrix) : ROWS(_matrix.ROWS), COLS(_matrix.COLS) {
this->data = std::vector<std::vector<std::pair<int, T> > >(_matrix.ROWS);
for (int i = 0; i < _matrix.ROWS; i++) {
for (int k = _matrix.indptr[i]; k < _matrix.indptr[i + 1]; k++) {
this->data[i].push_back(std::pair<int, T>(_matrix.indices[k], _matrix.data[k]));
}
}
}
template<class T>
inline bool LILCSR<T>::set(int _row, int _col, T _data) {
for (auto& dataj : this->data[_row]) {
if (dataj.first == _col) {
dataj.second = _data;
return true;
}
}
this->data[_row].push_back(std::pair<int, T>(_col, _data));
return false;
}
template<class T>
inline T LILCSR<T>::get(int _row, int _col) const {
for (const auto& dataj : this->data[_row]) {
if (dataj.first == _col) {
return dataj.second;
}
}
return T();
}
template<class T1, class T2>
inline const std::vector<T1> operator*(const LILCSR<T1>& _m, const std::vector<T2>& _vec) {
assert(_m.COLS == _vec.size());
std::vector<T1> v(_m.ROWS, T1());
//#pragma omp parallel for
for (int i = 0; i < _m.ROWS; i++) {
for (auto dataj : _m.data[i]) {
v[i] += dataj.second * _vec[dataj.first];
}
}
return v;
}
template<class T1, class T2>
inline const LILCSR<T1> operator+(const LILCSR<T1>& _m1, const LILCSR<T2>& _m2) {
assert(_m1.ROWS == _m2.ROWS && _m1.COLS == _m2.COLS);
LILCSR<T1> m = LILCSR<T1>(_m1);
for (int i = 0; i < _m2.ROWS; i++) {
for (auto dataij : _m2.data[i]) {
int j = dataij.first;
m.set(i, j, m.get(i, j) + dataij.second);
}
}
return m;
}
template<class T1, class T2>
inline const LILCSR<T1> operator-(const LILCSR<T1>& _m1, const LILCSR<T2>& _m2) {
assert(_m1.ROWS == _m2.ROWS && _m1.COLS == _m2.COLS);
LILCSR<T1> m = LILCSR<T1>(_m1);
for (int i = 0; i < _m2.ROWS; i++) {
for (auto dataij : _m2.data[i]) {
int j = dataij.first;
m.set(i, j, m.get(i, j) - dataij.second);
}
}
return m;
}
template<class T1, class T2>
inline const LILCSR<T2> operator*(T1 _a, const LILCSR<T2>& _m) {
LILCSR<T2> m = LILCSR<T2>(_m);
for (auto& row : m.data) {
for (auto& col : row) {
col.second *= _a;
}
}
return m;
}
template<class T1, class T2>
inline const LILCSR<T1> operator*(const LILCSR<T1>& _m, T2 _a) {
LILCSR<T1> m = LILCSR<T1>(_m);
for (auto& row : m.data) {
for (auto& col : row) {
col.second *= _a;
}
}
return m;
}
template<class T1, class T2>
inline const LILCSR<T1> operator/(const LILCSR<T1>& _m, T2 _a) {
LILCSR<T1> m = LILCSR<T1>(_m);
for (auto& row : m.data) {
for (auto& col : row) {
col.second /= _a;
}
}
return m;
}
template<class F>
inline std::ostream & operator<<(std::ostream & _out, const LILCSR<F>& _mat) {
for (int i = 0; i < _mat.ROWS; i++) {
for (int j = 0; j < _mat.COLS; j++) {
_out << _mat.get(i, j) << "\t";
}
_out << std::endl;
}
return _out;
} |
deflation_utils.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Riccardo Rossi
//
//
#if !defined(KRATOS_DEFLATION_UTILS )
#define KRATOS_DEFLATION_UTILS
/* System includes */
#include "includes/define.h"
#include "includes/model_part.h"
#include "includes/global_pointer_variables.h"
#ifdef KRATOS_USE_AMATRIX // This macro definition is for the migration period and to be removed afterward please do not use it
#include "boost/numeric/ublas/matrix.hpp" // for the vector used here.
#else
#endif // KRATOS_USE_AMATRIX
/* External includes */
/* Project includes */
namespace Kratos
{
/**@name Kratos Globals */
/*@{ */
/*@} */
/**@name Type Definitions */
/*@{ */
/*@} */
/**@name Enum's */
/*@{ */
/*@} */
/**@name Functions */
/*@{ */
/*@} */
/**@name Kratos Classes */
/*@{ */
/** This class defines utility for aggregation of node clusters to be used in deflated solvers.
Detail class definition.
\URL[Example of use html]{ extended_documentation/no_ex_of_use.html}
\URL[Example of use pdf]{ extended_documentation/no_ex_of_use.pdf}
\URL[Example of use doc]{ extended_documentation/no_ex_of_use.doc}
\URL[Example of use ps]{ extended_documentation/no_ex_of_use.ps}
\URL[Extended documentation html]{ extended_documentation/no_ext_doc.html}
\URL[Extended documentation pdf]{ extended_documentation/no_ext_doc.pdf}
\URL[Extended documentation doc]{ extended_documentation/no_ext_doc.doc}
\URL[Extended documentation ps]{ extended_documentation/no_ext_doc.ps}
*/
class DeflationUtils
{
public:
/**@name Type Definitions */
/*@{ */
typedef boost::numeric::ublas::compressed_matrix<double> SparseMatrixType;
typedef boost::numeric::ublas::vector<double> SparseVectorType;
/*@} */
/**@name Life Cycle
*/
/*@{ */
/** Constructor.
*/
/** Destructor.
*/
/*@} */
/**@name Operators
*/
/*@{ */
///visualize aggregates. This function assumes that neighbours are calculated and builds the connectivity matrix
///then writes it to a nodal variable so that it can be used for visualizing it.
void VisualizeAggregates(ModelPart::NodesContainerType& rNodes, Variable<double>& rVariable, const int max_reduced_size)
{
SparseMatrixType A(rNodes.size(),rNodes.size());
SparseMatrixType Adeflated;
//first of all build the connectivty matrix
std::vector< std::vector<int> > index_list(rNodes.size());
std::size_t total_size = 0;
//renumber nodes consecutively
int new_id = 1;
for(ModelPart::NodesContainerType::iterator in = rNodes.begin(); in!=rNodes.end(); in++)
in->SetId(new_id++);
//constructing the system matrix row by row
std::size_t index_i;
for(ModelPart::NodesContainerType::iterator in = rNodes.begin();
in!=rNodes.end(); in++)
{
index_i = (in)->Id()-1;
auto& neighb_nodes = in->GetValue(NEIGHBOUR_NODES);
std::vector<int>& indices = index_list[index_i];
indices.reserve(neighb_nodes.size()+1);
//filling the first neighbours list
indices.push_back(index_i);
for( auto i = neighb_nodes.begin();
i != neighb_nodes.end(); i++)
{
int index_j = i->Id()-1;
indices.push_back(index_j);
}
//sorting the indices and elminating the duplicates
std::sort(indices.begin(),indices.end());
std::vector<int>::iterator new_end = std::unique(indices.begin(),indices.end());
indices.erase(new_end,indices.end());
total_size += indices.size();
}
A.reserve(total_size,false);
//setting to zero the matrix (and the diagonal matrix)
for(unsigned int i=0; i<A.size1(); i++)
{
std::vector<int>& indices = index_list[i];
for(unsigned int j=0; j<indices.size(); j++)
{
A.push_back(i,indices[j] , 0.00);
}
}
// std::cout << "matrix constructed" << std::endl;
//now call aggregation function to color the nodes
std::vector<int> w(rNodes.size());
ConstructW(max_reduced_size, A, w, Adeflated);
// std::cout << "aggregates constructed" << std::endl;
//finally write the color to the nodes so that it can be visualized
int counter = 0;
for(ModelPart::NodesContainerType::iterator in=rNodes.begin(); in!=rNodes.end(); in++)
{
in->FastGetSolutionStepValue(rVariable) = w[counter++];
}
// std::cout << "finished" << std::endl;
}
///this function constructs the structure of a smaller matrix using a technique taken from MIS aggregation
///the algorythm is taken from the pyamg lib
static void ConstructW(const std::size_t max_reduced_size, SparseMatrixType& rA, std::vector<int>& w, SparseMatrixType& deflatedA)
{
KRATOS_TRY
std::size_t full_size = rA.size1();
w.resize(full_size,0);
//call aggregation function to fill mw with "colors"
std::size_t reduced_size = standard_aggregation<int>(rA.size1(),rA.index1_data().begin(), rA.index2_data().begin(), &w[0]);
// for( int i=0; i<full_size; i++)
// std::cout << w[i] << std::endl;
// Non-zero structure of deflatedA
std::vector<std::set<std::size_t> > deflatedANZ(reduced_size);
// Loop over non-zero structure of A and build non-zero structure of deflatedA
SparseMatrixType::iterator1 a_iterator = rA.begin1();
for (std::size_t i = 0; i < full_size; i++)
{
#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION
for (SparseMatrixType::iterator2 row_iterator = a_iterator.begin() ;
row_iterator != a_iterator.end() ; ++row_iterator)
{
#else
for (typename SparseMatrixType::iterator2 row_iterator = begin(a_iterator,
boost::numeric::ublas::iterator1_tag());
row_iterator != end(a_iterator,
boost::numeric::ublas::iterator1_tag()); ++row_iterator )
{
#endif
deflatedANZ[w[a_iterator.index1()]].insert(w[row_iterator.index2()]);
}
a_iterator++;
}
// std::cout << "********** NZS built!" << std::endl;
// Count the number of non-zeros in deflatedA
std::size_t NZ = 0;
for (std::size_t i = 0; i < reduced_size; i++)
NZ += deflatedANZ[i].size();
// std::cout << "********** NZ = " << NZ << std::endl;
// KRATOS_WATCH(reduced_size);
deflatedA = SparseMatrixType(reduced_size, reduced_size,NZ);
// Insert the non-zero structure into deflatedA
for(std::size_t i = 0 ; i < reduced_size ; i++)
{
for(std::set<std::size_t>::iterator j = deflatedANZ[i].begin() ; j != deflatedANZ[i].end() ; j++)
{
deflatedA.push_back(i,*j, 0.00);
}
}
// KRATOS_WATCH(__LINE__)
if(reduced_size > max_reduced_size)
{
SparseMatrixType Areduced;
std::vector<int> wsmaller;
// KRATOS_WATCH(__LINE__)
//need to reduce further!! - do it recursively
ConstructW(max_reduced_size, deflatedA, wsmaller, Areduced);
// KRATOS_WATCH(__LINE__)
//now change deflatedA and w on the coarser size
for(unsigned int i=0; i<full_size; i++)
{
int color = w[i];
int new_color = wsmaller[color];
w[i] = new_color;
}
deflatedA.clear();
deflatedA = Areduced;
// KRATOS_WATCH(__LINE__)
reduced_size = wsmaller.size();
}
// KRATOS_WATCH(reduced_size);
// std::cout << "reduction factor ="<<double(full_size)/double(reduced_size)<<std::endl;
KRATOS_CATCH("")
}
///block version of ConstructW. To be used when multiple DOFS are associated to the same node.
static void ConstructW(const int max_reduced_size, SparseMatrixType& rA, std::vector<int>& w, SparseMatrixType& deflatedA, const std::size_t block_size)
{
if(block_size == 1)
{
ConstructW(max_reduced_size,rA, w, deflatedA);
}
else
{
//simple checks to verify blocks are effectively respected
if(rA.size1()%block_size != 0 || rA.size2()%block_size != 0)
KRATOS_THROW_ERROR(std::logic_error,"the number of rows is not a multiple of block_size. Can not use the block deflation","")
if(rA.nnz()%block_size != 0)
KRATOS_THROW_ERROR(std::logic_error,"the number of non zeros is not a multiple of block_size. Can not use the block deflation","")
//construct Ascalar
SparseMatrixType Ascalar;
ConstructScalarMatrix(rA.size1(),block_size,rA.index1_data().begin(), rA.index2_data().begin(), Ascalar);
//deflate it using the standard methods
SparseMatrixType deflatedAscalar;
std::vector<int> wscalar;
ConstructW(max_reduced_size/block_size,Ascalar, wscalar, deflatedAscalar);
//compute w for the block structured problem
std::vector<int> w(wscalar.size()*block_size);
for(std::size_t i=0; i<wscalar.size(); i++)
{
for(std::size_t j=0; j<block_size; j++)
{
w[i*block_size + j] = wscalar[i]*block_size+j;
}
}
//compute deflatedA
SparseMatrixType deflatedA(deflatedAscalar.size1()*block_size,deflatedAscalar.size2()*block_size);
//do reserve!!
deflatedA.reserve(deflatedAscalar.nnz()*block_size*block_size);
ExpandScalarMatrix(rA.size1(),block_size,rA.index1_data().begin(), rA.index2_data().begin(), deflatedA);
}
}
//W is the deflation matrix, stored as a single vector of indices
//y is a vector of "full" size
//x is a vector of reduced size
//y = W*x;
static void ApplyW(const std::vector<int>& w, const SparseVectorType& x, SparseVectorType& y)
{
#pragma omp parallel for
for(int i=0; i<static_cast<int>(w.size()); i++)
{
y[i] = x[w[i]];
}
}
//W is the deflation matrix, stored as a single vector of indices
//y is a vector of "reduced" size
//s is a vector of "full" size
//y = Wtranspose*x;
static void ApplyWtranspose(const std::vector<int>& w, const SparseVectorType& x, SparseVectorType& y)
{
//first set to zero the destination vector
#pragma omp parallel for
for(int i=0; i<static_cast<int>(y.size()); i++)
y[i] = 0.0;
//Pragma atomic does not work with MSVC 19.0.23506 ( aka Visual Studio 2015 Update1 )
#if(_MSC_FULL_VER == 190023506)
for(int i=0; i<static_cast<int>(w.size()); i++)
{
y[w[i]] += x[i];
}
#else
//now apply the Wtranspose
#pragma omp parallel for
for(int i=0; i<static_cast<int>(w.size()); i++)
{
#pragma omp atomic
y[w[i]] += x[i];
}
#endif
}
//*******************************************************************************
//*******************************************************************************
static void FillDeflatedMatrix( const SparseMatrixType& rA, std::vector<int>& w, SparseMatrixType& Ah)
{
KRATOS_TRY
double* abegin = Ah.value_data().begin();
int size = Ah.value_data().size();
#pragma omp parallel for
for (int i = 0; i < size; i++)
{
*(abegin+i) = 0.0;
}
// TSparseSpaceType::SetToZero(Ah);
// Now building Ah
SparseMatrixType::const_iterator1 a_iterator = rA.begin1();
int full_size = rA.size1();
for (int i = 0; i < full_size; i++)
{
#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION
for (SparseMatrixType::const_iterator2 row_iterator = a_iterator.begin() ;
row_iterator != a_iterator.end() ; ++row_iterator)
{
#else
for (typename SparseMatrixType::iterator2 row_iterator = begin(a_iterator,
boost::numeric::ublas::iterator1_tag());
row_iterator != end(a_iterator,
boost::numeric::ublas::iterator1_tag()); ++row_iterator )
{
#endif
Ah(w[a_iterator.index1()], w[row_iterator.index2()]) += *row_iterator;
}
a_iterator++;
}
// std::cout << "********** W^T * A * W built!" << std::endl;
KRATOS_CATCH("");
}
/*@} */
/**@name Operations */
/*@{ */
/*@} */
/**@name Acces */
/*@{ */
/*@} */
/**@name Inquiry */
/*@{ */
/*@} */
/**@name Friends */
/*@{ */
/*@} */
private:
/**@name Static Member Variables */
/*@{ */
/*@} */
/**@name Member Variables */
/*@{ */
/*@} */
/**@name Private Operators*/
/*@{ */
/*
* Compute aggregates for a matrix A stored in CSR format
*
* Parameters:
* n_row - number of rows in A
* Ap[n_row + 1] - CSR row pointer
* Aj[nnz] - CSR column indices
* x[n_row] - aggregate numbers for each node
*
* Returns:
* The number of aggregates (== max(x[:]) + 1 )
*
* Notes:
* It is assumed that A is structurally symmetric.
* A may contain diagonal entries (self loops)
* Unaggregated nodes are marked with a -1
*
*/
template <class I>
static I standard_aggregation(const I n_row,
const std::size_t Ap[],
const std::size_t Aj[],
I x[])
{
// Bj[n] == -1 means i-th node has not been aggregated
std::fill(x, x + n_row, 0);
I next_aggregate = 1; // number of aggregates + 1
//Pass #1
for(I i = 0; i < n_row; i++)
{
if(x[i])
{
continue; //already marked
}
const I row_start = Ap[i];
const I row_end = Ap[i+1];
//Determine whether all neighbors of this node are free (not already aggregates)
bool has_aggregated_neighbors = false;
bool has_neighbors = false;
for(I jj = row_start; jj < row_end; jj++)
{
const I j = Aj[jj];
if( i != j )
{
has_neighbors = true;
if( x[j] )
{
has_aggregated_neighbors = true;
break;
}
}
}
if(!has_neighbors)
{
//isolated node, do not aggregate
x[i] = -n_row;
}
else if (!has_aggregated_neighbors)
{
//Make an aggregate out of this node and its neighbors
x[i] = next_aggregate;
for(I jj = row_start; jj < row_end; jj++)
{
x[Aj[jj]] = next_aggregate;
}
next_aggregate++;
}
}
//Pass #2
// Add unaggregated nodes to any neighboring aggregate
for(I i = 0; i < n_row; i++)
{
if(x[i])
{
continue; //already marked
}
for(I jj = static_cast<I>(Ap[i]); jj < static_cast<I>(Ap[i+1]); jj++)
{
const I j = Aj[jj];
const I xj = x[j];
if(xj > 0)
{
x[i] = -xj;
break;
}
}
}
next_aggregate--;
//Pass #3
for(I i = 0; i < n_row; i++)
{
const I xi = x[i];
if(xi != 0)
{
// node i has been aggregated
if(xi > 0)
x[i] = xi - 1;
else if(xi == -n_row)
x[i] = -1;
else
x[i] = -xi - 1;
continue;
}
// node i has not been aggregated
const I row_start = Ap[i];
const I row_end = Ap[i+1];
x[i] = next_aggregate;
for(I jj = row_start; jj < row_end; jj++)
{
const I j = Aj[jj];
if(x[j] == 0) //unmarked neighbors
{
x[j] = next_aggregate;
}
}
next_aggregate++;
}
return next_aggregate; //number of aggregates
}
static void ConstructScalarMatrix(const std::size_t n_row, const std::size_t block_size,
const std::size_t Ap[],
const std::size_t Aj[],
SparseMatrixType& Ascalar
)
{
Ascalar.resize(n_row/block_size,n_row/block_size,0.0);
std::size_t scalar_size = (Ap[n_row]-Ap[0])/(block_size*block_size);
Ascalar.reserve(scalar_size);
for(std::size_t i = 0; i < n_row; i++)
{
if(i%block_size == 0)
{
std::size_t iscalar = i/block_size;
const std::size_t row_start = Ap[i];
const std::size_t row_end = Ap[i+1];
for(std::size_t jj = row_start; jj < row_end; jj++)
{
const std::size_t j = Aj[jj];
if(j%block_size == 0)
{
std::size_t jscalar = j/block_size;
Ascalar.push_back(iscalar,jscalar,0.0);
}
}
}
}
}
static void ExpandScalarMatrix(const std::size_t n_row, const std::size_t block_size,
const std::size_t Ap[],
const std::size_t Aj[],
SparseMatrixType& Aexpanded
)
{
Aexpanded.resize(n_row*block_size,n_row*block_size,0.0);
std::size_t expanded_size = (Ap[n_row]-Ap[0])*block_size*block_size;
Aexpanded.reserve(expanded_size);
for(std::size_t i = 0; i < n_row; i++)
{
const std::size_t row_start = Ap[i];
const std::size_t row_end = Ap[i+1];
for(std::size_t isub=0; isub<block_size; isub++)
{
std::size_t iexpanded = i*block_size + isub;
for(std::size_t jj = row_start; jj < row_end; jj++)
{
const std::size_t j = Aj[jj];
for(std::size_t jsub=0; jsub<block_size; jsub++)
{
std::size_t jexpanded = j*block_size+jsub;
Aexpanded.push_back(iexpanded,jexpanded,0.0);
}
}
}
}
}
/*@} */
/**@name Private Operations*/
/*@{ */
/*@} */
/**@name Private Acces */
/*@{ */
/*@} */
/**@name Private Inquiry */
/*@{ */
/*@} */
/**@name Un accessible methods */
/*@{ */
/*@} */
}; /* Class ClassName */
/*@} */
/**@name Type Definitions */
/*@{ */
/*@} */
} /* namespace Kratos.*/
#endif /* DEFLATION_UTILS defined */
|
GB_transpose_bucket.c | //------------------------------------------------------------------------------
// GB_transpose_bucket: transpose and optionally typecast and/or apply operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// C = A' or op(A'). Optionally typecasts from A->type to the new type ctype,
// and/or optionally applies a unary operator.
// If an operator z=op(x) is provided, the type of z must be the same as the
// type of C. The type of A must be compatible with the type of of x (A is
// typecasted into the type of x). These conditions must be checked in the
// caller.
// This function is agnostic for the CSR/CSC format of C and A. C_is_csc is
// defined by the caller and assigned to C->is_csc, but otherwise unused.
// A->is_csc is ignored.
// The input can be hypersparse or non-hypersparse. The output C is always
// non-hypersparse, and never shallow. On input, C is a static header.
// If A is m-by-n in CSC format, with e nonzeros, the time and memory taken is
// O(m+n+e) if A is non-hypersparse, or O(m+e) if hypersparse. This is fine if
// most rows and columns of A are non-empty, but can be very costly if A or A'
// is hypersparse. In particular, if A is a non-hypersparse column vector with
// m >> e, the time and memory is O(m), which can be huge. Thus, for
// hypersparse matrices, or for very sparse matrices, the qsort method should
// be used instead (see GB_transpose).
// This method is parallel, but not highly scalable. At most O(e/m) threads
// are used.
#include "GB_transpose.h"
#define GB_FREE_WORK \
{ \
if (Workspaces != NULL && Workspaces_size != NULL) \
{ \
for (int tid = 0 ; tid < nworkspaces ; tid++) \
{ \
GB_FREE_WERK (&(Workspaces [tid]), Workspaces_size [tid]) ; \
} \
} \
GB_WERK_POP (A_slice, int64_t) ; \
GB_WERK_POP (Workspaces_size, size_t) ; \
GB_WERK_POP (Workspaces, int64_t *) ; \
}
#define GB_FREE_ALL \
{ \
GB_phbix_free (C) ; \
GB_FREE_WORK ; \
}
GrB_Info GB_transpose_bucket // bucket transpose; typecast and apply op
(
GrB_Matrix C, // output matrix (static header)
const GB_iso_code C_code_iso, // iso code for C
const GrB_Type ctype, // type of output matrix C
const bool C_is_csc, // format of output matrix C
const GrB_Matrix A, // input matrix
// no operator is applied if both op1 and op2 are NULL
const GrB_UnaryOp op1, // unary operator to apply
const GrB_BinaryOp op2, // binary operator to apply
const GxB_Scalar scalar, // scalar to bind to binary operator
bool binop_bind1st, // if true, binop(x,A) else binop(A,y)
const int nworkspaces, // # of workspaces to use (1, or nthreads)
const int nthreads, // # of threads to use
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (C != NULL) ;
ASSERT (C->static_header) ;
ASSERT_TYPE_OK (ctype, "ctype for transpose", GB0) ;
ASSERT_MATRIX_OK (A, "A input for transpose_bucket", GB0) ;
ASSERT (!GB_PENDING (A)) ;
ASSERT (!GB_ZOMBIES (A)) ;
ASSERT (GB_JUMBLED_OK (A)) ;
// if op1 and op2 are NULL, then no operator is applied
// This method is only be used when A is sparse or hypersparse.
// The full and bitmap cases are handled in GB_transpose.
ASSERT (!GB_IS_FULL (A)) ;
ASSERT (!GB_IS_BITMAP (A)) ;
ASSERT (GB_IS_SPARSE (A) || GB_IS_HYPERSPARSE (A)) ;
GB_WERK_DECLARE (A_slice, int64_t) ; // size nthreads+1
GB_WERK_DECLARE (Workspaces, int64_t *) ; // size nworkspaces
GB_WERK_DECLARE (Workspaces_size, size_t) ; // size nworkspaces
//--------------------------------------------------------------------------
// get A
//--------------------------------------------------------------------------
int64_t anz = GB_nnz (A) ;
int64_t vlen = A->vlen ;
//--------------------------------------------------------------------------
// determine the number of threads to use
//--------------------------------------------------------------------------
// # of threads to use in the O(vlen) loops below
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nth = GB_nthreads (vlen, chunk, nthreads_max) ;
//--------------------------------------------------------------------------
// allocate C: always sparse
//--------------------------------------------------------------------------
// The bucket transpose only works when C is sparse.
// A can be sparse or hypersparse.
// C->p is allocated but not initialized.
GrB_Info info ;
// set C->iso = C_iso OK
bool C_iso = (C_code_iso != GB_NON_ISO) ;
GB_OK (GB_new_bix (&C, true, // sparse, static header
ctype, A->vdim, vlen, GB_Ap_malloc, C_is_csc,
GxB_SPARSE, true, A->hyper_switch, vlen, anz, true, C_iso, Context)) ;
int64_t *restrict Cp = C->p ;
//--------------------------------------------------------------------------
// allocate workspace
//--------------------------------------------------------------------------
GB_WERK_PUSH (Workspaces, nworkspaces, int64_t *) ;
GB_WERK_PUSH (Workspaces_size, nworkspaces, size_t) ;
if (Workspaces == NULL || Workspaces_size == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
bool ok = true ;
for (int tid = 0 ; tid < nworkspaces ; tid++)
{
Workspaces [tid] = GB_MALLOC_WERK (vlen + 1, int64_t,
&Workspaces_size [tid]) ;
ok = ok && (Workspaces [tid] != NULL) ;
}
if (!ok)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
//==========================================================================
// phase1: symbolic analysis
//==========================================================================
// slice the A matrix, perfectly balanced for one task per thread
GB_WERK_PUSH (A_slice, nthreads + 1, int64_t) ;
if (A_slice == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
GB_pslice (A_slice, A->p, A->nvec, nthreads, true) ;
// sum up the row counts and find C->p
if (nthreads == 1)
{
//----------------------------------------------------------------------
// sequential method: A is not sliced
//----------------------------------------------------------------------
// Only requires a single int64 workspace of size vlen for a single
// thread. The resulting C matrix is not jumbled.
// compute the row counts of A. No need to scan the A->p pointers
ASSERT (nworkspaces == 1) ;
int64_t *restrict workspace = Workspaces [0] ;
memset (workspace, 0, (vlen + 1) * sizeof (int64_t)) ;
const int64_t *restrict Ai = A->i ;
for (int64_t p = 0 ; p < anz ; p++)
{
int64_t i = Ai [p] ;
workspace [i]++ ;
}
// cumulative sum of the workspace, and copy back into C->p
GB_cumsum (workspace, vlen, &(C->nvec_nonempty), 1, NULL) ;
memcpy (Cp, workspace, (vlen + 1) * sizeof (int64_t)) ;
}
else if (nworkspaces == 1)
{
//----------------------------------------------------------------------
// atomic method: A is sliced but workspace is shared
//----------------------------------------------------------------------
// Only requires a single int64 workspace of size vlen, shared by all
// threads. Scales well, but requires atomics. If the # of rows is
// very small and the average row degree is high, this can be very slow
// because of contention on the atomic workspace. Otherwise, it is
// typically faster than the non-atomic method. The resulting C matrix
// is jumbled.
// compute the row counts of A. No need to scan the A->p pointers
int64_t *restrict workspace = Workspaces [0] ;
GB_memset (workspace, 0, (vlen + 1) * sizeof (int64_t), nth) ;
const int64_t *restrict Ai = A->i ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t i = Ai [p] ;
// update workspace [i]++ automically:
GB_ATOMIC_UPDATE
workspace [i]++ ;
}
C->jumbled = true ; // atomic transpose leaves C jumbled
// cumulative sum of the workspace, and copy back into C->p
GB_cumsum (workspace, vlen, &(C->nvec_nonempty), nth, Context) ;
GB_memcpy (Cp, workspace, (vlen+ 1) * sizeof (int64_t), nth) ;
}
else
{
//----------------------------------------------------------------------
// non-atomic method
//----------------------------------------------------------------------
// compute the row counts of A for each slice, one per thread; This
// method is parallel, but not highly scalable. Each thread requires
// int64 workspace of size vlen, but no atomics are required. The
// resulting C matrix is not jumbled, so this can save work if C needs
// to be unjumbled later.
ASSERT (nworkspaces == nthreads) ;
const int64_t *restrict Ap = A->p ;
const int64_t *restrict Ah = A->h ;
const int64_t *restrict Ai = A->i ;
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (tid = 0 ; tid < nthreads ; tid++)
{
// get the row counts for this slice, of size A->vlen
int64_t *restrict workspace = Workspaces [tid] ;
memset (workspace, 0, (vlen + 1) * sizeof (int64_t)) ;
for (int64_t k = A_slice [tid] ; k < A_slice [tid+1] ; k++)
{
// iterate over the entries in A(:,j)
int64_t j = GBH (Ah, k) ;
int64_t pA_start = Ap [k] ;
int64_t pA_end = Ap [k+1] ;
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
// count one more entry in C(i,:) for this slice
int64_t i = Ai [pA] ;
workspace [i]++ ;
}
}
}
// cumulative sum of the workspaces across the slices
int64_t i ;
#pragma omp parallel for num_threads(nth) schedule(static)
for (i = 0 ; i < vlen ; i++)
{
int64_t s = 0 ;
for (int tid = 0 ; tid < nthreads ; tid++)
{
int64_t *restrict workspace = Workspaces [tid] ;
int64_t c = workspace [i] ;
workspace [i] = s ;
s += c ;
}
Cp [i] = s ;
}
Cp [vlen] = 0 ;
// compute the vector pointers for C
GB_cumsum (Cp, vlen, &(C->nvec_nonempty), nth, Context) ;
// add Cp back to all Workspaces
#pragma omp parallel for num_threads(nth) schedule(static)
for (i = 0 ; i < vlen ; i++)
{
int64_t s = Cp [i] ;
int64_t *restrict workspace = Workspaces [0] ;
workspace [i] = s ;
for (int tid = 1 ; tid < nthreads ; tid++)
{
int64_t *restrict workspace = Workspaces [tid] ;
workspace [i] += s ;
}
}
}
C->magic = GB_MAGIC ;
//==========================================================================
// phase2: transpose A into C
//==========================================================================
// transpose both the pattern and the values
if (op1 == NULL && op2 == NULL)
{
// do not apply an operator; optional typecast to C->type
GB_transpose_ix (C, A, Workspaces, A_slice, nworkspaces, nthreads) ;
}
else
{
// apply an operator, C has type op->ztype
GB_transpose_op (C, C_code_iso, op1, op2, scalar, binop_bind1st, A,
Workspaces, A_slice, nworkspaces, nthreads) ;
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
GB_FREE_WORK ;
ASSERT_MATRIX_OK (C, "C transpose of A", GB0) ;
ASSERT (C->h == NULL) ;
return (GrB_SUCCESS) ;
}
|
remarks_parallel_in_multiple_target_state_machines.c | // RUN: %clang_cc1 -verify=host -Rpass=openmp-opt -Rpass-analysis=openmp-opt -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=all,safe -Rpass=openmp-opt -Rpass-analysis=openmp-opt -fopenmp -O2 -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t.out
// RUN: %clang_cc1 -fexperimental-new-pass-manager -verify=all,safe -Rpass=openmp-opt -Rpass-analysis=openmp-opt -fopenmp -O2 -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t.out
// host-no-diagnostics
void bar1(void) {
#pragma omp parallel // #0
// all-remark@#0 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}}
// safe-remark@#0 {{Parallel region is used in unknown ways; will not attempt to rewrite the state machine.}}
// force-remark@#0 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__2_wrapper, kernel ID: <NONE>}}
{
}
}
void bar2(void) {
#pragma omp parallel // #1
// all-remark@#1 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}}
// safe-remark@#1 {{Parallel region is used in unknown ways; will not attempt to rewrite the state machine.}}
// force-remark@#1 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__6_wrapper, kernel ID: <NONE>}}
{
}
}
void foo1(void) {
#pragma omp target teams // #2
// all-remark@#2 {{Target region containing the parallel region that is specialized. (parallel region ID: __omp_outlined__1_wrapper, kernel ID: __omp_offloading}}
// all-remark@#2 {{Target region containing the parallel region that is specialized. (parallel region ID: __omp_outlined__2_wrapper, kernel ID: __omp_offloading}}
{
#pragma omp parallel // #3
// all-remark@#3 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}}
// all-remark@#3 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__1_wrapper, kernel ID: __omp_offloading}}
{
}
bar1();
#pragma omp parallel // #4
// all-remark@#4 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}}
// all-remark@#4 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__2_wrapper, kernel ID: __omp_offloading}}
{
}
}
}
void foo2(void) {
#pragma omp target teams // #5
// all-remark@#5 {{Target region containing the parallel region that is specialized. (parallel region ID: __omp_outlined__5_wrapper, kernel ID: __omp_offloading}}
// all-remark@#5 {{Target region containing the parallel region that is specialized. (parallel region ID: __omp_outlined__4_wrapper, kernel ID: __omp_offloading}}
{
#pragma omp parallel // #6
// all-remark@#6 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}}
// all-remark@#6 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__4_wrapper, kernel ID: __omp_offloading}}
{
}
bar1();
bar2();
#pragma omp parallel // #7
// all-remark@#7 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}}
// all-remark@#7 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__5_wrapper, kernel ID: __omp_offloading}}
{
}
bar1();
bar2();
}
}
void foo3(void) {
#pragma omp target teams // #8
// all-remark@#8 {{Target region containing the parallel region that is specialized. (parallel region ID: __omp_outlined__7_wrapper, kernel ID: __omp_offloading}}
// all-remark@#8 {{Target region containing the parallel region that is specialized. (parallel region ID: __omp_outlined__8_wrapper, kernel ID: __omp_offloading}}
{
#pragma omp parallel // #9
// all-remark@#9 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}}
// all-remark@#9 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__7_wrapper, kernel ID: __omp_offloading}}
{
}
bar1();
bar2();
#pragma omp parallel // #10
// all-remark@#10 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}}
// all-remark@#10 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__8_wrapper, kernel ID: __omp_offloading}}
{
}
bar1();
bar2();
}
}
void spmd(void) {
// Verify we do not emit the remarks above for "SPMD" regions.
#pragma omp target teams
#pragma omp parallel
{
}
#pragma omp target teams distribute parallel for
for (int i = 0; i < 100; ++i) {
}
}
// all-remark@* 5 {{OpenMP runtime call __kmpc_global_thread_num moved to beginning of OpenMP region}}
// all-remark@* 12 {{OpenMP runtime call __kmpc_global_thread_num deduplicated}}
|
coordinate_common.h | /*!
* Copyright 2018 by Contributors
* \author Rory Mitchell
*/
#pragma once
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include <limits>
#include "../common/random.h"
namespace xgboost {
namespace linear {
/**
* \brief Calculate change in weight for a given feature. Applies l1/l2 penalty normalised by the
* number of training instances.
*
* \param sum_grad The sum gradient.
* \param sum_hess The sum hess.
* \param w The weight.
* \param reg_alpha Unnormalised L1 penalty.
* \param reg_lambda Unnormalised L2 penalty.
*
* \return The weight update.
*/
inline double CoordinateDelta(double sum_grad, double sum_hess, double w,
double reg_alpha, double reg_lambda) {
if (sum_hess < 1e-5f) return 0.0f;
const double sum_grad_l2 = sum_grad + reg_lambda * w;
const double sum_hess_l2 = sum_hess + reg_lambda;
const double tmp = w - sum_grad_l2 / sum_hess_l2;
if (tmp >= 0) {
return std::max(-(sum_grad_l2 + reg_alpha) / sum_hess_l2, -w);
} else {
return std::min(-(sum_grad_l2 - reg_alpha) / sum_hess_l2, -w);
}
}
/**
* \brief Calculate update to bias.
*
* \param sum_grad The sum gradient.
* \param sum_hess The sum hess.
*
* \return The weight update.
*/
inline double CoordinateDeltaBias(double sum_grad, double sum_hess) {
return -sum_grad / sum_hess;
}
/**
* \brief Get the gradient with respect to a single feature.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param fidx The target feature.
* \param gpair Gradients.
* \param p_fmat The feature matrix.
*
* \return The gradient and diagonal Hessian entry for a given feature.
*/
inline std::pair<double, double> GetGradient(int group_idx, int num_group, int fidx,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat) {
double sum_grad = 0.0, sum_hess = 0.0;
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
auto col = batch[fidx];
const auto ndata = static_cast<bst_omp_uint>(col.length);
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * num_group + group_idx];
if (p.GetHess() < 0.0f) continue;
sum_grad += p.GetGrad() * v;
sum_hess += p.GetHess() * v * v;
}
}
return std::make_pair(sum_grad, sum_hess);
}
/**
* \brief Get the gradient with respect to a single feature. Row-wise multithreaded.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param fidx The target feature.
* \param gpair Gradients.
* \param p_fmat The feature matrix.
*
* \return The gradient and diagonal Hessian entry for a given feature.
*/
inline std::pair<double, double> GetGradientParallel(int group_idx, int num_group, int fidx,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat) {
double sum_grad = 0.0, sum_hess = 0.0;
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
auto col = batch[fidx];
const auto ndata = static_cast<bst_omp_uint>(col.length);
#pragma omp parallel for schedule(static) reduction(+ : sum_grad, sum_hess)
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * num_group + group_idx];
if (p.GetHess() < 0.0f) continue;
sum_grad += p.GetGrad() * v;
sum_hess += p.GetHess() * v * v;
}
}
return std::make_pair(sum_grad, sum_hess);
}
/**
* \brief Get the gradient with respect to the bias. Row-wise multithreaded.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param gpair Gradients.
* \param p_fmat The feature matrix.
*
* \return The gradient and diagonal Hessian entry for the bias.
*/
inline std::pair<double, double> GetBiasGradientParallel(int group_idx, int num_group,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat) {
const RowSet &rowset = p_fmat->BufferedRowset();
double sum_grad = 0.0, sum_hess = 0.0;
const auto ndata = static_cast<bst_omp_uint>(rowset.Size());
#pragma omp parallel for schedule(static) reduction(+ : sum_grad, sum_hess)
for (bst_omp_uint i = 0; i < ndata; ++i) {
auto &p = gpair[rowset[i] * num_group + group_idx];
if (p.GetHess() >= 0.0f) {
sum_grad += p.GetGrad();
sum_hess += p.GetHess();
}
}
return std::make_pair(sum_grad, sum_hess);
}
/**
* \brief Updates the gradient vector with respect to a change in weight.
*
* \param fidx The feature index.
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param dw The change in weight.
* \param in_gpair The gradient vector to be updated.
* \param p_fmat The input feature matrix.
*/
inline void UpdateResidualParallel(int fidx, int group_idx, int num_group,
float dw, std::vector<GradientPair> *in_gpair,
DMatrix *p_fmat) {
if (dw == 0.0f) return;
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
auto col = batch[fidx];
// update grad value
const auto num_row = static_cast<bst_omp_uint>(col.length);
#pragma omp parallel for schedule(static)
for (bst_omp_uint j = 0; j < num_row; ++j) {
GradientPair &p = (*in_gpair)[col[j].index * num_group + group_idx];
if (p.GetHess() < 0.0f) continue;
p += GradientPair(p.GetHess() * col[j].fvalue * dw, 0);
}
}
}
/**
* \brief Updates the gradient vector based on a change in the bias.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param dbias The change in bias.
* \param in_gpair The gradient vector to be updated.
* \param p_fmat The input feature matrix.
*/
inline void UpdateBiasResidualParallel(int group_idx, int num_group, float dbias,
std::vector<GradientPair> *in_gpair,
DMatrix *p_fmat) {
if (dbias == 0.0f) return;
const RowSet &rowset = p_fmat->BufferedRowset();
const auto ndata = static_cast<bst_omp_uint>(p_fmat->Info().num_row_);
#pragma omp parallel for schedule(static)
for (bst_omp_uint i = 0; i < ndata; ++i) {
GradientPair &g = (*in_gpair)[rowset[i] * num_group + group_idx];
if (g.GetHess() < 0.0f) continue;
g += GradientPair(g.GetHess() * dbias, 0);
}
}
/**
* \brief Abstract class for stateful feature selection or ordering
* in coordinate descent algorithms.
*/
class FeatureSelector {
public:
/*! \brief factory method */
static FeatureSelector *Create(int choice);
/*! \brief virtual destructor */
virtual ~FeatureSelector() = default;
/**
* \brief Setting up the selector state prior to looping through features.
*
* \param model The model.
* \param gpair The gpair.
* \param p_fmat The feature matrix.
* \param alpha Regularisation alpha.
* \param lambda Regularisation lambda.
* \param param A parameter with algorithm-dependent use.
*/
virtual void Setup(const gbm::GBLinearModel &model,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat,
float alpha, float lambda, int param) {}
/**
* \brief Select next coordinate to update.
*
* \param iteration The iteration in a loop through features
* \param model The model.
* \param group_idx Zero-based index of the group.
* \param gpair The gpair.
* \param p_fmat The feature matrix.
* \param alpha Regularisation alpha.
* \param lambda Regularisation lambda.
*
* \return The index of the selected feature. -1 indicates none selected.
*/
virtual int NextFeature(int iteration,
const gbm::GBLinearModel &model,
int group_idx,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) = 0;
};
/**
* \brief Deterministic selection by cycling through features one at a time.
*/
class CyclicFeatureSelector : public FeatureSelector {
public:
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
return iteration % model.param.num_feature;
}
};
/**
* \brief Similar to Cyclyc but with random feature shuffling prior to each update.
* \note Its randomness is controllable by setting a random seed.
*/
class ShuffleFeatureSelector : public FeatureSelector {
public:
void Setup(const gbm::GBLinearModel &model,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda, int param) override {
if (feat_index_.size() == 0) {
feat_index_.resize(model.param.num_feature);
std::iota(feat_index_.begin(), feat_index_.end(), 0);
}
std::shuffle(feat_index_.begin(), feat_index_.end(), common::GlobalRandom());
}
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
return feat_index_[iteration % model.param.num_feature];
}
protected:
std::vector<bst_uint> feat_index_;
};
/**
* \brief A random (with replacement) coordinate selector.
* \note Its randomness is controllable by setting a random seed.
*/
class RandomFeatureSelector : public FeatureSelector {
public:
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
return common::GlobalRandom()() % model.param.num_feature;
}
};
/**
* \brief Select coordinate with the greatest gradient magnitude.
* \note It has O(num_feature^2) complexity. It is fully deterministic.
*
* \note It allows restricting the selection to top_k features per group with
* the largest magnitude of univariate weight change, by passing the top_k value
* through the `param` argument of Setup(). That would reduce the complexity to
* O(num_feature*top_k).
*/
class GreedyFeatureSelector : public FeatureSelector {
public:
void Setup(const gbm::GBLinearModel &model,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda, int param) override {
top_k_ = static_cast<bst_uint>(param);
const bst_uint ngroup = model.param.num_output_group;
if (param <= 0) top_k_ = std::numeric_limits<bst_uint>::max();
if (counter_.size() == 0) {
counter_.resize(ngroup);
gpair_sums_.resize(model.param.num_feature * ngroup);
}
for (bst_uint gid = 0u; gid < ngroup; ++gid) {
counter_[gid] = 0u;
}
}
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
// k-th selected feature for a group
auto k = counter_[group_idx]++;
// stop after either reaching top-K or going through all the features in a group
if (k >= top_k_ || counter_[group_idx] == model.param.num_feature) return -1;
const int ngroup = model.param.num_output_group;
const bst_omp_uint nfeat = model.param.num_feature;
// Calculate univariate gradient sums
std::fill(gpair_sums_.begin(), gpair_sums_.end(), std::make_pair(0., 0.));
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
#pragma omp parallel for schedule(static)
for (bst_omp_uint i = 0; i < nfeat; ++i) {
const auto col = batch[i];
const bst_uint ndata = col.length;
auto &sums = gpair_sums_[group_idx * nfeat + i];
for (bst_uint j = 0u; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * ngroup + group_idx];
if (p.GetHess() < 0.f) continue;
sums.first += p.GetGrad() * v;
sums.second += p.GetHess() * v * v;
}
}
}
// Find a feature with the largest magnitude of weight change
int best_fidx = 0;
double best_weight_update = 0.0f;
for (bst_omp_uint fidx = 0; fidx < nfeat; ++fidx) {
auto &s = gpair_sums_[group_idx * nfeat + fidx];
float dw = std::abs(static_cast<bst_float>(
CoordinateDelta(s.first, s.second, model[fidx][group_idx], alpha, lambda)));
if (dw > best_weight_update) {
best_weight_update = dw;
best_fidx = fidx;
}
}
return best_fidx;
}
protected:
bst_uint top_k_;
std::vector<bst_uint> counter_;
std::vector<std::pair<double, double>> gpair_sums_;
};
/**
* \brief Thrifty, approximately-greedy feature selector.
*
* \note Prior to cyclic updates, reorders features in descending magnitude of
* their univariate weight changes. This operation is multithreaded and is a
* linear complexity approximation of the quadratic greedy selection.
*
* \note It allows restricting the selection to top_k features per group with
* the largest magnitude of univariate weight change, by passing the top_k value
* through the `param` argument of Setup().
*/
class ThriftyFeatureSelector : public FeatureSelector {
public:
void Setup(const gbm::GBLinearModel &model,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda, int param) override {
top_k_ = static_cast<bst_uint>(param);
if (param <= 0) top_k_ = std::numeric_limits<bst_uint>::max();
const bst_uint ngroup = model.param.num_output_group;
const bst_omp_uint nfeat = model.param.num_feature;
if (deltaw_.size() == 0) {
deltaw_.resize(nfeat * ngroup);
sorted_idx_.resize(nfeat * ngroup);
counter_.resize(ngroup);
gpair_sums_.resize(nfeat * ngroup);
}
// Calculate univariate gradient sums
std::fill(gpair_sums_.begin(), gpair_sums_.end(), std::make_pair(0., 0.));
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
// column-parallel is usually faster than row-parallel
#pragma omp parallel for schedule(static)
for (bst_omp_uint i = 0; i < nfeat; ++i) {
const auto col = batch[i];
const bst_uint ndata = col.length;
for (bst_uint gid = 0u; gid < ngroup; ++gid) {
auto &sums = gpair_sums_[gid * nfeat + i];
for (bst_uint j = 0u; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * ngroup + gid];
if (p.GetHess() < 0.f) continue;
sums.first += p.GetGrad() * v;
sums.second += p.GetHess() * v * v;
}
}
}
}
// rank by descending weight magnitude within the groups
std::fill(deltaw_.begin(), deltaw_.end(), 0.f);
std::iota(sorted_idx_.begin(), sorted_idx_.end(), 0);
bst_float *pdeltaw = &deltaw_[0];
for (bst_uint gid = 0u; gid < ngroup; ++gid) {
// Calculate univariate weight changes
for (bst_omp_uint i = 0; i < nfeat; ++i) {
auto ii = gid * nfeat + i;
auto &s = gpair_sums_[ii];
deltaw_[ii] = static_cast<bst_float>(CoordinateDelta(
s.first, s.second, model[i][gid], alpha, lambda));
}
// sort in descending order of deltaw abs values
auto start = sorted_idx_.begin() + gid * nfeat;
std::sort(start, start + nfeat,
[pdeltaw](size_t i, size_t j) {
return std::abs(*(pdeltaw + i)) > std::abs(*(pdeltaw + j));
});
counter_[gid] = 0u;
}
}
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
// k-th selected feature for a group
auto k = counter_[group_idx]++;
// stop after either reaching top-N or going through all the features in a group
if (k >= top_k_ || counter_[group_idx] == model.param.num_feature) return -1;
// note that sorted_idx stores the "long" indices
const size_t grp_offset = group_idx * model.param.num_feature;
return static_cast<int>(sorted_idx_[grp_offset + k] - grp_offset);
}
protected:
bst_uint top_k_;
std::vector<bst_float> deltaw_;
std::vector<size_t> sorted_idx_;
std::vector<bst_uint> counter_;
std::vector<std::pair<double, double>> gpair_sums_;
};
/**
* \brief A set of available FeatureSelector's
*/
enum FeatureSelectorEnum {
kCyclic = 0,
kShuffle,
kThrifty,
kGreedy,
kRandom
};
inline FeatureSelector *FeatureSelector::Create(int choice) {
switch (choice) {
case kCyclic:
return new CyclicFeatureSelector();
case kShuffle:
return new ShuffleFeatureSelector();
case kThrifty:
return new ThriftyFeatureSelector();
case kGreedy:
return new GreedyFeatureSelector();
case kRandom:
return new RandomFeatureSelector();
default:
LOG(FATAL) << "unknown coordinate selector: " << choice;
}
return nullptr;
}
} // namespace linear
} // namespace xgboost
|
qcmdpc_decoder.c | /*
Copyright (c) 2019 Valentin Vasseur
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE
*/
#include <omp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "cli.h"
#include "decoder.h"
#include "param.h"
#include "sparse_cyclic.h"
/* In seconds */
#define TIME_BETWEEN_PRINTS 5
static void print_parameters(void);
static void print_stats(long int *n_test, long int *n_success);
static void inthandler(int signo);
static long int *n_test = NULL;
static long int *n_success = NULL;
static long int **n_iter = NULL;
static int n_threads = 1;
static int max_iter = 100;
static void print_parameters(void) {
fprintf(stderr,
"-DINDEX=%d "
"-DBLOCK_LENGTH=%d "
"-DBLOCK_WEIGHT=%d "
"-DERROR_WEIGHT=%d "
"-DOUROBOROS=%d "
"-DTTL_COEFF0=%lf "
"-DTTL_COEFF1=%lf "
"-DTTL_SATURATE=%d\n",
INDEX, BLOCK_LENGTH, BLOCK_WEIGHT, ERROR_WEIGHT, OUROBOROS,
TTL_COEFF0, TTL_COEFF1, TTL_SATURATE);
}
static void print_stats(long int *n_test, long int *n_success) {
if (!n_test && !n_success)
return;
long int n_test_total = 0;
long int n_success_total = 0;
for (int i = 0; i < n_threads; ++i) {
n_test_total += n_test[i];
n_success_total += n_success[i];
}
long int n_iter_total[max_iter + 1];
memset(n_iter_total, 0, (max_iter + 1) * sizeof(long int));
for (int i = 0; i < n_threads; ++i) {
for (int it = 0; it <= max_iter; ++it) {
n_iter_total[it] += n_iter[i][it];
}
}
fprintf(stderr, "%ld", n_test_total);
for (int it = 0; it <= max_iter; ++it) {
if (n_iter_total[it])
fprintf(stderr, " %d:%ld", it, n_iter_total[it]);
}
if (n_success_total != n_test_total)
fprintf(stderr, " >%d:%ld", max_iter, n_test_total - n_success_total);
fprintf(stderr, "\n");
}
static void inthandler(int signo) {
print_stats(n_test, n_success);
if (signo != SIGHUP)
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[]) {
struct sigaction action;
action.sa_handler = inthandler;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGINT, &action, NULL);
sigaction(SIGHUP, &action, NULL);
/* Number of test rounds */
long int r = -1;
/* PRNG seeds */
uint64_t s[2] = {0, 0};
int quiet = 0;
parse_arguments(argc, argv, &max_iter, &r, &n_threads, &quiet);
print_parameters();
seed_random(&s[0], &s[1]);
time_t last_print_time = time(NULL);
/* Keep independent statistics for all threads. */
n_test = calloc(n_threads, sizeof(long int));
n_success = calloc(n_threads, sizeof(long int));
n_iter = malloc(n_threads * sizeof(long int *));
for (index_t i = 0; i < n_threads; ++i) {
n_iter[i] = calloc(max_iter + 1, sizeof(long int));
}
#pragma omp parallel num_threads(n_threads)
{
int tid = omp_get_thread_num();
int thread_quiet = tid ? 1 : quiet;
/* Parity check matrix */
sparse_t *H = sparse_array_new(INDEX, BLOCK_WEIGHT);
/* Error pattern */
sparse_t e_block = sparse_new(ERROR_WEIGHT);
/* Error pattern on the syndrome (for Ouroboros) */
#if !OUROBOROS
sparse_t e2_block = NULL;
#else
sparse_t e2_block = sparse_new(ERROR_WEIGHT / 2);
#endif
struct decoder dec;
alloc_decoder(&dec);
prng_t prng = malloc(sizeof(struct PRNG));
prng->s0 = s[0];
prng->s1 = s[1];
prng->random_lim = random_lim;
prng->random_uint64_t = random_uint64_t;
for (int i = 0; i < tid; ++i) {
jump(&prng->s0, &prng->s1);
}
long int thread_total_tests = (tid + r) / n_threads;
while (r == -1 || n_test[tid] < thread_total_tests) {
sparse_array_rand(INDEX, BLOCK_LENGTH, BLOCK_WEIGHT, prng, H);
sparse_rand(INDEX * BLOCK_LENGTH, ERROR_WEIGHT, prng, e_block);
#if OUROBOROS
sparse_rand(BLOCK_LENGTH, SYNDROME_STOP, prng, e2_block);
#endif
reset_decoder(&dec);
init_decoder_error(&dec, H, e_block, e2_block);
if (qcmdpc_decode_ttl(&dec, max_iter)) {
n_success[tid]++;
n_iter[tid][dec.iter]++;
}
n_test[tid]++;
time_t current_time;
if (!thread_quiet && (current_time = time(NULL)) >
last_print_time + TIME_BETWEEN_PRINTS) {
print_stats(n_test, n_success);
last_print_time = current_time;
}
}
free(prng);
sparse_array_free(INDEX, H);
sparse_free(e_block);
if (e2_block) {
sparse_free(e2_block);
}
free_decoder(&dec);
}
print_stats(n_test, n_success);
free(n_test);
free(n_success);
for (index_t i = 0; i < n_threads; ++i) {
free(n_iter[i]);
}
free(n_iter);
exit(EXIT_SUCCESS);
}
|
data.c | #include "data.h"
#include "utils.h"
#include "image.h"
#include "cuda.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
list *get_paths(char *filename)
{
char *path;
FILE *file = fopen(filename, "r");
if(!file) file_error(filename);
list *lines = make_list();
while((path=fgetl(file))){
list_insert(lines, path);
}
fclose(file);
return lines;
}
/*
char **get_random_paths_indexes(char **paths, int n, int m, int *indexes)
{
char **random_paths = calloc(n, sizeof(char*));
int i;
pthread_mutex_lock(&mutex);
for(i = 0; i < n; ++i){
int index = rand()%m;
indexes[i] = index;
random_paths[i] = paths[index];
if(i == 0) printf("%s\n", paths[index]);
}
pthread_mutex_unlock(&mutex);
return random_paths;
}
*/
char **get_random_paths(char **paths, int n, int m)
{
char **random_paths = calloc(n, sizeof(char*));
int i;
pthread_mutex_lock(&mutex);
for(i = 0; i < n; ++i){
int index = rand()%m;
random_paths[i] = paths[index];
//if(i == 0) printf("%s\n", paths[index]);
}
pthread_mutex_unlock(&mutex);
return random_paths;
}
char **find_replace_paths(char **paths, int n, char *find, char *replace)
{
char **replace_paths = calloc(n, sizeof(char*));
int i;
for(i = 0; i < n; ++i){
char replaced[4096];
find_replace(paths[i], find, replace, replaced);
replace_paths[i] = copy_string(replaced);
}
return replace_paths;
}
matrix load_image_paths_gray(char **paths, int n, int w, int h)
{
int i;
matrix X;
X.rows = n;
X.vals = calloc(X.rows, sizeof(float*));
X.cols = 0;
for(i = 0; i < n; ++i){
image im = load_image(paths[i], w, h, 3);
image gray = grayscale_image(im);
free_image(im);
im = gray;
X.vals[i] = im.data;
X.cols = im.h*im.w*im.c;
}
return X;
}
matrix load_image_paths(char **paths, int n, int w, int h)
{
int i;
matrix X;
X.rows = n;
X.vals = calloc(X.rows, sizeof(float*));
X.cols = 0;
for(i = 0; i < n; ++i){
image im = load_image_color(paths[i], w, h);
X.vals[i] = im.data;
X.cols = im.h*im.w*im.c;
}
return X;
}
matrix load_image_augment_paths(char **paths, int n, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure, int center)
{
int i;
matrix X;
X.rows = n;
X.vals = calloc(X.rows, sizeof(float*));
X.cols = 0;
for(i = 0; i < n; ++i){
image im = load_image_color(paths[i], 0, 0);
image crop;
if(center){
crop = center_crop_image(im, size, size);
} else {
crop = random_augment_image(im, angle, aspect, min, max, size, size);
}
int flip = rand()%2;
if (flip) flip_image(crop);
random_distort_image(crop, hue, saturation, exposure);
/*
show_image(im, "orig");
show_image(crop, "crop");
cvWaitKey(0);
*/
free_image(im);
X.vals[i] = crop.data;
X.cols = crop.h*crop.w*crop.c;
}
return X;
}
box_label *read_boxes(char *filename, int *n)
{
FILE *file = fopen(filename, "r");
if(!file) file_error(filename);
float x, y, h, w;
int id;
int count = 0;
int size = 64;
box_label *boxes = calloc(size, sizeof(box_label));
while(fscanf(file, "%d %f %f %f %f", &id, &x, &y, &w, &h) == 5){
if(count == size) {
size = size * 2;
boxes = realloc(boxes, size*sizeof(box_label));
}
boxes[count].id = id;
boxes[count].x = x;
boxes[count].y = y;
boxes[count].h = h;
boxes[count].w = w;
boxes[count].left = x - w/2;
boxes[count].right = x + w/2;
boxes[count].top = y - h/2;
boxes[count].bottom = y + h/2;
++count;
}
fclose(file);
*n = count;
return boxes;
}
void randomize_boxes(box_label *b, int n)
{
int i;
for(i = 0; i < n; ++i){
box_label swap = b[i];
int index = rand()%n;
b[i] = b[index];
b[index] = swap;
}
}
void correct_boxes(box_label *boxes, int n, float dx, float dy, float sx, float sy, int flip)
{
int i;
for(i = 0; i < n; ++i){
if(boxes[i].x == 0 && boxes[i].y == 0) {
boxes[i].x = 999999;
boxes[i].y = 999999;
boxes[i].w = 999999;
boxes[i].h = 999999;
continue;
}
boxes[i].left = boxes[i].left * sx - dx;
boxes[i].right = boxes[i].right * sx - dx;
boxes[i].top = boxes[i].top * sy - dy;
boxes[i].bottom = boxes[i].bottom* sy - dy;
if(flip){
float swap = boxes[i].left;
boxes[i].left = 1. - boxes[i].right;
boxes[i].right = 1. - swap;
}
boxes[i].left = constrain(0, 1, boxes[i].left);
boxes[i].right = constrain(0, 1, boxes[i].right);
boxes[i].top = constrain(0, 1, boxes[i].top);
boxes[i].bottom = constrain(0, 1, boxes[i].bottom);
boxes[i].x = (boxes[i].left+boxes[i].right)/2;
boxes[i].y = (boxes[i].top+boxes[i].bottom)/2;
boxes[i].w = (boxes[i].right - boxes[i].left);
boxes[i].h = (boxes[i].bottom - boxes[i].top);
boxes[i].w = constrain(0, 1, boxes[i].w);
boxes[i].h = constrain(0, 1, boxes[i].h);
}
}
void fill_truth_swag(char *path, float *truth, int classes, int flip, float dx, float dy, float sx, float sy)
{
char labelpath[4096];
find_replace(path, "images", "labels", labelpath);
find_replace(labelpath, "JPEGImages", "labels", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".JPG", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
int count = 0;
box_label *boxes = read_boxes(labelpath, &count);
randomize_boxes(boxes, count);
correct_boxes(boxes, count, dx, dy, sx, sy, flip);
float x,y,w,h;
int id;
int i;
for (i = 0; i < count && i < 90; ++i) {
x = boxes[i].x;
y = boxes[i].y;
w = boxes[i].w;
h = boxes[i].h;
id = boxes[i].id;
if (w < .0 || h < .0) continue;
int index = (4+classes) * i;
truth[index++] = x;
truth[index++] = y;
truth[index++] = w;
truth[index++] = h;
if (id < classes) truth[index+id] = 1;
}
free(boxes);
}
void fill_truth_region(char *path, float *truth, int classes, int num_boxes, int flip, float dx, float dy, float sx, float sy)
{
char labelpath[4096];
find_replace(path, "images", "labels", labelpath);
find_replace(labelpath, "JPEGImages", "labels", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".png", ".txt", labelpath);
find_replace(labelpath, ".JPG", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
int count = 0;
box_label *boxes = read_boxes(labelpath, &count);
randomize_boxes(boxes, count);
correct_boxes(boxes, count, dx, dy, sx, sy, flip);
float x,y,w,h;
int id;
int i;
for (i = 0; i < count; ++i) {
x = boxes[i].x;
y = boxes[i].y;
w = boxes[i].w;
h = boxes[i].h;
id = boxes[i].id;
if (w < .005 || h < .005) continue;
int col = (int)(x*num_boxes);
int row = (int)(y*num_boxes);
x = x*num_boxes - col;
y = y*num_boxes - row;
int index = (col+row*num_boxes)*(5+classes);
if (truth[index]) continue;
truth[index++] = 1;
if (id < classes) truth[index+id] = 1;
index += classes;
truth[index++] = x;
truth[index++] = y;
truth[index++] = w;
truth[index++] = h;
}
free(boxes);
}
void load_rle(image im, int *rle, int n)
{
int count = 0;
int curr = 0;
int i,j;
for(i = 0; i < n; ++i){
for(j = 0; j < rle[i]; ++j){
im.data[count++] = curr;
}
curr = 1 - curr;
}
for(; count < im.h*im.w*im.c; ++count){
im.data[count] = curr;
}
}
void or_image(image src, image dest, int c)
{
int i;
for(i = 0; i < src.w*src.h; ++i){
if(src.data[i]) dest.data[dest.w*dest.h*c + i] = 1;
}
}
void exclusive_image(image src)
{
int k, j, i;
int s = src.w*src.h;
for(k = 0; k < src.c-1; ++k){
for(i = 0; i < s; ++i){
if (src.data[k*s + i]){
for(j = k+1; j < src.c; ++j){
src.data[j*s + i] = 0;
}
}
}
}
}
box bound_image(image im)
{
int x,y;
int minx = im.w;
int miny = im.h;
int maxx = 0;
int maxy = 0;
for(y = 0; y < im.h; ++y){
for(x = 0; x < im.w; ++x){
if(im.data[y*im.w + x]){
minx = (x < minx) ? x : minx;
miny = (y < miny) ? y : miny;
maxx = (x > maxx) ? x : maxx;
maxy = (y > maxy) ? y : maxy;
}
}
}
box b = {minx, miny, maxx-minx + 1, maxy-miny + 1};
//printf("%f %f %f %f\n", b.x, b.y, b.w, b.h);
return b;
}
void fill_truth_iseg(char *path, int num_boxes, float *truth, int classes, int w, int h, augment_args aug, int flip, int mw, int mh)
{
char labelpath[4096];
find_replace(path, "images", "mask", labelpath);
find_replace(labelpath, "JPEGImages", "mask", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".JPG", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
FILE *file = fopen(labelpath, "r");
if(!file) file_error(labelpath);
char buff[32788];
int id;
int i = 0;
image part = make_image(w, h, 1);
while((fscanf(file, "%d %s", &id, buff) == 2) && i < num_boxes){
int n = 0;
int *rle = read_intlist(buff, &n, 0);
load_rle(part, rle, n);
image sized = rotate_crop_image(part, aug.rad, aug.scale, aug.w, aug.h, aug.dx, aug.dy, aug.aspect);
if(flip) flip_image(sized);
box b = bound_image(sized);
if(b.w > 0){
image crop = crop_image(sized, b.x, b.y, b.w, b.h);
image mask = resize_image(crop, mw, mh);
truth[i*(4 + mw*mh + 1) + 0] = (b.x + b.w/2.)/sized.w;
truth[i*(4 + mw*mh + 1) + 1] = (b.y + b.h/2.)/sized.h;
truth[i*(4 + mw*mh + 1) + 2] = b.w/sized.w;
truth[i*(4 + mw*mh + 1) + 3] = b.h/sized.h;
int j;
for(j = 0; j < mw*mh; ++j){
truth[i*(4 + mw*mh + 1) + 4 + j] = mask.data[j];
}
truth[i*(4 + mw*mh + 1) + 4 + mw*mh] = id;
free_image(crop);
free_image(mask);
++i;
}
free_image(sized);
free(rle);
}
fclose(file);
free_image(part);
}
void fill_truth_detection(char *path, int num_boxes, float *truth, int classes, int flip, float dx, float dy, float sx, float sy)
{
char labelpath[4096];
find_replace(path, "images", "labels", labelpath);
find_replace(labelpath, "JPEGImages", "labels", labelpath);
find_replace(labelpath, "raw", "labels", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".png", ".txt", labelpath);
find_replace(labelpath, ".JPG", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
int count = 0;
box_label *boxes = read_boxes(labelpath, &count);
randomize_boxes(boxes, count);
correct_boxes(boxes, count, dx, dy, sx, sy, flip);
if(count > num_boxes) count = num_boxes;
float x,y,w,h;
int id;
int i;
int sub = 0;
for (i = 0; i < count; ++i) {
x = boxes[i].x;
y = boxes[i].y;
w = boxes[i].w;
h = boxes[i].h;
id = boxes[i].id;
if ((w < .001 || h < .001)) {
++sub;
continue;
}
truth[(i-sub)*5+0] = x;
truth[(i-sub)*5+1] = y;
truth[(i-sub)*5+2] = w;
truth[(i-sub)*5+3] = h;
truth[(i-sub)*5+4] = id;
}
free(boxes);
}
#define NUMCHARS 37
void print_letters(float *pred, int n)
{
int i;
for(i = 0; i < n; ++i){
int index = max_index(pred+i*NUMCHARS, NUMCHARS);
printf("%c", int_to_alphanum(index));
}
printf("\n");
}
void fill_truth_captcha(char *path, int n, float *truth)
{
char *begin = strrchr(path, '/');
++begin;
int i;
for(i = 0; i < strlen(begin) && i < n && begin[i] != '.'; ++i){
int index = alphanum_to_int(begin[i]);
if(index > 35) printf("Bad %c\n", begin[i]);
truth[i*NUMCHARS+index] = 1;
}
for(;i < n; ++i){
truth[i*NUMCHARS + NUMCHARS-1] = 1;
}
}
data load_data_captcha(char **paths, int n, int m, int k, int w, int h)
{
if(m) paths = get_random_paths(paths, n, m);
data d = {0};
d.shallow = 0;
d.X = load_image_paths(paths, n, w, h);
d.y = make_matrix(n, k*NUMCHARS);
int i;
for(i = 0; i < n; ++i){
fill_truth_captcha(paths[i], k, d.y.vals[i]);
}
if(m) free(paths);
return d;
}
data load_data_captcha_encode(char **paths, int n, int m, int w, int h)
{
if(m) paths = get_random_paths(paths, n, m);
data d = {0};
d.shallow = 0;
d.X = load_image_paths(paths, n, w, h);
d.X.cols = 17100;
d.y = d.X;
if(m) free(paths);
return d;
}
void fill_truth(char *path, char **labels, int k, float *truth)
{
int i;
memset(truth, 0, k*sizeof(float));
int count = 0;
for(i = 0; i < k; ++i){
if(strstr(path, labels[i])){
truth[i] = 1;
++count;
//printf("%s %s %d\n", path, labels[i], i);
}
}
if(count != 1 && (k != 1 || count != 0)) printf("Too many or too few labels: %d, %s\n", count, path);
}
void fill_hierarchy(float *truth, int k, tree *hierarchy)
{
int j;
for(j = 0; j < k; ++j){
if(truth[j]){
int parent = hierarchy->parent[j];
while(parent >= 0){
truth[parent] = 1;
parent = hierarchy->parent[parent];
}
}
}
int i;
int count = 0;
for(j = 0; j < hierarchy->groups; ++j){
//printf("%d\n", count);
int mask = 1;
for(i = 0; i < hierarchy->group_size[j]; ++i){
if(truth[count + i]){
mask = 0;
break;
}
}
if (mask) {
for(i = 0; i < hierarchy->group_size[j]; ++i){
truth[count + i] = SECRET_NUM;
}
}
count += hierarchy->group_size[j];
}
}
matrix load_regression_labels_paths(char **paths, int n, int k)
{
matrix y = make_matrix(n, k);
int i,j;
for(i = 0; i < n; ++i){
char labelpath[4096];
find_replace(paths[i], "images", "labels", labelpath);
find_replace(labelpath, "JPEGImages", "labels", labelpath);
find_replace(labelpath, ".BMP", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
find_replace(labelpath, ".JPG", ".txt", labelpath);
find_replace(labelpath, ".JPeG", ".txt", labelpath);
find_replace(labelpath, ".Jpeg", ".txt", labelpath);
find_replace(labelpath, ".PNG", ".txt", labelpath);
find_replace(labelpath, ".TIF", ".txt", labelpath);
find_replace(labelpath, ".bmp", ".txt", labelpath);
find_replace(labelpath, ".jpeg", ".txt", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".png", ".txt", labelpath);
find_replace(labelpath, ".tif", ".txt", labelpath);
FILE *file = fopen(labelpath, "r");
for(j = 0; j < k; ++j){
fscanf(file, "%f", &(y.vals[i][j]));
}
fclose(file);
}
return y;
}
matrix load_labels_paths(char **paths, int n, char **labels, int k, tree *hierarchy)
{
matrix y = make_matrix(n, k);
int i;
for(i = 0; i < n && labels; ++i){
fill_truth(paths[i], labels, k, y.vals[i]);
if(hierarchy){
fill_hierarchy(y.vals[i], k, hierarchy);
}
}
return y;
}
matrix load_tags_paths(char **paths, int n, int k)
{
matrix y = make_matrix(n, k);
int i;
//int count = 0;
for(i = 0; i < n; ++i){
char label[4096];
find_replace(paths[i], "images", "labels", label);
find_replace(label, ".jpg", ".txt", label);
FILE *file = fopen(label, "r");
if (!file) continue;
//++count;
int tag;
while(fscanf(file, "%d", &tag) == 1){
if(tag < k){
y.vals[i][tag] = 1;
}
}
fclose(file);
}
//printf("%d/%d\n", count, n);
return y;
}
char **get_labels(char *filename)
{
list *plist = get_paths(filename);
char **labels = (char **)list_to_array(plist);
free_list(plist);
return labels;
}
void free_data(data d)
{
if(!d.shallow){
free_matrix(d.X);
free_matrix(d.y);
}else{
free(d.X.vals);
free(d.y.vals);
}
}
image get_segmentation_image(char *path, int w, int h, int classes)
{
char labelpath[4096];
find_replace(path, "images", "mask", labelpath);
find_replace(labelpath, "JPEGImages", "mask", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".JPG", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
image mask = make_image(w, h, classes);
FILE *file = fopen(labelpath, "r");
if(!file) file_error(labelpath);
char buff[32788];
int id;
image part = make_image(w, h, 1);
while(fscanf(file, "%d %s", &id, buff) == 2){
int n = 0;
int *rle = read_intlist(buff, &n, 0);
load_rle(part, rle, n);
or_image(part, mask, id);
free(rle);
}
//exclusive_image(mask);
fclose(file);
free_image(part);
return mask;
}
image get_segmentation_image2(char *path, int w, int h, int classes)
{
char labelpath[4096];
find_replace(path, "images", "mask", labelpath);
find_replace(labelpath, "JPEGImages", "mask", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".JPG", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
image mask = make_image(w, h, classes+1);
int i;
for(i = 0; i < w*h; ++i){
mask.data[w*h*classes + i] = 1;
}
FILE *file = fopen(labelpath, "r");
if(!file) file_error(labelpath);
char buff[32788];
int id;
image part = make_image(w, h, 1);
while(fscanf(file, "%d %s", &id, buff) == 2){
int n = 0;
int *rle = read_intlist(buff, &n, 0);
load_rle(part, rle, n);
or_image(part, mask, id);
for(i = 0; i < w*h; ++i){
if(part.data[i]) mask.data[w*h*classes + i] = 0;
}
free(rle);
}
//exclusive_image(mask);
fclose(file);
free_image(part);
return mask;
}
data load_data_seg(int n, char **paths, int m, int w, int h, int classes, int min, int max, float angle, float aspect, float hue, float saturation, float exposure, int div)
{
char **random_paths = get_random_paths(paths, n, m);
int i;
data d = {0};
d.shallow = 0;
d.X.rows = n;
d.X.vals = calloc(d.X.rows, sizeof(float*));
d.X.cols = h*w*3;
d.y.rows = n;
d.y.cols = h*w*classes/div/div;
d.y.vals = calloc(d.X.rows, sizeof(float*));
for(i = 0; i < n; ++i){
image orig = load_image_color(random_paths[i], 0, 0);
augment_args a = random_augment_args(orig, angle, aspect, min, max, w, h);
image sized = rotate_crop_image(orig, a.rad, a.scale, a.w, a.h, a.dx, a.dy, a.aspect);
int flip = rand()%2;
if(flip) flip_image(sized);
random_distort_image(sized, hue, saturation, exposure);
d.X.vals[i] = sized.data;
image mask = get_segmentation_image(random_paths[i], orig.w, orig.h, classes);
//image mask = make_image(orig.w, orig.h, classes+1);
image sized_m = rotate_crop_image(mask, a.rad, a.scale/div, a.w/div, a.h/div, a.dx/div, a.dy/div, a.aspect);
if(flip) flip_image(sized_m);
d.y.vals[i] = sized_m.data;
free_image(orig);
free_image(mask);
/*
image rgb = mask_to_rgb(sized_m, classes);
show_image(rgb, "part");
show_image(sized, "orig");
cvWaitKey(0);
free_image(rgb);
*/
}
free(random_paths);
return d;
}
data load_data_iseg(int n, char **paths, int m, int w, int h, int classes, int boxes, int coords, int min, int max, float angle, float aspect, float hue, float saturation, float exposure)
{
char **random_paths = get_random_paths(paths, n, m);
int i;
data d = {0};
d.shallow = 0;
d.X.rows = n;
d.X.vals = calloc(d.X.rows, sizeof(float*));
d.X.cols = h*w*3;
d.y = make_matrix(n, (coords+1)*boxes);
for(i = 0; i < n; ++i){
image orig = load_image_color(random_paths[i], 0, 0);
augment_args a = random_augment_args(orig, angle, aspect, min, max, w, h);
image sized = rotate_crop_image(orig, a.rad, a.scale, a.w, a.h, a.dx, a.dy, a.aspect);
int flip = rand()%2;
if(flip) flip_image(sized);
random_distort_image(sized, hue, saturation, exposure);
d.X.vals[i] = sized.data;
//show_image(sized, "image");
fill_truth_iseg(random_paths[i], boxes, d.y.vals[i], classes, orig.w, orig.h, a, flip, 14, 14);
free_image(orig);
/*
image rgb = mask_to_rgb(sized_m, classes);
show_image(rgb, "part");
show_image(sized, "orig");
cvWaitKey(0);
free_image(rgb);
*/
}
free(random_paths);
return d;
}
data load_data_region(int n, char **paths, int m, int w, int h, int size, int classes, float jitter, float hue, float saturation, float exposure)
{
char **random_paths = get_random_paths(paths, n, m);
int i;
data d = {0};
d.shallow = 0;
d.X.rows = n;
d.X.vals = calloc(d.X.rows, sizeof(float*));
d.X.cols = h*w*3;
int k = size*size*(5+classes);
d.y = make_matrix(n, k);
for(i = 0; i < n; ++i){
image orig = load_image_color(random_paths[i], 0, 0);
int oh = orig.h;
int ow = orig.w;
int dw = (ow*jitter);
int dh = (oh*jitter);
int pleft = rand_uniform(-dw, dw);
int pright = rand_uniform(-dw, dw);
int ptop = rand_uniform(-dh, dh);
int pbot = rand_uniform(-dh, dh);
int swidth = ow - pleft - pright;
int sheight = oh - ptop - pbot;
float sx = (float)swidth / ow;
float sy = (float)sheight / oh;
int flip = rand()%2;
image cropped = crop_image(orig, pleft, ptop, swidth, sheight);
float dx = ((float)pleft/ow)/sx;
float dy = ((float)ptop /oh)/sy;
image sized = resize_image(cropped, w, h);
if(flip) flip_image(sized);
random_distort_image(sized, hue, saturation, exposure);
d.X.vals[i] = sized.data;
fill_truth_region(random_paths[i], d.y.vals[i], classes, size, flip, dx, dy, 1./sx, 1./sy);
free_image(orig);
free_image(cropped);
}
free(random_paths);
return d;
}
data load_data_compare(int n, char **paths, int m, int classes, int w, int h)
{
if(m) paths = get_random_paths(paths, 2*n, m);
int i,j;
data d = {0};
d.shallow = 0;
d.X.rows = n;
d.X.vals = calloc(d.X.rows, sizeof(float*));
d.X.cols = h*w*6;
int k = 2*(classes);
d.y = make_matrix(n, k);
for(i = 0; i < n; ++i){
image im1 = load_image_color(paths[i*2], w, h);
image im2 = load_image_color(paths[i*2+1], w, h);
d.X.vals[i] = calloc(d.X.cols, sizeof(float));
memcpy(d.X.vals[i], im1.data, h*w*3*sizeof(float));
memcpy(d.X.vals[i] + h*w*3, im2.data, h*w*3*sizeof(float));
int id;
float iou;
char imlabel1[4096];
char imlabel2[4096];
find_replace(paths[i*2], "imgs", "labels", imlabel1);
find_replace(imlabel1, "jpg", "txt", imlabel1);
FILE *fp1 = fopen(imlabel1, "r");
while(fscanf(fp1, "%d %f", &id, &iou) == 2){
if (d.y.vals[i][2*id] < iou) d.y.vals[i][2*id] = iou;
}
find_replace(paths[i*2+1], "imgs", "labels", imlabel2);
find_replace(imlabel2, "jpg", "txt", imlabel2);
FILE *fp2 = fopen(imlabel2, "r");
while(fscanf(fp2, "%d %f", &id, &iou) == 2){
if (d.y.vals[i][2*id + 1] < iou) d.y.vals[i][2*id + 1] = iou;
}
for (j = 0; j < classes; ++j){
if (d.y.vals[i][2*j] > .5 && d.y.vals[i][2*j+1] < .5){
d.y.vals[i][2*j] = 1;
d.y.vals[i][2*j+1] = 0;
} else if (d.y.vals[i][2*j] < .5 && d.y.vals[i][2*j+1] > .5){
d.y.vals[i][2*j] = 0;
d.y.vals[i][2*j+1] = 1;
} else {
d.y.vals[i][2*j] = SECRET_NUM;
d.y.vals[i][2*j+1] = SECRET_NUM;
}
}
fclose(fp1);
fclose(fp2);
free_image(im1);
free_image(im2);
}
if(m) free(paths);
return d;
}
data load_data_swag(char **paths, int n, int classes, float jitter)
{
int index = rand()%n;
char *random_path = paths[index];
image orig = load_image_color(random_path, 0, 0);
int h = orig.h;
int w = orig.w;
data d = {0};
d.shallow = 0;
d.w = w;
d.h = h;
d.X.rows = 1;
d.X.vals = calloc(d.X.rows, sizeof(float*));
d.X.cols = h*w*3;
int k = (4+classes)*90;
d.y = make_matrix(1, k);
int dw = w*jitter;
int dh = h*jitter;
int pleft = rand_uniform(-dw, dw);
int pright = rand_uniform(-dw, dw);
int ptop = rand_uniform(-dh, dh);
int pbot = rand_uniform(-dh, dh);
int swidth = w - pleft - pright;
int sheight = h - ptop - pbot;
float sx = (float)swidth / w;
float sy = (float)sheight / h;
int flip = rand()%2;
image cropped = crop_image(orig, pleft, ptop, swidth, sheight);
float dx = ((float)pleft/w)/sx;
float dy = ((float)ptop /h)/sy;
image sized = resize_image(cropped, w, h);
if(flip) flip_image(sized);
d.X.vals[0] = sized.data;
fill_truth_swag(random_path, d.y.vals[0], classes, flip, dx, dy, 1./sx, 1./sy);
free_image(orig);
free_image(cropped);
return d;
}
data load_data_detection(int n, char **paths, int m, int w, int h, int boxes, int classes, float jitter, float hue, float saturation, float exposure)
{
char **random_paths = get_random_paths(paths, n, m);
int i;
data d = {0};
d.shallow = 0;
d.X.rows = n;
d.X.vals = calloc(d.X.rows, sizeof(float*));
d.X.cols = h*w*3;
d.y = make_matrix(n, 5*boxes);
for(i = 0; i < n; ++i){
image orig = load_image_color(random_paths[i], 0, 0);
image sized = make_image(w, h, orig.c);
fill_image(sized, .5);
float dw = jitter * orig.w;
float dh = jitter * orig.h;
float new_ar = (orig.w + rand_uniform(-dw, dw)) / (orig.h + rand_uniform(-dh, dh));
float scale = rand_uniform(.25, 2);
float nw, nh;
if(new_ar < 1){
nh = scale * h;
nw = nh * new_ar;
} else {
nw = scale * w;
nh = nw / new_ar;
}
float dx = rand_uniform(0, w - nw);
float dy = rand_uniform(0, h - nh);
place_image(orig, nw, nh, dx, dy, sized);
random_distort_image(sized, hue, saturation, exposure);
int flip = rand()%2;
if(flip) flip_image(sized);
d.X.vals[i] = sized.data;
fill_truth_detection(random_paths[i], boxes, d.y.vals[i], classes, flip, -dx/w, -dy/h, nw/w, nh/h);
free_image(orig);
}
free(random_paths);
return d;
}
void *load_thread(void *ptr)
{
//printf("Loading data: %d\n", rand());
load_args a = *(struct load_args*)ptr;
if(a.exposure == 0) a.exposure = 1;
if(a.saturation == 0) a.saturation = 1;
if(a.aspect == 0) a.aspect = 1;
if (a.type == OLD_CLASSIFICATION_DATA){
*a.d = load_data_old(a.paths, a.n, a.m, a.labels, a.classes, a.w, a.h);
} else if (a.type == REGRESSION_DATA){
*a.d = load_data_regression(a.paths, a.n, a.m, a.classes, a.min, a.max, a.size, a.angle, a.aspect, a.hue, a.saturation, a.exposure);
} else if (a.type == CLASSIFICATION_DATA){
*a.d = load_data_augment(a.paths, a.n, a.m, a.labels, a.classes, a.hierarchy, a.min, a.max, a.size, a.angle, a.aspect, a.hue, a.saturation, a.exposure, a.center);
} else if (a.type == SUPER_DATA){
*a.d = load_data_super(a.paths, a.n, a.m, a.w, a.h, a.scale);
} else if (a.type == WRITING_DATA){
*a.d = load_data_writing(a.paths, a.n, a.m, a.w, a.h, a.out_w, a.out_h);
} else if (a.type == INSTANCE_DATA){
*a.d = load_data_iseg(a.n, a.paths, a.m, a.w, a.h, a.classes, a.num_boxes, a.coords, a.min, a.max, a.angle, a.aspect, a.hue, a.saturation, a.exposure);
} else if (a.type == SEGMENTATION_DATA){
*a.d = load_data_seg(a.n, a.paths, a.m, a.w, a.h, a.classes, a.min, a.max, a.angle, a.aspect, a.hue, a.saturation, a.exposure, a.scale);
} else if (a.type == REGION_DATA){
*a.d = load_data_region(a.n, a.paths, a.m, a.w, a.h, a.num_boxes, a.classes, a.jitter, a.hue, a.saturation, a.exposure);
} else if (a.type == DETECTION_DATA){
*a.d = load_data_detection(a.n, a.paths, a.m, a.w, a.h, a.num_boxes, a.classes, a.jitter, a.hue, a.saturation, a.exposure);
} else if (a.type == SWAG_DATA){
*a.d = load_data_swag(a.paths, a.n, a.classes, a.jitter);
} else if (a.type == COMPARE_DATA){
*a.d = load_data_compare(a.n, a.paths, a.m, a.classes, a.w, a.h);
} else if (a.type == IMAGE_DATA){
*(a.im) = load_image_color(a.path, 0, 0);
*(a.resized) = resize_image(*(a.im), a.w, a.h);
} else if (a.type == LETTERBOX_DATA){
*(a.im) = load_image_color(a.path, 0, 0);
*(a.resized) = letterbox_image(*(a.im), a.w, a.h);
} else if (a.type == TAG_DATA){
*a.d = load_data_tag(a.paths, a.n, a.m, a.classes, a.min, a.max, a.size, a.angle, a.aspect, a.hue, a.saturation, a.exposure);
}
free(ptr);
return 0;
}
pthread_t load_data_in_thread(load_args args)
{
pthread_t thread;
struct load_args *ptr = calloc(1, sizeof(struct load_args));
*ptr = args;
if(pthread_create(&thread, 0, load_thread, ptr)) error("Thread creation failed");
return thread;
}
void *load_threads(void *ptr)
{
int i;
load_args args = *(load_args *)ptr;
if (args.threads == 0) args.threads = 1;
data *out = args.d;
int total = args.n;
free(ptr);
data *buffers = calloc(args.threads, sizeof(data));
pthread_t *threads = calloc(args.threads, sizeof(pthread_t));
for(i = 0; i < args.threads; ++i){
args.d = buffers + i;
args.n = (i+1) * total/args.threads - i * total/args.threads;
threads[i] = load_data_in_thread(args);
}
for(i = 0; i < args.threads; ++i){
pthread_join(threads[i], 0);
}
*out = concat_datas(buffers, args.threads);
out->shallow = 0;
for(i = 0; i < args.threads; ++i){
buffers[i].shallow = 1;
free_data(buffers[i]);
}
free(buffers);
free(threads);
return 0;
}
void load_data_blocking(load_args args)
{
struct load_args *ptr = calloc(1, sizeof(struct load_args));
*ptr = args;
load_thread(ptr);
}
pthread_t load_data(load_args args)
{
pthread_t thread;
struct load_args *ptr = calloc(1, sizeof(struct load_args));
*ptr = args;
if(pthread_create(&thread, 0, load_threads, ptr)) error("Thread creation failed");
return thread;
}
data load_data_writing(char **paths, int n, int m, int w, int h, int out_w, int out_h)
{
if(m) paths = get_random_paths(paths, n, m);
char **replace_paths = find_replace_paths(paths, n, ".png", "-label.png");
data d = {0};
d.shallow = 0;
d.X = load_image_paths(paths, n, w, h);
d.y = load_image_paths_gray(replace_paths, n, out_w, out_h);
if(m) free(paths);
int i;
for(i = 0; i < n; ++i) free(replace_paths[i]);
free(replace_paths);
return d;
}
data load_data_old(char **paths, int n, int m, char **labels, int k, int w, int h)
{
if(m) paths = get_random_paths(paths, n, m);
data d = {0};
d.shallow = 0;
d.X = load_image_paths(paths, n, w, h);
d.y = load_labels_paths(paths, n, labels, k, 0);
if(m) free(paths);
return d;
}
/*
data load_data_study(char **paths, int n, int m, char **labels, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure)
{
data d = {0};
d.indexes = calloc(n, sizeof(int));
if(m) paths = get_random_paths_indexes(paths, n, m, d.indexes);
d.shallow = 0;
d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure);
d.y = load_labels_paths(paths, n, labels, k);
if(m) free(paths);
return d;
}
*/
data load_data_super(char **paths, int n, int m, int w, int h, int scale)
{
if(m) paths = get_random_paths(paths, n, m);
data d = {0};
d.shallow = 0;
int i;
d.X.rows = n;
d.X.vals = calloc(n, sizeof(float*));
d.X.cols = w*h*3;
d.y.rows = n;
d.y.vals = calloc(n, sizeof(float*));
d.y.cols = w*scale * h*scale * 3;
for(i = 0; i < n; ++i){
image im = load_image_color(paths[i], 0, 0);
image crop = random_crop_image(im, w*scale, h*scale);
int flip = rand()%2;
if (flip) flip_image(crop);
image resize = resize_image(crop, w, h);
d.X.vals[i] = resize.data;
d.y.vals[i] = crop.data;
free_image(im);
}
if(m) free(paths);
return d;
}
data load_data_regression(char **paths, int n, int m, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure)
{
if(m) paths = get_random_paths(paths, n, m);
data d = {0};
d.shallow = 0;
d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure, 0);
d.y = load_regression_labels_paths(paths, n, k);
if(m) free(paths);
return d;
}
data select_data(data *orig, int *inds)
{
data d = {0};
d.shallow = 1;
d.w = orig[0].w;
d.h = orig[0].h;
d.X.rows = orig[0].X.rows;
d.y.rows = orig[0].X.rows;
d.X.cols = orig[0].X.cols;
d.y.cols = orig[0].y.cols;
d.X.vals = calloc(orig[0].X.rows, sizeof(float *));
d.y.vals = calloc(orig[0].y.rows, sizeof(float *));
int i;
for(i = 0; i < d.X.rows; ++i){
d.X.vals[i] = orig[inds[i]].X.vals[i];
d.y.vals[i] = orig[inds[i]].y.vals[i];
}
return d;
}
data *tile_data(data orig, int divs, int size)
{
data *ds = calloc(divs*divs, sizeof(data));
int i, j;
#pragma omp parallel for
for(i = 0; i < divs*divs; ++i){
data d;
d.shallow = 0;
d.w = orig.w/divs * size;
d.h = orig.h/divs * size;
d.X.rows = orig.X.rows;
d.X.cols = d.w*d.h*3;
d.X.vals = calloc(d.X.rows, sizeof(float*));
d.y = copy_matrix(orig.y);
#pragma omp parallel for
for(j = 0; j < orig.X.rows; ++j){
int x = (i%divs) * orig.w / divs - (d.w - orig.w/divs)/2;
int y = (i/divs) * orig.h / divs - (d.h - orig.h/divs)/2;
image im = float_to_image(orig.w, orig.h, 3, orig.X.vals[j]);
d.X.vals[j] = crop_image(im, x, y, d.w, d.h).data;
}
ds[i] = d;
}
return ds;
}
data resize_data(data orig, int w, int h)
{
data d = {0};
d.shallow = 0;
d.w = w;
d.h = h;
int i;
d.X.rows = orig.X.rows;
d.X.cols = w*h*3;
d.X.vals = calloc(d.X.rows, sizeof(float*));
d.y = copy_matrix(orig.y);
#pragma omp parallel for
for(i = 0; i < orig.X.rows; ++i){
image im = float_to_image(orig.w, orig.h, 3, orig.X.vals[i]);
d.X.vals[i] = resize_image(im, w, h).data;
}
return d;
}
data load_data_augment(char **paths, int n, int m, char **labels, int k, tree *hierarchy, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure, int center)
{
if(m) paths = get_random_paths(paths, n, m);
data d = {0};
d.shallow = 0;
d.w=size;
d.h=size;
d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure, center);
d.y = load_labels_paths(paths, n, labels, k, hierarchy);
if(m) free(paths);
return d;
}
data load_data_tag(char **paths, int n, int m, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure)
{
if(m) paths = get_random_paths(paths, n, m);
data d = {0};
d.w = size;
d.h = size;
d.shallow = 0;
d.X = load_image_augment_paths(paths, n, min, max, size, angle, aspect, hue, saturation, exposure, 0);
d.y = load_tags_paths(paths, n, k);
if(m) free(paths);
return d;
}
matrix concat_matrix(matrix m1, matrix m2)
{
int i, count = 0;
matrix m;
m.cols = m1.cols;
m.rows = m1.rows+m2.rows;
m.vals = calloc(m1.rows + m2.rows, sizeof(float*));
for(i = 0; i < m1.rows; ++i){
m.vals[count++] = m1.vals[i];
}
for(i = 0; i < m2.rows; ++i){
m.vals[count++] = m2.vals[i];
}
return m;
}
data concat_data(data d1, data d2)
{
data d = {0};
d.shallow = 1;
d.X = concat_matrix(d1.X, d2.X);
d.y = concat_matrix(d1.y, d2.y);
d.w = d1.w;
d.h = d1.h;
return d;
}
data concat_datas(data *d, int n)
{
int i;
data out = {0};
for(i = 0; i < n; ++i){
data new = concat_data(d[i], out);
free_data(out);
out = new;
}
return out;
}
data load_categorical_data_csv(char *filename, int target, int k)
{
data d = {0};
d.shallow = 0;
matrix X = csv_to_matrix(filename);
float *truth_1d = pop_column(&X, target);
float **truth = one_hot_encode(truth_1d, X.rows, k);
matrix y;
y.rows = X.rows;
y.cols = k;
y.vals = truth;
d.X = X;
d.y = y;
free(truth_1d);
return d;
}
data load_cifar10_data(char *filename)
{
data d = {0};
d.shallow = 0;
long i,j;
matrix X = make_matrix(10000, 3072);
matrix y = make_matrix(10000, 10);
d.X = X;
d.y = y;
FILE *fp = fopen(filename, "rb");
if(!fp) file_error(filename);
for(i = 0; i < 10000; ++i){
unsigned char bytes[3073];
fread(bytes, 1, 3073, fp);
int class = bytes[0];
y.vals[i][class] = 1;
for(j = 0; j < X.cols; ++j){
X.vals[i][j] = (double)bytes[j+1];
}
}
scale_data_rows(d, 1./255);
//normalize_data_rows(d);
fclose(fp);
return d;
}
void get_random_batch(data d, int n, float *X, float *y)
{
int j;
for(j = 0; j < n; ++j){
int index = rand()%d.X.rows;
memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float));
memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float));
}
}
void get_next_batch(data d, int n, int offset, float *X, float *y)
{
int j;
for(j = 0; j < n; ++j){
int index = offset + j;
memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float));
if(y) memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float));
}
}
void smooth_data(data d)
{
int i, j;
float scale = 1. / d.y.cols;
float eps = .1;
for(i = 0; i < d.y.rows; ++i){
for(j = 0; j < d.y.cols; ++j){
d.y.vals[i][j] = eps * scale + (1-eps) * d.y.vals[i][j];
}
}
}
data load_all_cifar10()
{
data d = {0};
d.shallow = 0;
int i,j,b;
matrix X = make_matrix(50000, 3072);
matrix y = make_matrix(50000, 10);
d.X = X;
d.y = y;
for(b = 0; b < 5; ++b){
char buff[256];
sprintf(buff, "data/cifar/cifar-10-batches-bin/data_batch_%d.bin", b+1);
FILE *fp = fopen(buff, "rb");
if(!fp) file_error(buff);
for(i = 0; i < 10000; ++i){
unsigned char bytes[3073];
fread(bytes, 1, 3073, fp);
int class = bytes[0];
y.vals[i+b*10000][class] = 1;
for(j = 0; j < X.cols; ++j){
X.vals[i+b*10000][j] = (double)bytes[j+1];
}
}
fclose(fp);
}
//normalize_data_rows(d);
scale_data_rows(d, 1./255);
smooth_data(d);
return d;
}
data load_go(char *filename)
{
FILE *fp = fopen(filename, "rb");
matrix X = make_matrix(3363059, 361);
matrix y = make_matrix(3363059, 361);
int row, col;
if(!fp) file_error(filename);
char *label;
int count = 0;
while((label = fgetl(fp))){
int i;
if(count == X.rows){
X = resize_matrix(X, count*2);
y = resize_matrix(y, count*2);
}
sscanf(label, "%d %d", &row, &col);
char *board = fgetl(fp);
int index = row*19 + col;
y.vals[count][index] = 1;
for(i = 0; i < 19*19; ++i){
float val = 0;
if(board[i] == '1') val = 1;
else if(board[i] == '2') val = -1;
X.vals[count][i] = val;
}
++count;
free(label);
free(board);
}
X = resize_matrix(X, count);
y = resize_matrix(y, count);
data d = {0};
d.shallow = 0;
d.X = X;
d.y = y;
fclose(fp);
return d;
}
void randomize_data(data d)
{
int i;
for(i = d.X.rows-1; i > 0; --i){
int index = rand()%i;
float *swap = d.X.vals[index];
d.X.vals[index] = d.X.vals[i];
d.X.vals[i] = swap;
swap = d.y.vals[index];
d.y.vals[index] = d.y.vals[i];
d.y.vals[i] = swap;
}
}
void scale_data_rows(data d, float s)
{
int i;
for(i = 0; i < d.X.rows; ++i){
scale_array(d.X.vals[i], d.X.cols, s);
}
}
void translate_data_rows(data d, float s)
{
int i;
for(i = 0; i < d.X.rows; ++i){
translate_array(d.X.vals[i], d.X.cols, s);
}
}
data copy_data(data d)
{
data c = {0};
c.w = d.w;
c.h = d.h;
c.shallow = 0;
c.num_boxes = d.num_boxes;
c.boxes = d.boxes;
c.X = copy_matrix(d.X);
c.y = copy_matrix(d.y);
return c;
}
void normalize_data_rows(data d)
{
int i;
for(i = 0; i < d.X.rows; ++i){
normalize_array(d.X.vals[i], d.X.cols);
}
}
data get_data_part(data d, int part, int total)
{
data p = {0};
p.shallow = 1;
p.X.rows = d.X.rows * (part + 1) / total - d.X.rows * part / total;
p.y.rows = d.y.rows * (part + 1) / total - d.y.rows * part / total;
p.X.cols = d.X.cols;
p.y.cols = d.y.cols;
p.X.vals = d.X.vals + d.X.rows * part / total;
p.y.vals = d.y.vals + d.y.rows * part / total;
return p;
}
data get_random_data(data d, int num)
{
data r = {0};
r.shallow = 1;
r.X.rows = num;
r.y.rows = num;
r.X.cols = d.X.cols;
r.y.cols = d.y.cols;
r.X.vals = calloc(num, sizeof(float *));
r.y.vals = calloc(num, sizeof(float *));
int i;
for(i = 0; i < num; ++i){
int index = rand()%d.X.rows;
r.X.vals[i] = d.X.vals[index];
r.y.vals[i] = d.y.vals[index];
}
return r;
}
data *split_data(data d, int part, int total)
{
data *split = calloc(2, sizeof(data));
int i;
int start = part*d.X.rows/total;
int end = (part+1)*d.X.rows/total;
data train;
data test;
train.shallow = test.shallow = 1;
test.X.rows = test.y.rows = end-start;
train.X.rows = train.y.rows = d.X.rows - (end-start);
train.X.cols = test.X.cols = d.X.cols;
train.y.cols = test.y.cols = d.y.cols;
train.X.vals = calloc(train.X.rows, sizeof(float*));
test.X.vals = calloc(test.X.rows, sizeof(float*));
train.y.vals = calloc(train.y.rows, sizeof(float*));
test.y.vals = calloc(test.y.rows, sizeof(float*));
for(i = 0; i < start; ++i){
train.X.vals[i] = d.X.vals[i];
train.y.vals[i] = d.y.vals[i];
}
for(i = start; i < end; ++i){
test.X.vals[i-start] = d.X.vals[i];
test.y.vals[i-start] = d.y.vals[i];
}
for(i = end; i < d.X.rows; ++i){
train.X.vals[i-(end-start)] = d.X.vals[i];
train.y.vals[i-(end-start)] = d.y.vals[i];
}
split[0] = train;
split[1] = test;
return split;
}
|
test.c |
#include <stdio.h>
#include <omp.h>
#include "../utilities/check.h"
#include "../utilities/utilities.h"
#define TRIALS (1)
#define N (992)
#define INIT() INIT_LOOP(N, {C[i] = 1; D[i] = i; E[i] = -i;})
#define ZERO(X) ZERO_ARRAY(N, X)
int check_results(double* A){
for (int i = 0 ; i < N ; i++){
if (A[i] != TRIALS){
printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]);
return 0;
}
}
return 1;
}
int check_results_priv(double *A, double *B){
for(int i = 0 ; i < N ; i++) {
if (A[i] != TRIALS*3) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) TRIALS*2, A[i]);
return 0;
}
if (B[i] != TRIALS*7) {
printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) TRIALS*3, B[i]);
return 0;
}
}
return 1;
}
#define CODE() \
ZERO(A); \
success = 0; \
for (int t = 0 ; t < TRIALS ; t++) { \
_Pragma("omp target teams distribute simd CLAUSES") \
for (int i = 0 ; i < N ; i++){ \
A[i] += C[i]; \
} \
} \
success += check_results(A); \
if (success == expected) \
printf("Succeeded\n");
#define CODE_PRIV() \
ZERO(A); \
ZERO(B); \
p = 2.0; \
q = 4.0; \
success = 0; \
for (int t = 0 ; t < TRIALS ; t++) { \
_Pragma("omp target teams distribute simd CLAUSES") \
for (int i = 0 ; i < N ; i++){ \
p = 3; \
q = 7; \
A[i] += p; \
B[i] += q; \
} \
} \
success += check_results_priv(A, B); \
if (success == expected) \
printf("Succeeded\n");
int main(void) {
check_offloading();
double A[N], B[N], C[N], D[N], E[N];
int fail = 0;
int expected = 1;
int success = 0;
int chunkSize;
double p = 2.0, q = 4.0;
int nte, tl, blockSize;
INIT();
// **************************
// Series 1: no dist_schedule
// **************************
//
// Test: #iterations == #teams
//
printf("iterations = teams\n");
#define CLAUSES num_teams(992)
CODE()
#undef CLAUSES
printf("iterations > teams\n");
#define CLAUSES num_teams(256)
CODE()
#undef CLAUSES
printf("iterations < teams\n");
#define CLAUSES num_teams(1024)
CODE()
#undef CLAUSES
printf("num_teams(512) dist_schedule(static,1)\n");
#define CLAUSES num_teams(512) dist_schedule(static, 1)
CODE()
#undef CLAUSES
printf("num_teams(512) dist_schedule(static,512)\n");
#define CLAUSES num_teams(512) dist_schedule(static, 512)
CODE()
#undef CLAUSES
printf("num_teams(512) dist_schedule(static, chunkSize)\n");
chunkSize = N / 10;
#define CLAUSES num_teams(512) dist_schedule(static, chunkSize)
CODE()
#undef CLAUSES
printf("num_teams(1024) dist_schedule(static, chunkSize)\n");
chunkSize = N / 10;
#define CLAUSES num_teams(1024) dist_schedule(static, chunkSize)
CODE()
#undef CLAUSES
printf("num_teams(1024) dist_schedule(static, 1)\n");
#define CLAUSES num_teams(1024) dist_schedule(static, 1)
CODE()
#undef CLAUSES
printf("num_teams(3) dist_schedule(static, 1)\n");
#define CLAUSES num_teams(3) dist_schedule(static, 1)
CODE()
#undef CLAUSES
printf("num_teams(3) dist_schedule(static, 3)\n");
#define CLAUSES num_teams(3) dist_schedule(static, 3)
CODE()
#undef CLAUSES
printf("num_teams(10) dist_schedule(static, 99)\n");
#define CLAUSES num_teams(10) dist_schedule(static, 99)
CODE()
#undef CLAUSES
printf("num_teams(256) dist_schedule(static, 992)\n");
#define CLAUSES num_teams(256) dist_schedule(static, 992)
CODE()
#undef CLAUSES
#if 0
printf("num_teams(256) private(p,q)\n");
#define CLAUSES num_teams(256) private(p,q)
CODE_PRIV()
#undef CLAUSES
#endif
//
// Test: firstprivate
//
#if 0
printf("num_teams(64) firstprivate(p, q)\n");
ZERO(A); ZERO(B);
p = 2.0, q = 4.0;
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target // implicit firstprivate for p and q, their initial values being 2 and 4 for each target invocation
#pragma omp teams distribute num_teams(64) firstprivate(p, q)
for(int i = 0 ; i < 128 ; i++) { // 2 iterations for each team
p += 3.0; // p and q are firstprivate to the team, and as such incremented twice (2 iterations per team)
q += 7.0;
A[i] += p;
B[i] += q;
}
}
for(int i = 0 ; i < 128 ; i++) {
if (i % 2 == 0) {
if (A[i] != (2.0+3.0)*TRIALS) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]);
fail = 1;
}
if (B[i] != (4.0+7.0)*TRIALS) {
printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) (4.0+7.0)*TRIALS, B[i]);
fail = 1;
}
} else {
if (A[i] != (2.0+3.0*2)*TRIALS) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0*2)*TRIALS, A[i]);
fail = 1;
}
if (B[i] != (4.0+7.0*2)*TRIALS) {
printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) (4.0+7.0*2)*TRIALS, B[i]);
fail = 1;
}
}
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
#endif
//
// Test: lastprivate
//
#if 0
printf("num_teams(10) lastprivate(lastpriv)\n");
success = 0;
int lastpriv = -1;
#pragma omp target data map(tofrom:lastpriv)
#pragma omp target teams distribute simd num_teams(10) lastprivate(lastpriv)
for(int i = 0 ; i < omp_get_num_teams() ; i++)
lastpriv = omp_get_team_num();
if(lastpriv != 9) {
printf("lastpriv value is %d and should have been %d\n", lastpriv, 9);
fail = 1;
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
#endif
// // ***************************
// // Series 4: with parallel for
// // ***************************
//
// Test: simple blocking loop
//
printf("num_teams(nte) thread_limit(tl) with parallel for innermost\n");
success = 0;
ZERO(A); ZERO(B);
nte = 32;
tl = 64;
blockSize = tl;
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target teams distribute simd num_teams(nte) thread_limit(tl)
for(int j = 0 ; j < 256 ; j += blockSize) {
for(int i = j ; i < j+blockSize; i++) {
A[i] += B[i] + C[i];
}
}
}
for(int i = 0 ; i < 256 ; i++) {
if (A[i] != TRIALS) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]);
fail = 1;
}
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
//
// Test: blocking loop where upper bound is not a multiple of tl*nte
//
printf("num_teams(nte) thread_limit(tl) with parallel for innermost\n");
success = 0;
ZERO(A); ZERO(B);
nte = 32;
tl = 64;
blockSize = tl;
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target teams distribute simd num_teams(nte) thread_limit(tl)
for(int j = 0 ; j < 510 ; j += blockSize) {
int ub = (j+blockSize < 510) ? (j+blockSize) : 512;
for(int i = j ; i < ub; i++) {
A[i] += B[i] + C[i];
}
}
}
for(int i = 0 ; i < 256 ; i++) {
if (A[i] != TRIALS) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]);
fail = 1;
}
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
// **************************
// Series 5: collapse
// **************************
//
// Test: 2 loops
//
printf("num_teams(512) collapse(2)\n");
success = 0;
double * S = (double *) malloc(N*N*sizeof(double));
double * T = (double *) malloc(N*N*sizeof(double));
double * U = (double *) malloc(N*N*sizeof(double));
for (int i = 0 ; i < N ; i++)
for (int j = 0 ; j < N ; j++)
{
S[i*N+j] = 0.0;
T[i*N+j] = 1.0;
U[i*N+j] = 2.0;
}
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target data map(tofrom:S[:N*N]), map(to:T[:N*N],U[:N*N])
#pragma omp target teams distribute simd num_teams(512) collapse(2)
for (int i = 0 ; i < N ; i++)
for (int j = 0 ; j < N ; j++)
S[i*N+j] += T[i*N+j] + U[i*N+j]; // += 3 at each t
}
for (int i = 0 ; i < N ; i++)
for (int j = 0 ; j < N ; j++)
if (S[i*N+j] != TRIALS*3.0) {
printf("Error at (%d,%d), h = %lf, d = %lf\n", i, j, (double) TRIALS*3.0, S[i*N+j]);
fail = 1;
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
//
// Test: 3 loops
//
printf("num_teams(512) collapse(3)\n");
success = 0;
int M = N/8;
double * V = (double *) malloc(M*M*M*sizeof(double));
double * Z = (double *) malloc(M*M*M*sizeof(double));
for (int i = 0 ; i < M ; i++)
for (int j = 0 ; j < M ; j++)
for (int k = 0 ; k < M ; k++)
{
V[i*M*M+j*M+k] = 2.0;
Z[i*M*M+j*M+k] = 3.0;
}
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target data map(tofrom:V[:M*M*M]), map(to:Z[:M*M*M])
#pragma omp target teams distribute simd num_teams(512) collapse(3)
for (int i = 0 ; i < M ; i++)
for (int j = 0 ; j < M ; j++)
for (int k = 0 ; k < M ; k++)
V[i*M*M+j*M+k] += Z[i*M*M+j*M+k]; // += 3 at each t
}
for (int i = 0 ; i < M ; i++)
for (int j = 0 ; j < M ; j++)
for (int k = 0 ; k < M ; k++)
if (V[i*M*M+j*M+k] != 2.0+TRIALS*3.0) {
printf("Error at (%d,%d), h = %lf, d = %lf\n", i, j, (double) TRIALS*3.0, V[i*M*M+j*M+k]);
fail = 1;
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
return 0;
}
|
trsm_x_csc_n_lo_row.c | #include "alphasparse/opt.h"
#include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include <memory.h>
alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSC *A, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, ALPHA_Number *y, const ALPHA_INT ldy)
{
const ALPHA_INT m = A->rows;
const ALPHA_INT n = A->cols;
ALPHA_Number* diag=(ALPHA_Number*) alpha_malloc(n*sizeof(ALPHA_Number));
memset(diag, '\0', m * sizeof(ALPHA_Number));
ALPHA_INT num_thread = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for (ALPHA_INT c = 0; c < n; c++)
{
for (ALPHA_INT ai = A->cols_start[c]; ai < A->cols_end[c]; ai++)
{
ALPHA_INT ar = A->row_indx[ai];
if (ar == c)
{
diag[c] = A->values[ai];
}
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
//initialize y as x*alpha
for(int i = 0 ; i < m;i++){
for(int j = 0 ; j < columns ; j++){
//initialize y[] as x[]*aplha
alpha_mul(y[index2(i,j,ldy)], x[index2(i,j,ldx)] ,alpha);
}
}
//csc format, traverse by column
for(ALPHA_INT c = 0; c < n;++c){
//following processing simulates Gaussian Elimination
//step 1: processing the lower right diagonal ele such that the coefficient equals to 1
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for(ALPHA_INT out_y_col = 0; out_y_col < columns;out_y_col++){
alpha_div( y[index2(c,out_y_col,ldy)] , y[index2(c,out_y_col,ldy)] ,diag[c]);
}
for(ALPHA_INT ai = A->cols_start[c]; ai < A->cols_end[c];ai++){
ALPHA_INT ar = A->row_indx[ai];
if(c < ar){
//step 2: use the diagonal ele to eliminate coefficients of other rows at the same column
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_thread)
#endif
for(ALPHA_INT out_y_col = 0; out_y_col < columns;out_y_col++){
alpha_msube(y[index2(ar,out_y_col,ldy)],A->values[ai],y[index2(c,out_y_col,ldy)]);
}
}
}
}
alpha_free(diag);
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
disfuncs.c | /******************************************************************************
* Copyright (c) 2015 - 2016 Philipp Schubert. *
* All rights reserved. This program and the accompanying materials are made *
* available under the terms of LICENSE.txt. *
* *
* Contributors: *
* Philipp Schubert *
*****************************************************************************/
/** @file disfuncs.c
* @brief Implementation der Prototypen aus disfuncs.h.
*
* In dieser Datei sind die Funktionen zur Berechnung der Unähnlichkeitsmatrix
* Delta, sowie die zur Berechnung einer (euklidischen) Distanzmatrix (ohne
* eigenes Speichermanagment).
*
* @author Philipp D. Schubert
* @bug Keine Bugs bekannt.
*/
#include "disfuncs.h"
#include "m.h"
#include "tm.h"
#include "utils.h"
#include <omp.h>
#include <stdlib.h>
#include <string.h>
tm_t *calcDeltaMatrix(const m_t *data, const enum delta d, const int p) {
tm_t *delta = initTM(data->rows);
unsigned int i, j;
switch (d) {
case EUCLIDEAN:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
euclidean(&data->elems[i * data->cols],
&data->elems[j * data->cols], data->cols);
}
}
break;
case CITYBLOCK:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
cityblock(&data->elems[i * data->cols],
&data->elems[j * data->cols], data->cols);
}
}
break;
case MINKOWSKI:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
minkowski(&data->elems[i * data->cols],
&data->elems[j * data->cols], p, data->cols);
}
}
break;
case CANBERRA:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
canberra(&data->elems[i * data->cols], &data->elems[j * data->cols],
data->cols);
}
}
break;
case DIVERGENCE:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
divergence(&data->elems[i * data->cols],
&data->elems[j * data->cols], data->cols);
}
}
break;
case BRAYCURTIS:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
braycurtis(&data->elems[i * data->cols],
&data->elems[j * data->cols], data->cols);
}
}
break;
case SOERGEL:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
soergel(&data->elems[i * data->cols], &data->elems[j * data->cols],
data->cols);
}
}
break;
case BAHATTACHARYYA:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
bahattacharyya(&data->elems[i * data->cols],
&data->elems[j * data->cols], data->cols);
}
}
break;
case WAVEHEDGES:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
wavehedges(&data->elems[i * data->cols],
&data->elems[j * data->cols], data->cols);
}
}
break;
case ANGULARSEPERATION:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
angularseperation(&data->elems[i * data->cols],
&data->elems[j * data->cols], data->cols);
}
}
break;
case CORRELATION:
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j < i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] =
correlation(&data->elems[i * data->cols],
&data->elems[j * data->cols], data->cols);
}
}
break;
case NONE:
CERROR(data->rows != data->cols, "input is no valid dissimilarity matrix");
#pragma omp parallel for shared(delta) private(i, j) schedule(dynamic)
for (i = 0; i < data->rows; ++i) {
for (j = 0; j <= i; ++j) {
delta->elems[(i * (i + 1)) / 2 + j] = data->elems[i * data->cols + j];
}
}
break;
default:
perror("unsupported measure of DELTA");
HEREANDNOW;
exit(-1);
break;
}
return delta;
}
void calcDistanceMatrix_nomem(const m_t *x, tm_t *dx) {
unsigned int i, j;
#pragma omp parallel for shared(x, dx) private(i, j) schedule(dynamic)
for (i = 0; i < x->rows; ++i) {
for (j = 0; j < i; ++j) {
dx->elems[(i * (i + 1)) / 2 + j] =
euclidean(&x->elems[i * x->cols], &x->elems[j * x->cols], x->cols);
}
}
}
|
model_initializer.h | // -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & Newcastle University for the benefit of the
// BioDynaMo collaboration. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#ifndef CORE_MODEL_INITIALIZER_H_
#define CORE_MODEL_INITIALIZER_H_
#include <ctime>
#include <string>
#include <vector>
#include "core/container/math_array.h"
#include "core/diffusion/diffusion_grid.h"
#include "core/resource_manager.h"
#include "core/simulation.h"
#include "core/util/random.h"
class EulerGrid;
class StencilGrid;
class RungaKuttaGrid;
namespace bdm {
struct ModelInitializer {
/// Creates a 3D cubic grid of agents and adds them to the
/// ExecutionContext. Type of the agent is determined by the return
/// type of parameter agent_builder.
///
/// ModelInitializer::Grid3D(8, 10, [](const Double3& pos){
/// return Cell(pos); });
/// @param agents_per_dim number of agents on each axis.
/// Number of generated agents =
/// `agents_per_dim ^ 3`
/// @param space space between the positions - e.g space = 10:
/// positions = `{(0, 0, 0), (0, 0, 10), (0, 0,
/// 20), ... }`
/// @param agent_builder function containing the logic to instantiate a
/// new agent. Takes `const
/// Double3&` as input parameter
///
template <typename Function>
static void Grid3D(size_t agents_per_dim, double space,
Function agent_builder) {
#pragma omp parallel
{
auto* sim = Simulation::GetActive();
auto* ctxt = sim->GetExecutionContext();
#pragma omp for
for (size_t x = 0; x < agents_per_dim; x++) {
auto x_pos = x * space;
for (size_t y = 0; y < agents_per_dim; y++) {
auto y_pos = y * space;
for (size_t z = 0; z < agents_per_dim; z++) {
auto* new_agent = agent_builder({x_pos, y_pos, z * space});
ctxt->AddAgent(new_agent);
}
}
}
}
}
/// Creates a 3D grid of agents and adds them to the
/// ExecutionContext. Type of the agent is determined by the return
/// type of parameter agent_builder.
///
/// ModelInitializer::Grid3D({8,6,4}, 10, [](const Double3&
/// pos){ return Cell(pos); });
/// @param agents_per_dim number of agents on each axis.
/// Number of generated agents =
/// `agents_per_dim[0] * agents_per_dim[1] *
/// agents_per_dim[2]`
/// @param space space between the positions - e.g space = 10:
/// positions = `{(0, 0, 0), (0, 0, 10), (0, 0,
/// 20), ... }`
/// @param agent_builder function containing the logic to instantiate a
/// new agent. Takes `const
/// Double3&` as input parameter
///
template <typename Function>
static void Grid3D(const std::array<size_t, 3>& agents_per_dim, double space,
Function agent_builder) {
#pragma omp parallel
{
auto* sim = Simulation::GetActive();
auto* ctxt = sim->GetExecutionContext();
#pragma omp for
for (size_t x = 0; x < agents_per_dim[0]; x++) {
auto x_pos = x * space;
for (size_t y = 0; y < agents_per_dim[1]; y++) {
auto y_pos = y * space;
for (size_t z = 0; z < agents_per_dim[2]; z++) {
auto* new_agent = agent_builder({x_pos, y_pos, z * space});
ctxt->AddAgent(new_agent);
}
}
}
}
}
/// Adds agents to the ExecutionContext. Type of the simulation
/// object is determined by the return type of parameter agent_builder.
///
/// @param positions positions of the agents to be
/// @param agent_builder function containing the logic to instantiate a
/// new agent. Takes `const
/// Double3&` as input parameter
///
template <typename Function>
static void CreateAgents(const std::vector<Double3>& positions,
Function agent_builder) {
#pragma omp parallel
{
auto* sim = Simulation::GetActive();
auto* ctxt = sim->GetExecutionContext();
#pragma omp for
for (size_t i = 0; i < positions.size(); i++) {
auto* new_agent =
agent_builder({positions[i][0], positions[i][1], positions[i][2]});
ctxt->AddAgent(new_agent);
}
}
}
/// Adds agents with random positions to the ExecutionContext.
/// Type of the agent is determined by the return type of
/// parameter agent_builder.
///
/// @param[in] min The minimum position value
/// @param[in] max The maximum position value
/// @param[in] num_agents The number agents
/// @param[in] agent_builder function containing the logic to instantiate a
/// new agent. Takes `const
/// Double3&` as input parameter
///
template <typename Function>
static void CreateAgentsRandom(double min, double max, uint64_t num_agents,
Function agent_builder) {
#pragma omp parallel
{
auto* sim = Simulation::GetActive();
auto* ctxt = sim->GetExecutionContext();
auto* random = sim->GetRandom();
#pragma omp for
for (uint64_t i = 0; i < num_agents; i++) {
auto* new_agent = agent_builder(random->UniformArray<3>(min, max));
ctxt->AddAgent(new_agent);
}
}
}
/// Allows agents to secrete the specified substance. Diffusion throughout the
/// simulation space is automatically taken care of by the DiffusionGrid class
///
/// @param[in] substance_id The substance identifier
/// @param[in] substance_name The substance name
/// @param[in] diffusion_coeff The diffusion coefficient
/// @param[in] decay_constant The decay constant
/// @param[in] resolution The resolution of the diffusion grid
///
static void DefineSubstance(size_t substance_id, std::string substance_name,
double diffusion_coeff, double decay_constant,
int resolution = 10);
template <typename F>
static void InitializeSubstance(size_t substance_id, F function) {
auto* sim = Simulation::GetActive();
auto* rm = sim->GetResourceManager();
auto diffusion_grid = rm->GetDiffusionGrid(substance_id);
diffusion_grid->AddInitializer(function);
}
};
} // namespace bdm
#endif // CORE_MODEL_INITIALIZER_H_
|
convolution_3x3_pack4to1.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 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 conv3x3s1_winograd64_transform_kernel_pack4to1_neon(const Mat& kernel, Mat& kernel_tm_pack4, int inch, int outch)
{
// winograd63 transform kernel
Mat kernel_tm;
kernel_tm.create(8*8, inch, outch);
const float ktm[8][3] = {
{ 1.0f, 0.0f, 0.0f},
{-2.0f/9, -2.0f/9, -2.0f/9},
{-2.0f/9, 2.0f/9, -2.0f/9},
{1.0f/90, 1.0f/45, 2.0f/45},
{1.0f/90, -1.0f/45, 2.0f/45},
{1.0f/45, 1.0f/90, 1.0f/180},
{1.0f/45, -1.0f/90, 1.0f/180},
{ 0.0f, 0.0f, 1.0f}
};
#pragma omp parallel for
for (int p = 0; p<outch; p++)
{
for (int q = 0; q<inch; q++)
{
const float* kernel0 = (const float*)kernel + p*inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm.channel(p).row(q);
// transform kernel, transposed
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[8][3];
for (int i=0; i<8; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// v
for (int j=0; j<8; j++)
{
float* tmpp = &tmp[j][0];
for (int i=0; i<8; i++)
{
kernel_tm0[j*8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// interleave
// src = 64-inch-outch
// dst = 4a-inch/4a-64-outch;
#if __aarch64__
kernel_tm_pack4.create(8 * inch/4, 64, outch/8 + (outch%8)/4 + outch%4, (size_t)4u*4, 4);
#else
kernel_tm_pack4.create(4 * inch/4, 64, outch/4 + outch%4, (size_t)4u*4, 4);
#endif
int p=0;
#if __aarch64__
for (; p+7<outch; p+=8)
{
const Mat k0 = kernel_tm.channel(p);
const Mat k1 = kernel_tm.channel(p+1);
const Mat k2 = kernel_tm.channel(p+2);
const Mat k3 = kernel_tm.channel(p+3);
const Mat k4 = kernel_tm.channel(p+4);
const Mat k5 = kernel_tm.channel(p+5);
const Mat k6 = kernel_tm.channel(p+6);
const Mat k7 = kernel_tm.channel(p+7);
Mat g0 = kernel_tm_pack4.channel(p/8);
for (int k=0; k<64; k++)
{
float* g00 = g0.row(k);
for (int q=0; q+3<inch; q+=4)
{
const float* k00 = k0.row(q);
const float* k01 = k0.row(q+1);
const float* k02 = k0.row(q+2);
const float* k03 = k0.row(q+3);
const float* k10 = k1.row(q);
const float* k11 = k1.row(q+1);
const float* k12 = k1.row(q+2);
const float* k13 = k1.row(q+3);
const float* k20 = k2.row(q);
const float* k21 = k2.row(q+1);
const float* k22 = k2.row(q+2);
const float* k23 = k2.row(q+3);
const float* k30 = k3.row(q);
const float* k31 = k3.row(q+1);
const float* k32 = k3.row(q+2);
const float* k33 = k3.row(q+3);
const float* k40 = k4.row(q);
const float* k41 = k4.row(q+1);
const float* k42 = k4.row(q+2);
const float* k43 = k4.row(q+3);
const float* k50 = k5.row(q);
const float* k51 = k5.row(q+1);
const float* k52 = k5.row(q+2);
const float* k53 = k5.row(q+3);
const float* k60 = k6.row(q);
const float* k61 = k6.row(q+1);
const float* k62 = k6.row(q+2);
const float* k63 = k6.row(q+3);
const float* k70 = k7.row(q);
const float* k71 = k7.row(q+1);
const float* k72 = k7.row(q+2);
const float* k73 = k7.row(q+3);
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00[4] = k40[k];
g00[5] = k50[k];
g00[6] = k60[k];
g00[7] = k70[k];
g00[8] = k01[k];
g00[9] = k11[k];
g00[10] = k21[k];
g00[11] = k31[k];
g00[12] = k41[k];
g00[13] = k51[k];
g00[14] = k61[k];
g00[15] = k71[k];
g00[16] = k02[k];
g00[17] = k12[k];
g00[18] = k22[k];
g00[19] = k32[k];
g00[20] = k42[k];
g00[21] = k52[k];
g00[22] = k62[k];
g00[23] = k72[k];
g00[24] = k03[k];
g00[25] = k13[k];
g00[26] = k23[k];
g00[27] = k33[k];
g00[28] = k43[k];
g00[29] = k53[k];
g00[30] = k63[k];
g00[31] = k73[k];
g00 += 32;
}
}
}
#endif // __aarch64__
for (; p+3<outch; p+=4)
{
const Mat k0 = kernel_tm.channel(p);
const Mat k1 = kernel_tm.channel(p+1);
const Mat k2 = kernel_tm.channel(p+2);
const Mat k3 = kernel_tm.channel(p+3);
#if __aarch64__
Mat g0 = kernel_tm_pack4.channel(p/8+(p%8)/4);
#else
Mat g0 = kernel_tm_pack4.channel(p/4);
#endif
for (int k=0; k<64; k++)
{
float* g00 = g0.row(k);
for (int q=0; q+3<inch; q+=4)
{
const float* k00 = k0.row(q);
const float* k01 = k0.row(q+1);
const float* k02 = k0.row(q+2);
const float* k03 = k0.row(q+3);
const float* k10 = k1.row(q);
const float* k11 = k1.row(q+1);
const float* k12 = k1.row(q+2);
const float* k13 = k1.row(q+3);
const float* k20 = k2.row(q);
const float* k21 = k2.row(q+1);
const float* k22 = k2.row(q+2);
const float* k23 = k2.row(q+3);
const float* k30 = k3.row(q);
const float* k31 = k3.row(q+1);
const float* k32 = k3.row(q+2);
const float* k33 = k3.row(q+3);
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00[4] = k01[k];
g00[5] = k11[k];
g00[6] = k21[k];
g00[7] = k31[k];
g00[8] = k02[k];
g00[9] = k12[k];
g00[10] = k22[k];
g00[11] = k32[k];
g00[12] = k03[k];
g00[13] = k13[k];
g00[14] = k23[k];
g00[15] = k33[k];
g00 += 16;
}
}
}
for (; p<outch; p++)
{
const Mat k0 = kernel_tm.channel(p);
#if __aarch64__
Mat g0 = kernel_tm_pack4.channel(p/8+(p%8)/4+p%4);
#else
Mat g0 = kernel_tm_pack4.channel(p/4+p%4);
#endif
for (int k=0; k<64; k++)
{
float* g00 = g0.row(k);
for (int q=0; q+3<inch; q+=4)
{
const float* k00 = k0.row(q);
const float* k01 = k0.row(q+1);
const float* k02 = k0.row(q+2);
const float* k03 = k0.row(q+3);
g00[0] = k00[k];
g00[1] = k01[k];
g00[2] = k02[k];
g00[3] = k03[k];
g00 += 4;
}
}
}
}
static void conv3x3s1_winograd64_pack4to1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 6n+2
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 5) / 6 * 6;
outh = (outh + 5) / 6 * 6;
w = outw + 2;
h = outh + 2;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt);
const float* bias = _bias;
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm/8 * h_tm/8;
bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator);
// const float itm[8][8] = {
// {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f},
//
// {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f},
// {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f},
//
// {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f},
// {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f},
//
// {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f},
// {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f},
//
// {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f}
// };
// 0 = r00 - r06 + (r04 - r02) * 5.25
// 7 = r07 - r01 + (r03 - r05) * 5.25
// 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05)
// 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05)
// 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// reuse r04 * 1.25
// reuse r03 * 2.5
// 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5)
// 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5)
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q<inch; q++)
{
const Mat img0 = bottom_blob_bordered.channel(q);
Mat img0_tm = bottom_blob_tm.channel(q);
float tmp[8][8][4];
// tile
for (int i=0; i<h_tm/8; i++)
{
for (int j=0; j<w_tm/8; j++)
{
const float* r0 = img0.row(i * 6) + (j * 6) * 4;
for (int m=0; m<8; m++)
{
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _r05 = vld1q_f32(r0 + 20);
float32x4_t _r06 = vld1q_f32(r0 + 24);
float32x4_t _r07 = vld1q_f32(r0 + 28);
float32x4_t _tmp0m = vmlaq_n_f32(vsubq_f32(_r00, _r06), vsubq_f32(_r04, _r02), 5.25f);
float32x4_t _tmp7m = vmlaq_n_f32(vsubq_f32(_r07, _r01), vsubq_f32(_r03, _r05), 5.25f);
vst1q_f32(tmp[0][m], _tmp0m);
vst1q_f32(tmp[7][m], _tmp7m);
// tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25;
// tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25;
float32x4_t _tmp12a = vmlsq_n_f32(vaddq_f32(_r02, _r06), _r04, 4.25f);
float32x4_t _tmp12b = vmlsq_n_f32(vaddq_f32(_r01, _r05), _r03, 4.25f);
// float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25);
// float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25);
float32x4_t _tmp1m = vaddq_f32(_tmp12a, _tmp12b);
float32x4_t _tmp2m = vsubq_f32(_tmp12a, _tmp12b);
vst1q_f32(tmp[1][m], _tmp1m);
vst1q_f32(tmp[2][m], _tmp2m);
// tmp[1][m] = tmp12a + tmp12b;
// tmp[2][m] = tmp12a - tmp12b;
float32x4_t _tmp34a = vmlsq_n_f32(vmlaq_n_f32(_r06, _r02, 0.25f), _r04, 1.25f);
float32x4_t _tmp34b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_r01, 0.5f), _r03, 2.5f), _r05, 2.f);
// float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25);
// float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2);
float32x4_t _tmp3m = vaddq_f32(_tmp34a, _tmp34b);
float32x4_t _tmp4m = vsubq_f32(_tmp34a, _tmp34b);
vst1q_f32(tmp[3][m], _tmp3m);
vst1q_f32(tmp[4][m], _tmp4m);
// tmp[3][m] = tmp34a + tmp34b;
// tmp[4][m] = tmp34a - tmp34b;
float32x4_t _tmp56a = vmlaq_n_f32(_r06, vmlsq_n_f32(_r02, _r04, 1.25f), 4.f);
float32x4_t _tmp56b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_r01, 2.f), _r03, 2.5f), _r05, 0.5f);
// float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4);
// float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5);
float32x4_t _tmp5m = vaddq_f32(_tmp56a, _tmp56b);
float32x4_t _tmp6m = vsubq_f32(_tmp56a, _tmp56b);
vst1q_f32(tmp[5][m], _tmp5m);
vst1q_f32(tmp[6][m], _tmp6m);
// tmp[5][m] = tmp56a + tmp56b;
// tmp[6][m] = tmp56a - tmp56b;
r0 += w * 4;
}
float* r0_tm_0 = (float*)img0_tm + (i * w_tm/8 + j) * 4;
float* r0_tm_1 = r0_tm_0 + tiles * 4;
float* r0_tm_2 = r0_tm_0 + tiles * 8;
float* r0_tm_3 = r0_tm_0 + tiles * 12;
float* r0_tm_4 = r0_tm_0 + tiles * 16;
float* r0_tm_5 = r0_tm_0 + tiles * 20;
float* r0_tm_6 = r0_tm_0 + tiles * 24;
float* r0_tm_7 = r0_tm_0 + tiles * 28;
for (int m=0; m<8; m++)
{
float32x4_t _tmp00 = vld1q_f32(tmp[m][0]);
float32x4_t _tmp01 = vld1q_f32(tmp[m][1]);
float32x4_t _tmp02 = vld1q_f32(tmp[m][2]);
float32x4_t _tmp03 = vld1q_f32(tmp[m][3]);
float32x4_t _tmp04 = vld1q_f32(tmp[m][4]);
float32x4_t _tmp05 = vld1q_f32(tmp[m][5]);
float32x4_t _tmp06 = vld1q_f32(tmp[m][6]);
float32x4_t _tmp07 = vld1q_f32(tmp[m][7]);
float32x4_t _r0tm0 = vmlaq_n_f32(vsubq_f32(_tmp00, _tmp06), vsubq_f32(_tmp04, _tmp02), 5.25f);
float32x4_t _r0tm7 = vmlaq_n_f32(vsubq_f32(_tmp07, _tmp01), vsubq_f32(_tmp03, _tmp05), 5.25f);
// r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25;
// r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25;
float32x4_t _tmp12a = vmlsq_n_f32(vaddq_f32(_tmp02, _tmp06), _tmp04, 4.25f);
float32x4_t _tmp12b = vmlsq_n_f32(vaddq_f32(_tmp01, _tmp05), _tmp03, 4.25f);
// float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25);
// float tmp12b = (tmp0[1] + tmp0[5] - tmp0[3] * 4.25);
float32x4_t _r0tm1 = vaddq_f32(_tmp12a, _tmp12b);
float32x4_t _r0tm2 = vsubq_f32(_tmp12a, _tmp12b);
// r0_tm[1] = tmp12a + tmp12b;
// r0_tm[2] = tmp12a - tmp12b;
float32x4_t _tmp34a = vmlsq_n_f32(vmlaq_n_f32(_tmp06, _tmp02, 0.25f), _tmp04, 1.25f);
float32x4_t _tmp34b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_tmp01, 0.5f), _tmp03, 2.5f), _tmp05, 2.f);
// float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25);
// float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2);
float32x4_t _r0tm3 = vaddq_f32(_tmp34a, _tmp34b);
float32x4_t _r0tm4 = vsubq_f32(_tmp34a, _tmp34b);
// r0_tm[3] = tmp34a + tmp34b;
// r0_tm[4] = tmp34a - tmp34b;
float32x4_t _tmp56a = vmlaq_n_f32(_tmp06, vmlsq_n_f32(_tmp02, _tmp04, 1.25f), 4.f);
float32x4_t _tmp56b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_tmp01, 2.f), _tmp03, 2.5f), _tmp05, 0.5f);
// float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4);
// float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5);
float32x4_t _r0tm5 = vaddq_f32(_tmp56a, _tmp56b);
float32x4_t _r0tm6 = vsubq_f32(_tmp56a, _tmp56b);
// r0_tm[5] = tmp56a + tmp56b;
// r0_tm[6] = tmp56a - tmp56b;
vst1q_f32(r0_tm_0, _r0tm0);
vst1q_f32(r0_tm_1, _r0tm1);
vst1q_f32(r0_tm_2, _r0tm2);
vst1q_f32(r0_tm_3, _r0tm3);
vst1q_f32(r0_tm_4, _r0tm4);
vst1q_f32(r0_tm_5, _r0tm5);
vst1q_f32(r0_tm_6, _r0tm6);
vst1q_f32(r0_tm_7, _r0tm7);
r0_tm_0 += tiles * 32;
r0_tm_1 += tiles * 32;
r0_tm_2 += tiles * 32;
r0_tm_3 += tiles * 32;
r0_tm_4 += tiles * 32;
r0_tm_5 += tiles * 32;
r0_tm_6 += tiles * 32;
r0_tm_7 += tiles * 32;
}
}
}
}
}
bottom_blob_bordered = Mat();
// END transform input
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = h_tm/8 * w_tm/8;
// permute
// bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator);
Mat bottom_blob_tm2;
#if __aarch64__
if (tiles >= 12)
bottom_blob_tm2.create(12 * inch, tiles/12 + (tiles%12)/8 + (tiles%12%8)/4 + tiles%12%4, 64, elemsize, elempack, opt.workspace_allocator);
else if (tiles >= 8)
bottom_blob_tm2.create(8 * inch, tiles/8 + (tiles%8)/4 + tiles%4, 64, elemsize, elempack, opt.workspace_allocator);
else if (tiles >= 4)
bottom_blob_tm2.create(4 * inch, tiles/4 + tiles%4, 64, elemsize, elempack, opt.workspace_allocator);
else // if (tiles >= 1)
bottom_blob_tm2.create(1 * inch, tiles, 64, elemsize, elempack, opt.workspace_allocator);
#else
if (tiles >= 8)
bottom_blob_tm2.create(8 * inch, tiles/8 + (tiles%8)/4 + tiles%4, 64, elemsize, elempack, opt.workspace_allocator);
else if (tiles >= 4)
bottom_blob_tm2.create(4 * inch, tiles/4 + tiles%4, 64, elemsize, elempack, opt.workspace_allocator);
else // if (tiles >= 1)
bottom_blob_tm2.create(1 * inch, tiles, 64, elemsize, elempack, opt.workspace_allocator);
#endif
#pragma omp parallel for num_threads(opt.num_threads)
for (int r=0; r<64; r++)
{
Mat tm2 = bottom_blob_tm2.channel(r);
// tile
int i=0;
#if __aarch64__
for (; i+11<tiles; i+=12)
{
float* tm2p = tm2.row(i/12);
const float* r0 = bottom_blob_tm;
r0 += (r*tiles + i) * 4;
for (int q=0; q<inch; q++)
{
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0], #64 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v16.4s, v17.4s, v18.4s, v19.4s}, [%0] \n"
"sub %0, %0, #128 \n"
"st1 {v0.4s}, [%1], #16 \n"
"st1 {v4.4s}, [%1], #16 \n"
"st1 {v16.4s}, [%1], #16 \n"
"st1 {v1.4s}, [%1], #16 \n"
"st1 {v5.4s}, [%1], #16 \n"
"st1 {v17.4s}, [%1], #16 \n"
"st1 {v2.4s}, [%1], #16 \n"
"st1 {v6.4s}, [%1], #16 \n"
"st1 {v18.4s}, [%1], #16 \n"
"st1 {v3.4s}, [%1], #16 \n"
"st1 {v7.4s}, [%1], #16 \n"
"st1 {v19.4s}, [%1], #16 \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19"
);
r0 += bottom_blob_tm.cstep * 4;
}
}
#endif
for (; i+7<tiles; i+=8)
{
#if __aarch64__
float* tm2p = tm2.row(i/12 + (i%12)/8);
#else
float* tm2p = tm2.row(i/8);
#endif
const float* r0 = bottom_blob_tm;
r0 += (r*tiles + i) * 4;
for (int q=0; q<inch; q++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0] \n"
"sub %0, %0, #64 \n"
"st1 {v0.4s}, [%1], #16 \n"
"st1 {v4.4s}, [%1], #16 \n"
"st1 {v1.4s}, [%1], #16 \n"
"st1 {v5.4s}, [%1], #16 \n"
"st1 {v2.4s}, [%1], #16 \n"
"st1 {v6.4s}, [%1], #16 \n"
"st1 {v3.4s}, [%1], #16 \n"
"st1 {v7.4s}, [%1], #16 \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7"
);
#else
asm volatile(
"pld [%0, #256] \n"
"vld4.f32 {d0-d3}, [%0 :128]! \n"
"pld [%0, #256] \n"
"vld4.f32 {d4-d7}, [%0 :128]! \n"
"pld [%0, #256] \n"
"vld4.f32 {d16-d19}, [%0 :128]! \n"
"pld [%0, #256] \n"
"vld4.f32 {d20-d23}, [%0 :128] \n"
"sub %0, %0, #96 \n"
"vswp d1, d4 \n"
"vswp d3, d6 \n"
"vswp d17, d20 \n"
"vswp d19, d22 \n"
"vst1.f32 {d0-d1}, [%1 :128]! \n"
"vst1.f32 {d16-d17}, [%1 :128]! \n"
"vst1.f32 {d4-d5}, [%1 :128]! \n"
"vst1.f32 {d20-d21}, [%1 :128]! \n"
"vst1.f32 {d2-d3}, [%1 :128]! \n"
"vst1.f32 {d18-d19}, [%1 :128]! \n"
"vst1.f32 {d6-d7}, [%1 :128]! \n"
"vst1.f32 {d22-d23}, [%1 :128]! \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11"
);
#endif
r0 += bottom_blob_tm.cstep * 4;
}
}
for (; i+3<tiles; i+=4)
{
#if __aarch64__
float* tm2p = tm2.row(i/12 + (i%12)/8 + (i%12%8)/4);
#else
float* tm2p = tm2.row(i/8 + (i%8)/4);
#endif
const float* r0 = bottom_blob_tm;
r0 += (r*tiles + i) * 4;
for (int q=0; q<inch; q++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0] \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "v0", "v1", "v2", "v3"
);
#else
asm volatile(
"pld [%0, #256] \n"
"vld4.f32 {d0-d3}, [%0 :128]! \n"
"pld [%0, #256] \n"
"vld4.f32 {d4-d7}, [%0 :128] \n"
"sub %0, %0, #32 \n"
"vswp d1, d4 \n"
"vswp d3, d6 \n"
"vst1.f32 {d0-d1}, [%1 :128]! \n"
"vst1.f32 {d4-d5}, [%1 :128]! \n"
"vst1.f32 {d2-d3}, [%1 :128]! \n"
"vst1.f32 {d6-d7}, [%1 :128]! \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "q0", "q1", "q2", "q3"
);
#endif // __aarch64__
r0 += bottom_blob_tm.cstep * 4;
}
}
for (; i<tiles; i++)
{
#if __aarch64__
float* tm2p = tm2.row(i/12 + (i%12)/8 + (i%12%8)/4 + i%12%4);
#else
float* tm2p = tm2.row(i/8 + (i%8)/4 + i%4);
#endif
const float* r0 = bottom_blob_tm;
r0 += (r*tiles + i) * 4;
for (int q=0; q<inch; q++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v0.4s}, [%0] \n"
"st1 {v0.4s}, [%1], #16 \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "v0"
);
#else
asm volatile(
"pld [%0, #128] \n"
"vld1.f32 {d0-d1}, [%0 :128] \n"
"vst1.f32 {d0-d1}, [%1 :128]! \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "q0"
);
#endif // __aarch64__
r0 += bottom_blob_tm.cstep * 4;
}
}
}
bottom_blob_tm = Mat();
// permute end
top_blob_tm.create(tiles, 64, outch, 4u, 1, opt.workspace_allocator);
int nn_outch = 0;
int remain_outch_start = 0;
#if __aarch64__
nn_outch = outch >> 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 8;
float* output0_tm = top_blob_tm.channel(p);
float* output1_tm = top_blob_tm.channel(p+1);
float* output2_tm = top_blob_tm.channel(p+2);
float* output3_tm = top_blob_tm.channel(p+3);
float* output4_tm = top_blob_tm.channel(p+4);
float* output5_tm = top_blob_tm.channel(p+5);
float* output6_tm = top_blob_tm.channel(p+6);
float* output7_tm = top_blob_tm.channel(p+7);
const Mat kernel01_tm = kernel_tm.channel(p/8);
for (int r=0; r<64; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
int i=0;
for (; i+11<tiles; i+=12)
{
const float* r0 = bb2.row(i/12);
const float* kptr = kernel01_tm.row(r);
int nn = inch;// inch always > 0
asm volatile(
"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"
"eor v12.16b, v12.16b, v12.16b \n"
"eor v13.16b, v13.16b, v13.16b \n"
"eor v14.16b, v14.16b, v14.16b \n"
"eor v15.16b, v15.16b, v15.16b \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"
"eor v24.16b, v24.16b, v24.16b \n"
"eor v25.16b, v25.16b, v25.16b \n"
"eor v26.16b, v26.16b, v26.16b \n"
"eor v27.16b, v27.16b, v27.16b \n"
"eor v28.16b, v28.16b, v28.16b \n"
"eor v29.16b, v29.16b, v29.16b \n"
"eor v30.16b, v30.16b, v30.16b \n"
"eor v31.16b, v31.16b, v31.16b \n"
"0: \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"prfm pldl1keep, [%10, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v11.4s, v0.4s, v4.s[1] \n"
"fmla v14.4s, v0.4s, v4.s[2] \n"
"fmla v17.4s, v0.4s, v4.s[3] \n"
"fmla v20.4s, v0.4s, v5.s[0] \n"
"fmla v23.4s, v0.4s, v5.s[1] \n"
"fmla v26.4s, v0.4s, v5.s[2] \n"
"fmla v29.4s, v0.4s, v5.s[3] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v12.4s, v1.4s, v4.s[1] \n"
"fmla v15.4s, v1.4s, v4.s[2] \n"
"fmla v18.4s, v1.4s, v4.s[3] \n"
"fmla v21.4s, v1.4s, v5.s[0] \n"
"fmla v24.4s, v1.4s, v5.s[1] \n"
"fmla v27.4s, v1.4s, v5.s[2] \n"
"fmla v30.4s, v1.4s, v5.s[3] \n"
"fmla v10.4s, v2.4s, v4.s[0] \n"
"fmla v13.4s, v2.4s, v4.s[1] \n"
"fmla v16.4s, v2.4s, v4.s[2] \n"
"fmla v19.4s, v2.4s, v4.s[3] \n"
"fmla v22.4s, v2.4s, v5.s[0] \n"
"fmla v25.4s, v2.4s, v5.s[1] \n"
"fmla v28.4s, v2.4s, v5.s[2] \n"
"fmla v31.4s, v2.4s, v5.s[3] \n"
"fmla v8.4s, v3.4s, v6.s[0] \n"
"fmla v11.4s, v3.4s, v6.s[1] \n"
"fmla v14.4s, v3.4s, v6.s[2] \n"
"fmla v17.4s, v3.4s, v6.s[3] \n"
"fmla v20.4s, v3.4s, v7.s[0] \n"
"fmla v23.4s, v3.4s, v7.s[1] \n"
"fmla v26.4s, v3.4s, v7.s[2] \n"
"fmla v29.4s, v3.4s, v7.s[3] \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"fmla v9.4s, v0.4s, v6.s[0] \n"
"fmla v12.4s, v0.4s, v6.s[1] \n"
"fmla v15.4s, v0.4s, v6.s[2] \n"
"fmla v18.4s, v0.4s, v6.s[3] \n"
"fmla v21.4s, v0.4s, v7.s[0] \n"
"fmla v24.4s, v0.4s, v7.s[1] \n"
"fmla v27.4s, v0.4s, v7.s[2] \n"
"fmla v30.4s, v0.4s, v7.s[3] \n"
"fmla v10.4s, v1.4s, v6.s[0] \n"
"fmla v13.4s, v1.4s, v6.s[1] \n"
"fmla v16.4s, v1.4s, v6.s[2] \n"
"fmla v19.4s, v1.4s, v6.s[3] \n"
"fmla v22.4s, v1.4s, v7.s[0] \n"
"fmla v25.4s, v1.4s, v7.s[1] \n"
"fmla v28.4s, v1.4s, v7.s[2] \n"
"fmla v31.4s, v1.4s, v7.s[3] \n"
"prfm pldl1keep, [%10, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n"
"fmla v8.4s, v2.4s, v4.s[0] \n"
"fmla v11.4s, v2.4s, v4.s[1] \n"
"fmla v14.4s, v2.4s, v4.s[2] \n"
"fmla v17.4s, v2.4s, v4.s[3] \n"
"fmla v20.4s, v2.4s, v5.s[0] \n"
"fmla v23.4s, v2.4s, v5.s[1] \n"
"fmla v26.4s, v2.4s, v5.s[2] \n"
"fmla v29.4s, v2.4s, v5.s[3] \n"
"fmla v9.4s, v3.4s, v4.s[0] \n"
"fmla v12.4s, v3.4s, v4.s[1] \n"
"fmla v15.4s, v3.4s, v4.s[2] \n"
"fmla v18.4s, v3.4s, v4.s[3] \n"
"fmla v21.4s, v3.4s, v5.s[0] \n"
"fmla v24.4s, v3.4s, v5.s[1] \n"
"fmla v27.4s, v3.4s, v5.s[2] \n"
"fmla v30.4s, v3.4s, v5.s[3] \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"fmla v10.4s, v0.4s, v4.s[0] \n"
"fmla v13.4s, v0.4s, v4.s[1] \n"
"fmla v16.4s, v0.4s, v4.s[2] \n"
"fmla v19.4s, v0.4s, v4.s[3] \n"
"fmla v22.4s, v0.4s, v5.s[0] \n"
"fmla v25.4s, v0.4s, v5.s[1] \n"
"fmla v28.4s, v0.4s, v5.s[2] \n"
"fmla v31.4s, v0.4s, v5.s[3] \n"
"fmla v8.4s, v1.4s, v6.s[0] \n"
"fmla v11.4s, v1.4s, v6.s[1] \n"
"fmla v14.4s, v1.4s, v6.s[2] \n"
"fmla v17.4s, v1.4s, v6.s[3] \n"
"fmla v20.4s, v1.4s, v7.s[0] \n"
"fmla v23.4s, v1.4s, v7.s[1] \n"
"fmla v26.4s, v1.4s, v7.s[2] \n"
"fmla v29.4s, v1.4s, v7.s[3] \n"
"fmla v9.4s, v2.4s, v6.s[0] \n"
"fmla v12.4s, v2.4s, v6.s[1] \n"
"fmla v15.4s, v2.4s, v6.s[2] \n"
"fmla v18.4s, v2.4s, v6.s[3] \n"
"fmla v21.4s, v2.4s, v7.s[0] \n"
"fmla v24.4s, v2.4s, v7.s[1] \n"
"fmla v27.4s, v2.4s, v7.s[2] \n"
"fmla v30.4s, v2.4s, v7.s[3] \n"
"fmla v10.4s, v3.4s, v6.s[0] \n"
"fmla v13.4s, v3.4s, v6.s[1] \n"
"fmla v16.4s, v3.4s, v6.s[2] \n"
"fmla v19.4s, v3.4s, v6.s[3] \n"
"fmla v22.4s, v3.4s, v7.s[0] \n"
"fmla v25.4s, v3.4s, v7.s[1] \n"
"fmla v28.4s, v3.4s, v7.s[2] \n"
"fmla v31.4s, v3.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v8.4s, v9.4s, v10.4s}, [%1], #48 \n"
"st1 {v11.4s, v12.4s, v13.4s}, [%2], #48 \n"
"st1 {v14.4s, v15.4s, v16.4s}, [%3], #48 \n"
"st1 {v17.4s, v18.4s, v19.4s}, [%4], #48 \n"
"st1 {v20.4s, v21.4s, v22.4s}, [%5], #48 \n"
"st1 {v23.4s, v24.4s, v25.4s}, [%6], #48 \n"
"st1 {v26.4s, v27.4s, v28.4s}, [%7], #48 \n"
"st1 {v29.4s, v30.4s, v31.4s}, [%8], #48 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(output4_tm), // %5
"=r"(output5_tm), // %6
"=r"(output6_tm), // %7
"=r"(output7_tm), // %8
"=r"(r0), // %9
"=r"(kptr) // %10
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(output4_tm),
"6"(output5_tm),
"7"(output6_tm),
"8"(output7_tm),
"9"(r0),
"10"(kptr)
: "cc", "memory", "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+7<tiles; i+=8)
{
const float* r0 = bb2.row(i/12 + (i%12)/8);
const float* kptr = kernel01_tm.row(r);
int nn = inch;// inch always > 0
asm volatile(
"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"
"eor v24.16b, v24.16b, v24.16b \n"
"eor v25.16b, v25.16b, v25.16b \n"
"eor v26.16b, v26.16b, v26.16b \n"
"eor v27.16b, v27.16b, v27.16b \n"
"eor v28.16b, v28.16b, v28.16b \n"
"eor v29.16b, v29.16b, v29.16b \n"
"eor v30.16b, v30.16b, v30.16b \n"
"eor v31.16b, v31.16b, v31.16b \n"
"0: \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"prfm pldl1keep, [%10, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v0.4s, v4.s[0] \n"
"fmla v18.4s, v0.4s, v4.s[1] \n"
"fmla v20.4s, v0.4s, v4.s[2] \n"
"fmla v22.4s, v0.4s, v4.s[3] \n"
"fmla v24.4s, v0.4s, v5.s[0] \n"
"fmla v26.4s, v0.4s, v5.s[1] \n"
"fmla v28.4s, v0.4s, v5.s[2] \n"
"fmla v30.4s, v0.4s, v5.s[3] \n"
"fmla v17.4s, v1.4s, v4.s[0] \n"
"fmla v19.4s, v1.4s, v4.s[1] \n"
"fmla v21.4s, v1.4s, v4.s[2] \n"
"fmla v23.4s, v1.4s, v4.s[3] \n"
"fmla v25.4s, v1.4s, v5.s[0] \n"
"fmla v27.4s, v1.4s, v5.s[1] \n"
"fmla v29.4s, v1.4s, v5.s[2] \n"
"fmla v31.4s, v1.4s, v5.s[3] \n"
"fmla v16.4s, v2.4s, v6.s[0] \n"
"fmla v18.4s, v2.4s, v6.s[1] \n"
"fmla v20.4s, v2.4s, v6.s[2] \n"
"fmla v22.4s, v2.4s, v6.s[3] \n"
"fmla v24.4s, v2.4s, v7.s[0] \n"
"fmla v26.4s, v2.4s, v7.s[1] \n"
"fmla v28.4s, v2.4s, v7.s[2] \n"
"fmla v30.4s, v2.4s, v7.s[3] \n"
"fmla v17.4s, v3.4s, v6.s[0] \n"
"fmla v19.4s, v3.4s, v6.s[1] \n"
"fmla v21.4s, v3.4s, v6.s[2] \n"
"fmla v23.4s, v3.4s, v6.s[3] \n"
"fmla v25.4s, v3.4s, v7.s[0] \n"
"fmla v27.4s, v3.4s, v7.s[1] \n"
"fmla v29.4s, v3.4s, v7.s[2] \n"
"fmla v31.4s, v3.4s, v7.s[3] \n"
"prfm pldl1keep, [%9, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%9], #64 \n"
"prfm pldl1keep, [%10, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%10], #64 \n"
"fmla v16.4s, v12.4s, v8.s[0] \n"
"fmla v18.4s, v12.4s, v8.s[1] \n"
"fmla v20.4s, v12.4s, v8.s[2] \n"
"fmla v22.4s, v12.4s, v8.s[3] \n"
"fmla v24.4s, v12.4s, v9.s[0] \n"
"fmla v26.4s, v12.4s, v9.s[1] \n"
"fmla v28.4s, v12.4s, v9.s[2] \n"
"fmla v30.4s, v12.4s, v9.s[3] \n"
"fmla v17.4s, v13.4s, v8.s[0] \n"
"fmla v19.4s, v13.4s, v8.s[1] \n"
"fmla v21.4s, v13.4s, v8.s[2] \n"
"fmla v23.4s, v13.4s, v8.s[3] \n"
"fmla v25.4s, v13.4s, v9.s[0] \n"
"fmla v27.4s, v13.4s, v9.s[1] \n"
"fmla v29.4s, v13.4s, v9.s[2] \n"
"fmla v31.4s, v13.4s, v9.s[3] \n"
"fmla v16.4s, v14.4s, v10.s[0] \n"
"fmla v18.4s, v14.4s, v10.s[1] \n"
"fmla v20.4s, v14.4s, v10.s[2] \n"
"fmla v22.4s, v14.4s, v10.s[3] \n"
"fmla v24.4s, v14.4s, v11.s[0] \n"
"fmla v26.4s, v14.4s, v11.s[1] \n"
"fmla v28.4s, v14.4s, v11.s[2] \n"
"fmla v30.4s, v14.4s, v11.s[3] \n"
"fmla v17.4s, v15.4s, v10.s[0] \n"
"fmla v19.4s, v15.4s, v10.s[1] \n"
"fmla v21.4s, v15.4s, v10.s[2] \n"
"fmla v23.4s, v15.4s, v10.s[3] \n"
"fmla v25.4s, v15.4s, v11.s[0] \n"
"fmla v27.4s, v15.4s, v11.s[1] \n"
"fmla v29.4s, v15.4s, v11.s[2] \n"
"fmla v31.4s, v15.4s, v11.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s}, [%1], #32 \n"
"st1 {v18.4s, v19.4s}, [%2], #32 \n"
"st1 {v20.4s, v21.4s}, [%3], #32 \n"
"st1 {v22.4s, v23.4s}, [%4], #32 \n"
"st1 {v24.4s, v25.4s}, [%5], #32 \n"
"st1 {v26.4s, v27.4s}, [%6], #32 \n"
"st1 {v28.4s, v29.4s}, [%7], #32 \n"
"st1 {v30.4s, v31.4s}, [%8], #32 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(output4_tm), // %5
"=r"(output5_tm), // %6
"=r"(output6_tm), // %7
"=r"(output7_tm), // %8
"=r"(r0), // %9
"=r"(kptr) // %10
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(output4_tm),
"6"(output5_tm),
"7"(output6_tm),
"8"(output7_tm),
"9"(r0),
"10"(kptr)
: "cc", "memory", "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<tiles; i+=4)
{
const float* r0 = bb2.row(i/12 + (i%12)/8 + (i%12%8)/4);
const float* kptr = kernel01_tm.row(r);
int nn = inch;// inch always > 0
asm volatile(
"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, [%9, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%9], #64 \n"
"prfm pldl1keep, [%10, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v0.4s, v4.s[0] \n"
"fmla v17.4s, v0.4s, v4.s[1] \n"
"fmla v18.4s, v0.4s, v4.s[2] \n"
"fmla v19.4s, v0.4s, v4.s[3] \n"
"fmla v20.4s, v0.4s, v5.s[0] \n"
"fmla v21.4s, v0.4s, v5.s[1] \n"
"fmla v22.4s, v0.4s, v5.s[2] \n"
"fmla v23.4s, v0.4s, v5.s[3] \n"
"prfm pldl1keep, [%10, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%10], #64 \n"
"fmla v16.4s, v1.4s, v6.s[0] \n"
"fmla v17.4s, v1.4s, v6.s[1] \n"
"fmla v18.4s, v1.4s, v6.s[2] \n"
"fmla v19.4s, v1.4s, v6.s[3] \n"
"fmla v20.4s, v1.4s, v7.s[0] \n"
"fmla v21.4s, v1.4s, v7.s[1] \n"
"fmla v22.4s, v1.4s, v7.s[2] \n"
"fmla v23.4s, v1.4s, v7.s[3] \n"
"fmla v16.4s, v2.4s, v8.s[0] \n"
"fmla v17.4s, v2.4s, v8.s[1] \n"
"fmla v18.4s, v2.4s, v8.s[2] \n"
"fmla v19.4s, v2.4s, v8.s[3] \n"
"fmla v20.4s, v2.4s, v9.s[0] \n"
"fmla v21.4s, v2.4s, v9.s[1] \n"
"fmla v22.4s, v2.4s, v9.s[2] \n"
"fmla v23.4s, v2.4s, v9.s[3] \n"
"fmla v16.4s, v3.4s, v10.s[0] \n"
"fmla v17.4s, v3.4s, v10.s[1] \n"
"fmla v18.4s, v3.4s, v10.s[2] \n"
"fmla v19.4s, v3.4s, v10.s[3] \n"
"fmla v20.4s, v3.4s, v11.s[0] \n"
"fmla v21.4s, v3.4s, v11.s[1] \n"
"fmla v22.4s, v3.4s, v11.s[2] \n"
"fmla v23.4s, v3.4s, v11.s[3] \n"
"bne 0b \n"
"st1 {v16.4s}, [%1], #16 \n"
"st1 {v17.4s}, [%2], #16 \n"
"st1 {v18.4s}, [%3], #16 \n"
"st1 {v19.4s}, [%4], #16 \n"
"st1 {v20.4s}, [%5], #16 \n"
"st1 {v21.4s}, [%6], #16 \n"
"st1 {v22.4s}, [%7], #16 \n"
"st1 {v23.4s}, [%8], #16 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(output4_tm), // %5
"=r"(output5_tm), // %6
"=r"(output6_tm), // %7
"=r"(output7_tm), // %8
"=r"(r0), // %9
"=r"(kptr) // %10
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(output4_tm),
"6"(output5_tm),
"7"(output6_tm),
"8"(output7_tm),
"9"(r0),
"10"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"
);
}
for (; i<tiles; i++)
{
const float* r0 = bb2.row(i/12 + (i%12)/8 + (i%12%8)/4 + i%12%4);
const float* kptr = kernel01_tm.row(r);
int nn = inch;// inch always > 0
asm volatile(
"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"
"0: \n"
"prfm pldl1keep, [%9, #128] \n"
"ld1 {v0.4s}, [%9], #16 \n"
"prfm pldl1keep, [%10, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%10], #64 \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v4.4s, v0.s[0] \n"
"fmla v17.4s, v5.4s, v0.s[0] \n"
"fmla v18.4s, v6.4s, v0.s[1] \n"
"fmla v19.4s, v7.4s, v0.s[1] \n"
"prfm pldl1keep, [%10, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%10], #64 \n"
"fmla v16.4s, v8.4s, v0.s[2] \n"
"fmla v17.4s, v9.4s, v0.s[2] \n"
"fmla v18.4s, v10.4s, v0.s[3] \n"
"fmla v19.4s, v11.4s, v0.s[3] \n"
"bne 0b \n"
"fadd v16.4s, v16.4s, v18.4s \n"
"fadd v17.4s, v17.4s, v19.4s \n"
"st1 {v16.s}[0], [%1], #4 \n"
"st1 {v16.s}[1], [%2], #4 \n"
"st1 {v16.s}[2], [%3], #4 \n"
"st1 {v16.s}[3], [%4], #4 \n"
"st1 {v17.s}[0], [%5], #4 \n"
"st1 {v17.s}[1], [%6], #4 \n"
"st1 {v17.s}[2], [%7], #4 \n"
"st1 {v17.s}[3], [%8], #4 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(output4_tm), // %5
"=r"(output5_tm), // %6
"=r"(output6_tm), // %7
"=r"(output7_tm), // %8
"=r"(r0), // %9
"=r"(kptr) // %10
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(output4_tm),
"6"(output5_tm),
"7"(output6_tm),
"8"(output7_tm),
"9"(r0),
"10"(kptr)
: "cc", "memory", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19"
);
}
}
}
remain_outch_start += nn_outch << 3;
nn_outch = (outch - remain_outch_start) >> 2;
#else // __aarch64__
nn_outch = outch >> 2;
#endif // __aarch64__
#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* output0_tm = top_blob_tm.channel(p);
float* output1_tm = top_blob_tm.channel(p+1);
float* output2_tm = top_blob_tm.channel(p+2);
float* output3_tm = top_blob_tm.channel(p+3);
#if __aarch64__
const Mat kernel01_tm = kernel_tm.channel(p/8+(p%8)/4);
#else
const Mat kernel01_tm = kernel_tm.channel(p/4);
#endif
for (int r=0; r<64; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
int i=0;
#if __aarch64__
for (; i+11<tiles; i+=12)
{
const float* r0 = bb2.row(i/12);
const float* kptr = kernel01_tm.row(r);
int nn = inch;// inch always > 0
asm volatile(
"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"
"eor v12.16b, v12.16b, v12.16b \n"
"eor v13.16b, v13.16b, v13.16b \n"
"eor v14.16b, v14.16b, v14.16b \n"
"eor v15.16b, v15.16b, v15.16b \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"
"0: \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n"
"prfm pldl1keep, [%6, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%6], #64 \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v11.4s, v0.4s, v4.s[1] \n"
"fmla v14.4s, v0.4s, v4.s[2] \n"
"fmla v17.4s, v0.4s, v4.s[3] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v12.4s, v1.4s, v4.s[1] \n"
"fmla v15.4s, v1.4s, v4.s[2] \n"
"fmla v18.4s, v1.4s, v4.s[3] \n"
"fmla v10.4s, v2.4s, v4.s[0] \n"
"fmla v13.4s, v2.4s, v4.s[1] \n"
"fmla v16.4s, v2.4s, v4.s[2] \n"
"fmla v19.4s, v2.4s, v4.s[3] \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%5], #64 \n"
"fmla v8.4s, v3.4s, v5.s[0] \n"
"fmla v11.4s, v3.4s, v5.s[1] \n"
"fmla v14.4s, v3.4s, v5.s[2] \n"
"fmla v17.4s, v3.4s, v5.s[3] \n"
"fmla v9.4s, v20.4s, v5.s[0] \n"
"fmla v12.4s, v20.4s, v5.s[1] \n"
"fmla v15.4s, v20.4s, v5.s[2] \n"
"fmla v18.4s, v20.4s, v5.s[3] \n"
"fmla v10.4s, v21.4s, v5.s[0] \n"
"fmla v13.4s, v21.4s, v5.s[1] \n"
"fmla v16.4s, v21.4s, v5.s[2] \n"
"fmla v19.4s, v21.4s, v5.s[3] \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%5], #64 \n"
"fmla v8.4s, v22.4s, v6.s[0] \n"
"fmla v11.4s, v22.4s, v6.s[1] \n"
"fmla v14.4s, v22.4s, v6.s[2] \n"
"fmla v17.4s, v22.4s, v6.s[3] \n"
"fmla v9.4s, v23.4s, v6.s[0] \n"
"fmla v12.4s, v23.4s, v6.s[1] \n"
"fmla v15.4s, v23.4s, v6.s[2] \n"
"fmla v18.4s, v23.4s, v6.s[3] \n"
"fmla v10.4s, v24.4s, v6.s[0] \n"
"fmla v13.4s, v24.4s, v6.s[1] \n"
"fmla v16.4s, v24.4s, v6.s[2] \n"
"fmla v19.4s, v24.4s, v6.s[3] \n"
"fmla v8.4s, v25.4s, v7.s[0] \n"
"fmla v11.4s, v25.4s, v7.s[1] \n"
"fmla v14.4s, v25.4s, v7.s[2] \n"
"fmla v17.4s, v25.4s, v7.s[3] \n"
"fmla v9.4s, v26.4s, v7.s[0] \n"
"fmla v12.4s, v26.4s, v7.s[1] \n"
"fmla v15.4s, v26.4s, v7.s[2] \n"
"fmla v18.4s, v26.4s, v7.s[3] \n"
"fmla v10.4s, v27.4s, v7.s[0] \n"
"fmla v13.4s, v27.4s, v7.s[1] \n"
"fmla v16.4s, v27.4s, v7.s[2] \n"
"fmla v19.4s, v27.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v8.4s, v9.4s, v10.4s}, [%1], #48 \n"
"st1 {v11.4s, v12.4s, v13.4s}, [%2], #48 \n"
"st1 {v14.4s, v15.4s, v16.4s}, [%3], #48 \n"
"st1 {v17.4s, v18.4s, v19.4s}, [%4], #48 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(r0), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(r0),
"6"(kptr)
: "cc", "memory", "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"
);
}
#endif // __aarch64__
for (; i+7<tiles; i+=8)
{
#if __aarch64__
const float* r0 = bb2.row(i/12 + (i%12)/8);
#else
const float* r0 = bb2.row(i/8);
#endif
const float* kptr = kernel01_tm.row(r);
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"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"
"eor v12.16b, v12.16b, v12.16b \n"
"eor v13.16b, v13.16b, v13.16b \n"
"eor v14.16b, v14.16b, v14.16b \n"
"eor v15.16b, v15.16b, v15.16b \n"
"0: \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n"
"prfm pldl1keep, [%6, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%6], #64 \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v10.4s, v0.4s, v4.s[1] \n"
"fmla v12.4s, v0.4s, v4.s[2] \n"
"fmla v14.4s, v0.4s, v4.s[3] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v11.4s, v1.4s, v4.s[1] \n"
"fmla v13.4s, v1.4s, v4.s[2] \n"
"fmla v15.4s, v1.4s, v4.s[3] \n"
"fmla v8.4s, v2.4s, v5.s[0] \n"
"fmla v10.4s, v2.4s, v5.s[1] \n"
"fmla v12.4s, v2.4s, v5.s[2] \n"
"fmla v14.4s, v2.4s, v5.s[3] \n"
"fmla v9.4s, v3.4s, v5.s[0] \n"
"fmla v11.4s, v3.4s, v5.s[1] \n"
"fmla v13.4s, v3.4s, v5.s[2] \n"
"fmla v15.4s, v3.4s, v5.s[3] \n"
"prfm pldl1keep, [%5, #512] \n"
"ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%5], #64 \n"
"fmla v8.4s, v16.4s, v6.s[0] \n"
"fmla v10.4s, v16.4s, v6.s[1] \n"
"fmla v12.4s, v16.4s, v6.s[2] \n"
"fmla v14.4s, v16.4s, v6.s[3] \n"
"fmla v9.4s, v17.4s, v6.s[0] \n"
"fmla v11.4s, v17.4s, v6.s[1] \n"
"fmla v13.4s, v17.4s, v6.s[2] \n"
"fmla v15.4s, v17.4s, v6.s[3] \n"
"fmla v8.4s, v18.4s, v7.s[0] \n"
"fmla v10.4s, v18.4s, v7.s[1] \n"
"fmla v12.4s, v18.4s, v7.s[2] \n"
"fmla v14.4s, v18.4s, v7.s[3] \n"
"fmla v9.4s, v19.4s, v7.s[0] \n"
"fmla v11.4s, v19.4s, v7.s[1] \n"
"fmla v13.4s, v19.4s, v7.s[2] \n"
"fmla v15.4s, v19.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v8.4s, v9.4s}, [%1], #32 \n"
"st1 {v10.4s, v11.4s}, [%2], #32 \n"
"st1 {v12.4s, v13.4s}, [%3], #32 \n"
"st1 {v14.4s, v15.4s}, [%4], #32 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(r0), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(r0),
"6"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"
);
#else // __aarch64__
asm volatile(
"veor q8, q8 \n"
"veor q9, q9 \n"
"veor q10, q10 \n"
"veor q11, q11 \n"
"veor q12, q12 \n"
"veor q13, q13 \n"
"veor q14, q14 \n"
"veor q15, q15 \n"
"0: \n"
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n"
"pld [%6, #512] \n"
"vldm %6!, {d8-d15} \n"
"vmla.f32 q8, q0, d8[0] \n"
"vmla.f32 q10, q0, d8[1] \n"
"vmla.f32 q12, q0, d9[0] \n"
"vmla.f32 q14, q0, d9[1] \n"
"vmla.f32 q9, q1, d8[0] \n"
"vmla.f32 q11, q1, d8[1] \n"
"vmla.f32 q13, q1, d9[0] \n"
"vmla.f32 q15, q1, d9[1] \n"
"vmla.f32 q8, q2, d10[0] \n"
"vmla.f32 q10, q2, d10[1] \n"
"vmla.f32 q12, q2, d11[0] \n"
"vmla.f32 q14, q2, d11[1] \n"
"vmla.f32 q9, q3, d10[0] \n"
"vmla.f32 q11, q3, d10[1] \n"
"vmla.f32 q13, q3, d11[0] \n"
"vmla.f32 q15, q3, d11[1] \n"
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n"
"vmla.f32 q8, q0, d12[0] \n"
"vmla.f32 q10, q0, d12[1] \n"
"vmla.f32 q12, q0, d13[0] \n"
"vmla.f32 q14, q0, d13[1] \n"
"vmla.f32 q9, q1, d12[0] \n"
"vmla.f32 q11, q1, d12[1] \n"
"vmla.f32 q13, q1, d13[0] \n"
"vmla.f32 q15, q1, d13[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q2, d14[0] \n"
"vmla.f32 q10, q2, d14[1] \n"
"vmla.f32 q12, q2, d15[0] \n"
"vmla.f32 q14, q2, d15[1] \n"
"vmla.f32 q9, q3, d14[0] \n"
"vmla.f32 q11, q3, d14[1] \n"
"vmla.f32 q13, q3, d15[0] \n"
"vmla.f32 q15, q3, d15[1] \n"
"bne 0b \n"
"vst1.f32 {d16-d19}, [%1]! \n"
"vst1.f32 {d20-d23}, [%2]! \n"
"vst1.f32 {d24-d27}, [%3]! \n"
"vst1.f32 {d28-d31}, [%4]! \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(r0), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(r0),
"6"(kptr)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
#endif // __aarch64__
}
for (; i+3<tiles; i+=4)
{
#if __aarch64__
const float* r0 = bb2.row(i/12 + (i%12)/8 + (i%12%8)/4);
#else
const float* r0 = bb2.row(i/8 + (i%8)/4);
#endif
const float* kptr = kernel01_tm.row(r);
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"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, [%5, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%5], #64 \n"
"prfm pldl1keep, [%6, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%6], #64 \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v9.4s, v0.4s, v4.s[1] \n"
"fmla v10.4s, v0.4s, v4.s[2] \n"
"fmla v11.4s, v0.4s, v4.s[3] \n"
"fmla v8.4s, v1.4s, v5.s[0] \n"
"fmla v9.4s, v1.4s, v5.s[1] \n"
"fmla v10.4s, v1.4s, v5.s[2] \n"
"fmla v11.4s, v1.4s, v5.s[3] \n"
"fmla v8.4s, v2.4s, v6.s[0] \n"
"fmla v9.4s, v2.4s, v6.s[1] \n"
"fmla v10.4s, v2.4s, v6.s[2] \n"
"fmla v11.4s, v2.4s, v6.s[3] \n"
"fmla v8.4s, v3.4s, v7.s[0] \n"
"fmla v9.4s, v3.4s, v7.s[1] \n"
"fmla v10.4s, v3.4s, v7.s[2] \n"
"fmla v11.4s, v3.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v8.4s}, [%1], #16 \n"
"st1 {v9.4s}, [%2], #16 \n"
"st1 {v10.4s}, [%3], #16 \n"
"st1 {v11.4s}, [%4], #16 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(r0), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(r0),
"6"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11"
);
#else // __aarch64__
asm volatile(
"veor q8, q8 \n"
"veor q9, q9 \n"
"veor q10, q10 \n"
"veor q11, q11 \n"
"0: \n"
"pld [%5, #512] \n"
"vldm %5!, {d0-d7} \n"
"pld [%6, #512] \n"
"vldm %6!, {d8-d15} \n"
"vmla.f32 q8, q0, d8[0] \n"
"vmla.f32 q9, q0, d8[1] \n"
"vmla.f32 q10, q0, d9[0] \n"
"vmla.f32 q11, q0, d9[1] \n"
"vmla.f32 q8, q1, d10[0] \n"
"vmla.f32 q9, q1, d10[1] \n"
"vmla.f32 q10, q1, d11[0] \n"
"vmla.f32 q11, q1, d11[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q2, d12[0] \n"
"vmla.f32 q9, q2, d12[1] \n"
"vmla.f32 q10, q2, d13[0] \n"
"vmla.f32 q11, q2, d13[1] \n"
"vmla.f32 q8, q3, d14[0] \n"
"vmla.f32 q9, q3, d14[1] \n"
"vmla.f32 q10, q3, d15[0] \n"
"vmla.f32 q11, q3, d15[1] \n"
"bne 0b \n"
"vst1.f32 {d16-d17}, [%1]! \n"
"vst1.f32 {d18-d19}, [%2]! \n"
"vst1.f32 {d20-d21}, [%3]! \n"
"vst1.f32 {d22-d23}, [%4]! \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(r0), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(r0),
"6"(kptr)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"
);
#endif // __aarch64__
}
for (; i<tiles; i++)
{
#if __aarch64__
const float* r0 = bb2.row(i/12 + (i%12)/8 + (i%12%8)/4 + i%12%4);
#else
const float* r0 = bb2.row(i/8 + (i%8)/4 + i%4);
#endif
const float* kptr = kernel01_tm.row(r);
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"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, [%5, #128] \n"
"ld1 {v0.4s}, [%5], #16 \n"
"prfm pldl1keep, [%6, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%6], #64 \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v5.4s, v0.s[1] \n"
"fmla v10.4s, v6.4s, v0.s[2] \n"
"fmla v11.4s, v7.4s, v0.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"
"st1 {v8.s}[0], [%1], #4 \n"
"st1 {v8.s}[1], [%2], #4 \n"
"st1 {v8.s}[2], [%3], #4 \n"
"st1 {v8.s}[3], [%4], #4 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(r0), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(r0),
"6"(kptr)
: "cc", "memory", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11"
);
#else // __aarch64__
asm volatile(
"veor q8, q8 \n"
"veor q9, q9 \n"
"veor q10, q10 \n"
"veor q11, q11 \n"
"0: \n"
"pld [%5, #128] \n"
"vld1.f32 {d0-d1}, [%5]! \n"
"pld [%6, #512] \n"
"vldm %6!, {d8-d15} \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q5, d0[1] \n"
"vmla.f32 q10, q6, d1[0] \n"
"vmla.f32 q11, q7, d1[1] \n"
"bne 0b \n"
"vadd.f32 q8, q8, q9 \n"
"vadd.f32 q10, q10, q11 \n"
"vadd.f32 q8, q8, q10 \n"
"vst1.f32 {d16[0]}, [%1]! \n"
"vst1.f32 {d16[1]}, [%2]! \n"
"vst1.f32 {d17[0]}, [%3]! \n"
"vst1.f32 {d17[1]}, [%4]! \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(output2_tm), // %3
"=r"(output3_tm), // %4
"=r"(r0), // %5
"=r"(kptr) // %6
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(output2_tm),
"4"(output3_tm),
"5"(r0),
"6"(kptr)
: "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"
);
#endif // __aarch64__
}
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
float* output0_tm = top_blob_tm.channel(p);
#if __aarch64__
const Mat kernel0_tm = kernel_tm.channel(p/8+(p%8)/4+p%4);
#else
const Mat kernel0_tm = kernel_tm.channel(p/4+p%4);
#endif
for (int r=0; r<64; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
int i=0;
#if __aarch64__
for (; i+11<tiles; i+=12)
{
const float* r0 = bb2.row(i/12);
const float* kptr = kernel0_tm.row(r);
int nn = inch;// inch always > 0
asm volatile(
"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 v5.16b, v5.16b, v5.16b \n"
"eor v6.16b, v6.16b, v6.16b \n"
"eor v7.16b, v7.16b, v7.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v4.4s}, [%3], #16 \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v10.4s, v2.4s, v4.s[0] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%2], #64 \n"
"fmla v5.4s, v3.4s, v4.s[1] \n"
"fmla v6.4s, v12.4s, v4.s[1] \n"
"fmla v7.4s, v13.4s, v4.s[1] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%2], #64 \n"
"fmla v8.4s, v14.4s, v4.s[2] \n"
"fmla v9.4s, v15.4s, v4.s[2] \n"
"fmla v10.4s, v16.4s, v4.s[2] \n"
"fmla v5.4s, v17.4s, v4.s[3] \n"
"fmla v6.4s, v18.4s, v4.s[3] \n"
"fmla v7.4s, v19.4s, v4.s[3] \n"
"bne 0b \n"
"fadd v8.4s, v8.4s, v5.4s \n"
"fadd v9.4s, v9.4s, v6.4s \n"
"fadd v10.4s, v10.4s, v7.4s \n"
"st1 {v8.4s, v9.4s, v10.4s}, [%1], #48 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(r0), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(output0_tm),
"2"(r0),
"3"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"
);
}
#endif
for (; i+7<tiles; i+=8)
{
#if __aarch64__
const float* r0 = bb2.row(i/12 + (i%12)/8);
#else
const float* r0 = bb2.row(i/8);
#endif
const float* kptr = kernel0_tm.row(r);
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"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, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v4.4s}, [%3], #16 \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v9.4s, v1.4s, v4.s[0] \n"
"fmla v10.4s, v2.4s, v4.s[1] \n"
"fmla v11.4s, v3.4s, v4.s[1] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%2], #64 \n"
"fmla v8.4s, v12.4s, v4.s[2] \n"
"fmla v9.4s, v13.4s, v4.s[2] \n"
"fmla v10.4s, v14.4s, v4.s[3] \n"
"fmla v11.4s, v15.4s, v4.s[3] \n"
"bne 0b \n"
"fadd v8.4s, v8.4s, v10.4s \n"
"fadd v9.4s, v9.4s, v11.4s \n"
"st1 {v8.4s, v9.4s}, [%1], #32 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(r0), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(output0_tm),
"2"(r0),
"3"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"
);
#else // __aarch64__
asm volatile(
"veor q8, q8 \n"
"veor q9, q9 \n"
"veor q10, q10 \n"
"veor q11, q11 \n"
"0: \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"pld [%3, #128] \n"
"vld1.f32 {d8-d9}, [%3]! \n"
"vmla.f32 q8, q0, d8[0] \n"
"vmla.f32 q9, q1, d8[0] \n"
"vmla.f32 q10, q2, d8[1] \n"
"vmla.f32 q11, q3, d8[1] \n"
"pld [%2, #512] \n"
"vldm %2!, {d24-d31} \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q12, d9[0] \n"
"vmla.f32 q9, q13, d9[0] \n"
"vmla.f32 q10, q14, d9[1] \n"
"vmla.f32 q11, q15, d9[1] \n"
"bne 0b \n"
"vadd.f32 q8, q8, q10 \n"
"vadd.f32 q9, q9, q11 \n"
"vst1.f32 {d16-d19}, [%1]! \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(r0), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(output0_tm),
"2"(r0),
"3"(kptr)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
#endif // __aarch64__
}
for (; i+3<tiles; i+=4)
{
#if __aarch64__
const float* r0 = bb2.row(i/12 + (i%12)/8 + (i%12%8)/4);
#else
const float* r0 = bb2.row(i/8 + (i%8)/4);
#endif
const float* kptr = kernel0_tm.row(r);
int nn = inch;// inch always > 0
#if __aarch64__
asm volatile(
"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, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v4.4s}, [%3], #16 \n"
"subs %w0, %w0, #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"
"st1 {v8.4s}, [%1], #16 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(r0), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(output0_tm),
"2"(r0),
"3"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11"
);
#else // __aarch64__
asm volatile(
"veor q8, q8 \n"
"veor q9, q9 \n"
"veor q10, q10 \n"
"veor q11, q11 \n"
"0: \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"pld [%3, #128] \n"
"vld1.f32 {d8-d9}, [%3]! \n"
"subs %0, %0, #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"
"vst1.f32 {d16-d17}, [%1]! \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(r0), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(output0_tm),
"2"(r0),
"3"(kptr)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11"
);
#endif // __aarch64__
}
for (; i<tiles; i++)
{
#if __aarch64__
const float* r0 = bb2.row(i/12 + (i%12)/8 + (i%12%8)/4 + i%12%4);
#else
const float* r0 = bb2.row(i/8 + (i%8)/4 + i%4);
#endif
const float* kptr = kernel0_tm.row(r);
float32x4_t _sum0 = vdupq_n_f32(0.f);
for (int q=0; q<inch; q++)
{
float32x4_t _r0 = vld1q_f32(r0);
float32x4_t _k0 = vld1q_f32(kptr);
_sum0 = vmlaq_f32(_sum0, _r0, _k0);
kptr += 4;
r0 += 4;
}
#if __aarch64__
float sum0 = vaddvq_f32(_sum0);
#else
float32x2_t _ss = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0));
float32x2_t _ss2 = vpadd_f32(_ss, _ss);
float sum0 = vget_lane_f32(_ss2, 0);
#endif
output0_tm[0] = sum0;
output0_tm++;
}
}
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
if (outw == top_blob.w && outh == top_blob.h)
{
top_blob_bordered = top_blob;
}
else
{
top_blob_bordered.create(outw, outh, outch, 4u, 1, opt.workspace_allocator);
}
{
// const float otm[6][8] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f}
// };
// 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32
// 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16
// 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8
// 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4
// 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2
// 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6)
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm/8 * h_tm/8;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p<outch; p++)
{
const Mat out0_tm = top_blob_tm.channel(p);
Mat out0 = top_blob_bordered.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
// float32x2_t _bias0 = vdup_n_f32(bias0);
float tmp[6][8];
// tile
for (int i=0; i<outh/6; i++)
{
for (int j=0; j<outw/6; j++)
{
// top_blob_tm.create(tiles, 64, outch, 4u, 1, opt.workspace_allocator);
const float* output0_tm_0 = (const float*)out0_tm + (i * w_tm/8 + j) * 1;
const float* output0_tm_1 = output0_tm_0 + tiles * 1;
const float* output0_tm_2 = output0_tm_0 + tiles * 2;
const float* output0_tm_3 = output0_tm_0 + tiles * 3;
const float* output0_tm_4 = output0_tm_0 + tiles * 4;
const float* output0_tm_5 = output0_tm_0 + tiles * 5;
const float* output0_tm_6 = output0_tm_0 + tiles * 6;
const float* output0_tm_7 = output0_tm_0 + tiles * 7;
// TODO neon optimize
for (int m=0; m<8; m++)
{
float tmp024a = output0_tm_1[0] + output0_tm_2[0];
float tmp135a = output0_tm_1[0] - output0_tm_2[0];
float tmp024b = output0_tm_3[0] + output0_tm_4[0];
float tmp135b = output0_tm_3[0] - output0_tm_4[0];
float tmp024c = output0_tm_5[0] + output0_tm_6[0];
float tmp135c = output0_tm_5[0] - output0_tm_6[0];
tmp[0][m] = output0_tm_0[0] + tmp024a + tmp024b + tmp024c * 32;
tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8;
tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c;
tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16;
tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4;
tmp[5][m] = output0_tm_7[0] + tmp135a + tmp135b * 32 + tmp135c;
output0_tm_0 += tiles * 8;
output0_tm_1 += tiles * 8;
output0_tm_2 += tiles * 8;
output0_tm_3 += tiles * 8;
output0_tm_4 += tiles * 8;
output0_tm_5 += tiles * 8;
output0_tm_6 += tiles * 8;
output0_tm_7 += tiles * 8;
}
float* output0 = out0.row(i * 6) + j * 6;
for (int m=0; m<6; m++)
{
const float* tmp0 = tmp[m];
float tmp024a = tmp0[1] + tmp0[2];
float tmp135a = tmp0[1] - tmp0[2];
float tmp024b = tmp0[3] + tmp0[4];
float tmp135b = tmp0[3] - tmp0[4];
float tmp024c = tmp0[5] + tmp0[6];
float tmp135c = tmp0[5] - tmp0[6];
output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32;
output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8;
output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c;
output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16;
output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4;
output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c;
output0 += outw;
}
}
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
static void conv3x3s1_pack4to1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
int nn_outch = 0;
int remain_outch_start = 0;
#if __ARM_NEON && __aarch64__
nn_outch = outch >> 1;
remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p+1);
const float bias0 = bias ? bias[p] : 0.f;
const float bias1 = bias ? bias[p+1] : 0.f;
out0.fill(bias0);
out1.fill(bias1);
const float* k0 = kernel.channel(p);
const float* k1 = kernel.channel(p+1);
for (int q=0; q<inch; q++)
{
float* outptr0 = out0;
float* outptr1 = out1;
const Mat img0 = bottom_blob.channel(q);
const float* r0 = img0.row(0);
const float* r1 = img0.row(1);
const float* r2 = img0.row(2);
float32x4_t _k00_0 = vld1q_f32(k0);
float32x4_t _k01_0 = vld1q_f32(k0+4);
float32x4_t _k02_0 = vld1q_f32(k0+8);
float32x4_t _k10_0 = vld1q_f32(k0+12);
float32x4_t _k11_0 = vld1q_f32(k0+16);
float32x4_t _k12_0 = vld1q_f32(k0+20);
float32x4_t _k20_0 = vld1q_f32(k0+24);
float32x4_t _k21_0 = vld1q_f32(k0+28);
float32x4_t _k22_0 = vld1q_f32(k0+32);
float32x4_t _k00_1 = vld1q_f32(k1);
float32x4_t _k01_1 = vld1q_f32(k1+4);
float32x4_t _k02_1 = vld1q_f32(k1+8);
float32x4_t _k10_1 = vld1q_f32(k1+12);
float32x4_t _k11_1 = vld1q_f32(k1+16);
float32x4_t _k12_1 = vld1q_f32(k1+20);
float32x4_t _k20_1 = vld1q_f32(k1+24);
float32x4_t _k21_1 = vld1q_f32(k1+28);
float32x4_t _k22_1 = vld1q_f32(k1+32);
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j+3<outw; j+=4)
{
asm volatile(
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"// r00 r01 r02 r03
"fmul v16.4s, %10.4s, v0.4s \n"
"fmul v17.4s, %19.4s, v0.4s \n"
"fmul v18.4s, %10.4s, v1.4s \n"
"fmul v19.4s, %19.4s, v1.4s \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v4.4s, v5.4s}, [%2] \n"// r04 r05
"fmul v6.4s, %10.4s, v2.4s \n"
"fmul v7.4s, %19.4s, v2.4s \n"
"fmul v8.4s, %10.4s, v3.4s \n"
"fmul v9.4s, %19.4s, v3.4s \n"
"fmla v16.4s, %11.4s, v1.4s \n"
"fmla v17.4s, %20.4s, v1.4s \n"
"fmla v18.4s, %11.4s, v2.4s \n"
"fmla v19.4s, %20.4s, v2.4s \n"
"fmla v6.4s, %11.4s, v3.4s \n"
"fmla v7.4s, %20.4s, v3.4s \n"
"fmla v8.4s, %11.4s, v4.4s \n"
"fmla v9.4s, %20.4s, v4.4s \n"
"fmla v16.4s, %12.4s, v2.4s \n"
"fmla v17.4s, %21.4s, v2.4s \n"
"fmla v18.4s, %12.4s, v3.4s \n"
"fmla v19.4s, %21.4s, v3.4s \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"// r10 r11 r12 r12
"fmla v6.4s, %12.4s, v4.4s \n"
"fmla v7.4s, %21.4s, v4.4s \n"
"fmla v8.4s, %12.4s, v5.4s \n"
"fmla v9.4s, %21.4s, v5.4s \n"
"fmla v16.4s, %13.4s, v0.4s \n"
"fmla v17.4s, %22.4s, v0.4s \n"
"fmla v18.4s, %13.4s, v1.4s \n"
"fmla v19.4s, %22.4s, v1.4s \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v4.4s, v5.4s}, [%3] \n"// r14 r15
"fmla v6.4s, %13.4s, v2.4s \n"
"fmla v7.4s, %22.4s, v2.4s \n"
"fmla v8.4s, %13.4s, v3.4s \n"
"fmla v9.4s, %22.4s, v3.4s \n"
"fmla v16.4s, %14.4s, v1.4s \n"
"fmla v17.4s, %23.4s, v1.4s \n"
"fmla v18.4s, %14.4s, v2.4s \n"
"fmla v19.4s, %23.4s, v2.4s \n"
"fmla v6.4s, %14.4s, v3.4s \n"
"fmla v7.4s, %23.4s, v3.4s \n"
"fmla v8.4s, %14.4s, v4.4s \n"
"fmla v9.4s, %23.4s, v4.4s \n"
"fmla v16.4s, %15.4s, v2.4s \n"
"fmla v17.4s, %24.4s, v2.4s \n"
"fmla v18.4s, %15.4s, v3.4s \n"
"fmla v19.4s, %24.4s, v3.4s \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%4], #64 \n"// r20 r21 r22 r22
"fmla v6.4s, %15.4s, v4.4s \n"
"fmla v7.4s, %24.4s, v4.4s \n"
"fmla v8.4s, %15.4s, v5.4s \n"
"fmla v9.4s, %24.4s, v5.4s \n"
"fmla v16.4s, %16.4s, v0.4s \n"
"fmla v17.4s, %25.4s, v0.4s \n"
"fmla v18.4s, %16.4s, v1.4s \n"
"fmla v19.4s, %25.4s, v1.4s \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v4.4s, v5.4s}, [%4] \n"// r24 r25
"fmla v6.4s, %16.4s, v2.4s \n"
"fmla v7.4s, %25.4s, v2.4s \n"
"fmla v8.4s, %16.4s, v3.4s \n"
"fmla v9.4s, %25.4s, v3.4s \n"
"fmla v16.4s, %17.4s, v1.4s \n"
"fmla v17.4s, %26.4s, v1.4s \n"
"fmla v18.4s, %17.4s, v2.4s \n"
"fmla v19.4s, %26.4s, v2.4s \n"
"fmla v6.4s, %17.4s, v3.4s \n"
"fmla v7.4s, %26.4s, v3.4s \n"
"fmla v8.4s, %17.4s, v4.4s \n"
"fmla v9.4s, %26.4s, v4.4s \n"
"fmla v16.4s, %18.4s, v2.4s \n"
"fmla v17.4s, %27.4s, v2.4s \n"
"fmla v18.4s, %18.4s, v3.4s \n"
"fmla v19.4s, %27.4s, v3.4s \n"
"fmla v6.4s, %18.4s, v4.4s \n"
"fmla v7.4s, %27.4s, v4.4s \n"
"fmla v8.4s, %18.4s, v5.4s \n"
"fmla v9.4s, %27.4s, v5.4s \n"
"ld1 {v0.4s}, [%0] \n"// sum00 sum01 sum02 sum03
"ld1 {v1.4s}, [%1] \n"// sum10 sum11 sum12 sum13
"faddp v16.4s, v16.4s, v16.4s \n"
"faddp v17.4s, v17.4s, v17.4s \n"
"faddp v18.4s, v18.4s, v18.4s \n"
"faddp v19.4s, v19.4s, v19.4s \n"
"faddp v6.4s, v6.4s, v6.4s \n"
"faddp v7.4s, v7.4s, v7.4s \n"
"faddp v8.4s, v8.4s, v8.4s \n"
"faddp v9.4s, v9.4s, v9.4s \n"
"faddp v16.2s, v16.2s, v18.2s \n"
"faddp v17.2s, v17.2s, v19.2s \n"
"faddp v6.2s, v6.2s, v8.2s \n"
"faddp v7.2s, v7.2s, v9.2s \n"
"trn1 v16.2d, v16.2d, v6.2d \n"
"trn1 v17.2d, v17.2d, v7.2d \n"
"fadd v0.4s, v0.4s, v16.4s \n"
"fadd v1.4s, v1.4s, v17.4s \n"
"st1 {v0.4s}, [%0], #16 \n"
"st1 {v1.4s}, [%1], #16 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0),
"1"(outptr1),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00_0), // %10
"w"(_k01_0), // %11
"w"(_k02_0), // %12
"w"(_k10_0), // %13
"w"(_k11_0), // %14
"w"(_k12_0), // %15
"w"(_k20_0), // %16
"w"(_k21_0), // %17
"w"(_k22_0), // %18
"w"(_k00_1), // %19
"w"(_k01_1), // %20
"w"(_k02_1), // %21
"w"(_k10_1), // %22
"w"(_k11_1), // %23
"w"(_k12_1), // %24
"w"(_k20_1), // %25
"w"(_k21_1), // %26
"w"(_k22_1) // %27
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v16", "v17", "v18", "v19"
);
}
for (; j+1<outw; j+=2)
{
asm volatile(
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2] \n"// r00 r01 r02 r03
"fmul v16.4s, %10.4s, v0.4s \n"
"fmul v17.4s, %19.4s, v0.4s \n"
"fmul v18.4s, %10.4s, v1.4s \n"
"fmul v19.4s, %19.4s, v1.4s \n"
"fmla v16.4s, %11.4s, v1.4s \n"
"fmla v17.4s, %20.4s, v1.4s \n"
"fmla v18.4s, %11.4s, v2.4s \n"
"fmla v19.4s, %20.4s, v2.4s \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3] \n"// r10 r11 r12 r12
"fmla v16.4s, %12.4s, v2.4s \n"
"fmla v17.4s, %21.4s, v2.4s \n"
"fmla v18.4s, %12.4s, v3.4s \n"
"fmla v19.4s, %21.4s, v3.4s \n"
"fmla v16.4s, %13.4s, v4.4s \n"
"fmla v17.4s, %22.4s, v4.4s \n"
"fmla v18.4s, %13.4s, v5.4s \n"
"fmla v19.4s, %22.4s, v5.4s \n"
"fmla v16.4s, %14.4s, v5.4s \n"
"fmla v17.4s, %23.4s, v5.4s \n"
"fmla v18.4s, %14.4s, v6.4s \n"
"fmla v19.4s, %23.4s, v6.4s \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%4] \n"// r20 r21 r22 r22
"fmla v16.4s, %15.4s, v6.4s \n"
"fmla v17.4s, %24.4s, v6.4s \n"
"fmla v18.4s, %15.4s, v7.4s \n"
"fmla v19.4s, %24.4s, v7.4s \n"
"fmla v16.4s, %16.4s, v0.4s \n"
"fmla v17.4s, %25.4s, v0.4s \n"
"fmla v18.4s, %16.4s, v1.4s \n"
"fmla v19.4s, %25.4s, v1.4s \n"
"fmla v16.4s, %17.4s, v1.4s \n"
"fmla v17.4s, %26.4s, v1.4s \n"
"fmla v18.4s, %17.4s, v2.4s \n"
"fmla v19.4s, %26.4s, v2.4s \n"
"fmla v16.4s, %18.4s, v2.4s \n"
"fmla v17.4s, %27.4s, v2.4s \n"
"fmla v18.4s, %18.4s, v3.4s \n"
"fmla v19.4s, %27.4s, v3.4s \n"
"ld1 {v4.2s}, [%0] \n"// sum00 sum01
"ld1 {v5.2s}, [%1] \n"// sum10 sum11
"faddp v16.4s, v16.4s, v16.4s \n"
"faddp v17.4s, v17.4s, v17.4s \n"
"faddp v18.4s, v18.4s, v18.4s \n"
"faddp v19.4s, v19.4s, v19.4s \n"
"add %2, %2, #32 \n"
"faddp v16.2s, v16.2s, v18.2s \n"
"faddp v17.2s, v17.2s, v19.2s \n"
"add %3, %3, #32 \n"
"fadd v4.2s, v4.2s, v16.2s \n"
"fadd v5.2s, v5.2s, v17.2s \n"
"add %4, %4, #32 \n"
"st1 {v4.2s}, [%0], #8 \n"
"st1 {v5.2s}, [%1], #8 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0),
"1"(outptr1),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00_0), // %10
"w"(_k01_0), // %11
"w"(_k02_0), // %12
"w"(_k10_0), // %13
"w"(_k11_0), // %14
"w"(_k12_0), // %15
"w"(_k20_0), // %16
"w"(_k21_0), // %17
"w"(_k22_0), // %18
"w"(_k00_1), // %19
"w"(_k01_1), // %20
"w"(_k02_1), // %21
"w"(_k10_1), // %22
"w"(_k11_1), // %23
"w"(_k12_1), // %24
"w"(_k20_1), // %25
"w"(_k21_1), // %26
"w"(_k22_1) // %27
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19"
);
}
for (; j<outw; j++)
{
asm volatile(
"prfm pldl1keep, [%2, #384] \n"
"ld1 {v0.4s, v1.4s, v2.4s}, [%2] \n"// r00 r01 r02
"fmul v16.4s, %10.4s, v0.4s \n"
"fmul v17.4s, %19.4s, v0.4s \n"
"fmul v18.4s, %11.4s, v1.4s \n"
"fmul v19.4s, %20.4s, v1.4s \n"
"prfm pldl1keep, [%3, #384] \n"
"ld1 {v3.4s, v4.4s, v5.4s}, [%3] \n"// r10 r11 r12
"fmla v16.4s, %12.4s, v2.4s \n"
"fmla v17.4s, %21.4s, v2.4s \n"
"fmla v18.4s, %13.4s, v3.4s \n"
"fmla v19.4s, %22.4s, v3.4s \n"
"fmla v16.4s, %14.4s, v4.4s \n"
"fmla v17.4s, %23.4s, v4.4s \n"
"prfm pldl1keep, [%4, #384] \n"
"ld1 {v0.4s, v1.4s, v2.4s}, [%4] \n"// r20 r21 r22
"fmla v18.4s, %15.4s, v5.4s \n"
"fmla v19.4s, %24.4s, v5.4s \n"
"fmla v16.4s, %16.4s, v0.4s \n"
"fmla v17.4s, %25.4s, v0.4s \n"
"fmla v18.4s, %17.4s, v1.4s \n"
"fmla v19.4s, %26.4s, v1.4s \n"
"fmla v16.4s, %18.4s, v2.4s \n"
"fmla v17.4s, %27.4s, v2.4s \n"
"ld1 {v3.s}[0], [%0] \n"// sum00
"ld1 {v4.s}[0], [%1] \n"// sum10
"fadd v16.4s, v16.4s, v18.4s \n"
"fadd v17.4s, v17.4s, v19.4s \n"
"add %2, %2, #16 \n"
"faddp v16.4s, v16.4s, v16.4s \n"
"faddp v17.4s, v17.4s, v17.4s \n"
"add %3, %3, #16 \n"
"faddp v16.2s, v16.2s, v16.2s \n"
"faddp v17.2s, v17.2s, v17.2s \n"
"add %4, %4, #16 \n"
"fadd v3.2s, v3.2s, v16.2s \n"
"fadd v4.2s, v4.2s, v17.2s \n"
"st1 {v3.s}[0], [%0], #4 \n"
"st1 {v4.s}[0], [%1], #4 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0),
"1"(outptr1),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00_0), // %10
"w"(_k01_0), // %11
"w"(_k02_0), // %12
"w"(_k10_0), // %13
"w"(_k11_0), // %14
"w"(_k12_0), // %15
"w"(_k20_0), // %16
"w"(_k21_0), // %17
"w"(_k22_0), // %18
"w"(_k00_1), // %19
"w"(_k01_1), // %20
"w"(_k02_1), // %21
"w"(_k10_1), // %22
"w"(_k11_1), // %23
"w"(_k12_1), // %24
"w"(_k20_1), // %25
"w"(_k21_1), // %26
"w"(_k22_1) // %27
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v16", "v17", "v18", "v19"
);
}
r0 += 2*4;
r1 += 2*4;
r2 += 2*4;
}
k0 += 9*4;
k1 += 9*4;
}
}
#endif // __ARM_NEON && __aarch64__
#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;
out0.fill(bias0);
const float* k0 = kernel.channel(p);
for (int q=0; q<inch; q++)
{
float* outptr0 = out0.row(0);
const Mat img0 = bottom_blob.channel(q);
const float* r0 = img0.row(0);
const float* r1 = img0.row(1);
const float* r2 = img0.row(2);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0+4);
float32x4_t _k02 = vld1q_f32(k0+8);
float32x4_t _k10 = vld1q_f32(k0+12);
float32x4_t _k11 = vld1q_f32(k0+16);
float32x4_t _k12 = vld1q_f32(k0+20);
float32x4_t _k20 = vld1q_f32(k0+24);
float32x4_t _k21 = vld1q_f32(k0+28);
float32x4_t _k22 = vld1q_f32(k0+32);
int i = 0;
for (; i < outh; i++)
{
int j = 0;
#if __aarch64__
for (; j+7<outw; j+=8)
{
asm volatile(
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n"// r00 r01 r02 r03
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n"// r04 r05 r06 r07
"fmul v16.4s, %8.4s, v0.4s \n"
"fmul v17.4s, %8.4s, v1.4s \n"
"fmul v18.4s, %8.4s, v2.4s \n"
"fmul v19.4s, %8.4s, v3.4s \n"
"fmul v20.4s, %8.4s, v4.4s \n"
"fmul v21.4s, %8.4s, v5.4s \n"
"fmul v22.4s, %8.4s, v6.4s \n"
"fmul v23.4s, %8.4s, v7.4s \n"
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v8.4s, v9.4s}, [%1] \n"// r08 r09
"fmla v16.4s, %9.4s, v1.4s \n"
"fmla v17.4s, %9.4s, v2.4s \n"
"fmla v18.4s, %9.4s, v3.4s \n"
"fmla v19.4s, %9.4s, v4.4s \n"
"fmla v20.4s, %9.4s, v5.4s \n"
"fmla v21.4s, %9.4s, v6.4s \n"
"fmla v22.4s, %9.4s, v7.4s \n"
"fmla v23.4s, %9.4s, v8.4s \n"
"fmla v16.4s, %10.4s, v2.4s \n"
"fmla v17.4s, %10.4s, v3.4s \n"
"fmla v18.4s, %10.4s, v4.4s \n"
"fmla v19.4s, %10.4s, v5.4s \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"// r10 r11 r12 r13
"fmla v20.4s, %10.4s, v6.4s \n"
"fmla v21.4s, %10.4s, v7.4s \n"
"fmla v22.4s, %10.4s, v8.4s \n"
"fmla v23.4s, %10.4s, v9.4s \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%2], #64 \n"// r14 r15 r16 r17
"fmla v16.4s, %11.4s, v0.4s \n"
"fmla v17.4s, %11.4s, v1.4s \n"
"fmla v18.4s, %11.4s, v2.4s \n"
"fmla v19.4s, %11.4s, v3.4s \n"
"fmla v20.4s, %11.4s, v4.4s \n"
"fmla v21.4s, %11.4s, v5.4s \n"
"fmla v22.4s, %11.4s, v6.4s \n"
"fmla v23.4s, %11.4s, v7.4s \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v8.4s, v9.4s}, [%2] \n"// r18 r19
"fmla v16.4s, %12.4s, v1.4s \n"
"fmla v17.4s, %12.4s, v2.4s \n"
"fmla v18.4s, %12.4s, v3.4s \n"
"fmla v19.4s, %12.4s, v4.4s \n"
"fmla v20.4s, %12.4s, v5.4s \n"
"fmla v21.4s, %12.4s, v6.4s \n"
"fmla v22.4s, %12.4s, v7.4s \n"
"fmla v23.4s, %12.4s, v8.4s \n"
"fmla v16.4s, %13.4s, v2.4s \n"
"fmla v17.4s, %13.4s, v3.4s \n"
"fmla v18.4s, %13.4s, v4.4s \n"
"fmla v19.4s, %13.4s, v5.4s \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"// r20 r21 r22 r23
"fmla v20.4s, %13.4s, v6.4s \n"
"fmla v21.4s, %13.4s, v7.4s \n"
"fmla v22.4s, %13.4s, v8.4s \n"
"fmla v23.4s, %13.4s, v9.4s \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n"// r24 r25 r26 r27
"fmla v16.4s, %14.4s, v0.4s \n"
"fmla v17.4s, %14.4s, v1.4s \n"
"fmla v18.4s, %14.4s, v2.4s \n"
"fmla v19.4s, %14.4s, v3.4s \n"
"fmla v20.4s, %14.4s, v4.4s \n"
"fmla v21.4s, %14.4s, v5.4s \n"
"fmla v22.4s, %14.4s, v6.4s \n"
"fmla v23.4s, %14.4s, v7.4s \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v8.4s, v9.4s}, [%3] \n"// r28 r29
"fmla v16.4s, %15.4s, v1.4s \n"
"fmla v17.4s, %15.4s, v2.4s \n"
"fmla v18.4s, %15.4s, v3.4s \n"
"fmla v19.4s, %15.4s, v4.4s \n"
"fmla v20.4s, %15.4s, v5.4s \n"
"fmla v21.4s, %15.4s, v6.4s \n"
"fmla v22.4s, %15.4s, v7.4s \n"
"fmla v23.4s, %15.4s, v8.4s \n"
"fmla v16.4s, %16.4s, v2.4s \n"
"fmla v17.4s, %16.4s, v3.4s \n"
"fmla v18.4s, %16.4s, v4.4s \n"
"fmla v19.4s, %16.4s, v5.4s \n"
"fmla v20.4s, %16.4s, v6.4s \n"
"fmla v21.4s, %16.4s, v7.4s \n"
"fmla v22.4s, %16.4s, v8.4s \n"
"fmla v23.4s, %16.4s, v9.4s \n"
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v0.4s, v1.4s}, [%0] \n"// sum0 sum1 sum2 sum3 sum4 sum5 sum6 sum7
"faddp v16.4s, v16.4s, v17.4s \n"
"faddp v18.4s, v18.4s, v19.4s \n"
"faddp v20.4s, v20.4s, v21.4s \n"
"faddp v22.4s, v22.4s, v23.4s \n"
"faddp v16.4s, v16.4s, v18.4s \n"
"faddp v20.4s, v20.4s, v22.4s \n"
"fadd v0.4s, v0.4s, v16.4s \n"
"fadd v1.4s, v1.4s, v20.4s \n"
"st1 {v0.4s, v1.4s}, [%0], #32 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"
);
}
#endif // __aarch64__
for (; j+3<outw; j+=4)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n"// r00 r01 r02 r03
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v8.4s, v9.4s}, [%1] \n"// r04 r05
"fmul v16.4s, %8.4s, v0.4s \n"
"fmul v17.4s, %8.4s, v1.4s \n"
"fmul v18.4s, %8.4s, v2.4s \n"
"fmul v19.4s, %8.4s, v3.4s \n"
"fmla v16.4s, %9.4s, v1.4s \n"
"fmla v17.4s, %9.4s, v2.4s \n"
"fmla v18.4s, %9.4s, v3.4s \n"
"fmla v19.4s, %9.4s, v8.4s \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%2], #64 \n"// r10 r11 r12 r13
"fmla v16.4s, %10.4s, v2.4s \n"
"fmla v17.4s, %10.4s, v3.4s \n"
"fmla v18.4s, %10.4s, v8.4s \n"
"fmla v19.4s, %10.4s, v9.4s \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v8.4s, v9.4s}, [%2] \n"// r14 r15
"fmla v16.4s, %11.4s, v4.4s \n"
"fmla v17.4s, %11.4s, v5.4s \n"
"fmla v18.4s, %11.4s, v6.4s \n"
"fmla v19.4s, %11.4s, v7.4s \n"
"fmla v16.4s, %12.4s, v5.4s \n"
"fmla v17.4s, %12.4s, v6.4s \n"
"fmla v18.4s, %12.4s, v7.4s \n"
"fmla v19.4s, %12.4s, v8.4s \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"// r20 r21 r22 r23
"fmla v16.4s, %13.4s, v6.4s \n"
"fmla v17.4s, %13.4s, v7.4s \n"
"fmla v18.4s, %13.4s, v8.4s \n"
"fmla v19.4s, %13.4s, v9.4s \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v8.4s, v9.4s}, [%3] \n"// r24 r25
"fmla v16.4s, %14.4s, v0.4s \n"
"fmla v17.4s, %14.4s, v1.4s \n"
"fmla v18.4s, %14.4s, v2.4s \n"
"fmla v19.4s, %14.4s, v3.4s \n"
"fmla v16.4s, %15.4s, v1.4s \n"
"fmla v17.4s, %15.4s, v2.4s \n"
"fmla v18.4s, %15.4s, v3.4s \n"
"fmla v19.4s, %15.4s, v8.4s \n"
"fmla v16.4s, %16.4s, v2.4s \n"
"fmla v17.4s, %16.4s, v3.4s \n"
"fmla v18.4s, %16.4s, v8.4s \n"
"fmla v19.4s, %16.4s, v9.4s \n"
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v0.4s}, [%0] \n"// sum0 sum1 sum2 sum3
"faddp v16.4s, v16.4s, v17.4s \n"
"faddp v18.4s, v18.4s, v19.4s \n"
"faddp v16.4s, v16.4s, v18.4s \n"
"fadd v0.4s, v0.4s, v16.4s \n"
"st1 {v0.4s}, [%0], #16 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v16", "v17", "v18", "v19"
);
#else // __aarch64__
asm volatile(
"pld [%1, #256] \n"
"vld1.f32 {d0-d3}, [%1 :128]! \n"// r00 r01
"vmul.f32 q3, %q8, q0 \n"
"pld [%1, #128] \n"
"vld1.f32 {d4-d5}, [%1 :128]! \n"// r02
"vmul.f32 q4, %q8, q1 \n"
"vmla.f32 q3, %q9, q1 \n"
"pld [%1, #256] \n"
"vld1.f32 {d0-d3}, [%1 :128]! \n"// r03 r04
"vmul.f32 q5, %q8, q2 \n"
"vmla.f32 q4, %q9, q2 \n"
"vmla.f32 q3, %q10, q2 \n"
"vmul.f32 q6, %q8, q0 \n"
"vmla.f32 q5, %q9, q0 \n"
"vmla.f32 q4, %q10, q0 \n"
"pld [%1, #128] \n"
"vld1.f32 {d4-d5}, [%1 :128] \n"// r05
"vmla.f32 q6, %q9, q1 \n"
"vmla.f32 q5, %q10, q1 \n"
"pld [%2, #256] \n"
"vld1.f32 {d0-d3}, [%2 :128]! \n"// r10 r11
"vmla.f32 q6, %q10, q2 \n"
"vmla.f32 q3, %q11, q0 \n"
"pld [%2, #128] \n"
"vld1.f32 {d4-d5}, [%2 :128]! \n"// r12
"vmla.f32 q4, %q11, q1 \n"
"vmla.f32 q3, %q12, q1 \n"
"pld [%2, #256] \n"
"vld1.f32 {d0-d3}, [%2 :128]! \n"// r13 r14
"vmla.f32 q5, %q11, q2 \n"
"vmla.f32 q4, %q12, q2 \n"
"vmla.f32 q3, %q13, q2 \n"
"vmla.f32 q6, %q11, q0 \n"
"vmla.f32 q5, %q12, q0 \n"
"vmla.f32 q4, %q13, q0 \n"
"pld [%2, #128] \n"
"vld1.f32 {d4-d5}, [%2 :128] \n"// r15
"vmla.f32 q6, %q12, q1 \n"
"vmla.f32 q5, %q13, q1 \n"
"pld [%3, #256] \n"
"vld1.f32 {d0-d3}, [%3 :128]! \n"// r20 r21
"vmla.f32 q6, %q13, q2 \n"
"vmla.f32 q3, %q14, q0 \n"
"pld [%3, #128] \n"
"vld1.f32 {d4-d5}, [%3 :128]! \n"// r22
"vmla.f32 q4, %q14, q1 \n"
"vmla.f32 q3, %q15, q1 \n"
"pld [%3, #256] \n"
"vld1.f32 {d0-d3}, [%3 :128]! \n"// r23 r24
"vmla.f32 q5, %q14, q2 \n"
"vmla.f32 q4, %q15, q2 \n"
"vmla.f32 q3, %q16, q2 \n"
"vmla.f32 q6, %q14, q0 \n"
"vmla.f32 q5, %q15, q0 \n"
"vmla.f32 q4, %q16, q0 \n"
"pld [%3, #128] \n"
"vld1.f32 {d4-d5}, [%3 :128] \n"// r25
"vmla.f32 q6, %q15, q1 \n"
"vmla.f32 q5, %q16, q1 \n"
"vld1.f32 {d0-d1}, [%0] \n"// sum0 sum1 sum2 sum3
"vmla.f32 q6, %q16, q2 \n"
"vadd.f32 d6, d6, d7 \n"
"vadd.f32 d8, d8, d9 \n"
"vadd.f32 d10, d10, d11 \n"
"vadd.f32 d12, d12, d13 \n"
"sub %1, %1, #16 \n"
"vpadd.f32 d6, d6, d8 \n"
"vpadd.f32 d7, d10, d12 \n"
"sub %2, %2, #16 \n"
"vadd.f32 q0, q0, q3 \n"
"sub %3, %3, #16 \n"
"vst1.f32 {d0-d1}, [%0]! \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6"
);
#endif // __aarch64__
}
for (; j+1<outw; j+=2)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1] \n"// r00 r01 r02 r03
"fmul v16.4s, %8.4s, v0.4s \n"
"fmul v17.4s, %8.4s, v1.4s \n"
"fmul v18.4s, %9.4s, v1.4s \n"
"fmul v19.4s, %9.4s, v2.4s \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%2] \n"// r10 r11 r12 r13
"fmla v16.4s, %10.4s, v2.4s \n"
"fmla v17.4s, %10.4s, v3.4s \n"
"fmla v18.4s, %11.4s, v4.4s \n"
"fmla v19.4s, %11.4s, v5.4s \n"
"fmla v16.4s, %12.4s, v5.4s \n"
"fmla v17.4s, %12.4s, v6.4s \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3] \n"// r20 r21 r22 r23
"fmla v18.4s, %13.4s, v6.4s \n"
"fmla v19.4s, %13.4s, v7.4s \n"
"fmla v16.4s, %14.4s, v0.4s \n"
"fmla v17.4s, %14.4s, v1.4s \n"
"fmla v18.4s, %15.4s, v1.4s \n"
"fmla v19.4s, %15.4s, v2.4s \n"
"fmla v16.4s, %16.4s, v2.4s \n"
"fmla v17.4s, %16.4s, v3.4s \n"
"ld1 {v0.2s}, [%0] \n"// sum0 sum1
"fadd v16.4s, v16.4s, v18.4s \n"
"fadd v17.4s, v17.4s, v19.4s \n"
"add %1, %1, #32 \n"
"faddp v16.4s, v16.4s, v17.4s \n"
"add %2, %2, #32 \n"
"faddp v16.4s, v16.4s, v16.4s \n"
"add %3, %3, #32 \n"
"fadd v0.2s, v0.2s, v16.2s \n"
"st1 {v0.2s}, [%0], #8 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19"
);
#else // __aarch64__
asm volatile(
"pld [%1, #256] \n"
"vld1.f32 {d0-d3}, [%1 :128]! \n"// r00 r01
"vmul.f32 q5, %q8, q0 \n"
"vmul.f32 q6, %q8, q1 \n"
"vmul.f32 q2, %q9, q1 \n"
"pld [%1, #256] \n"
"vld1.f32 {d0-d3}, [%1 :128] \n"// r02 r03
"vmul.f32 q3, %q9, q0 \n"
"vmla.f32 q5, %q10, q0 \n"
"vmla.f32 q6, %q10, q1 \n"
"pld [%2, #256] \n"
"vld1.f32 {d0-d3}, [%2 :128]! \n"// r10 r11
"vmla.f32 q2, %q11, q0 \n"
"vmla.f32 q3, %q11, q1 \n"
"vmla.f32 q5, %q12, q1 \n"
"pld [%2, #256] \n"
"vld1.f32 {d0-d3}, [%2 :128] \n"// r12 r13
"vmla.f32 q6, %q12, q0 \n"
"vmla.f32 q2, %q13, q0 \n"
"vmla.f32 q3, %q13, q1 \n"
"pld [%3, #256] \n"
"vld1.f32 {d0-d3}, [%3 :128]! \n"// r20 r21
"vmla.f32 q5, %q14, q0 \n"
"vmla.f32 q6, %q14, q1 \n"
"vmla.f32 q2, %q15, q1 \n"
"pld [%3, #256] \n"
"vld1.f32 {d0-d3}, [%3 :128] \n"// r22 r23
"vmla.f32 q3, %q15, q0 \n"
"vmla.f32 q5, %q16, q0 \n"
"vmla.f32 q6, %q16, q1 \n"
"vld1.f32 {d8}, [%0] \n"// sum0 sum1
"vadd.f32 q5, q5, q2 \n"
"vadd.f32 q6, q6, q3 \n"
"vadd.f32 d10, d10, d11 \n"
"vadd.f32 d12, d12, d13 \n"
"vpadd.f32 d10, d10, d12 \n"
"vadd.f32 d8, d8, d10 \n"
"vst1.f32 {d8}, [%0]! \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6"
);
#endif // __aarch64__
}
for (; j<outw; j++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%1, #384] \n"
"ld1 {v0.4s, v1.4s, v2.4s}, [%1] \n"// r00 r01 r02
"eor v16.16b, v16.16b, v16.16b \n"
"ld1 {v16.s}[0], [%0] \n"// sum0
"fmul v17.4s, %8.4s, v0.4s \n"
"fmul v18.4s, %9.4s, v1.4s \n"
"prfm pldl1keep, [%2, #384] \n"
"ld1 {v3.4s, v4.4s, v5.4s}, [%2] \n"// r10 r11 r12
"fmla v16.4s, %10.4s, v2.4s \n"
"fmla v17.4s, %11.4s, v3.4s \n"
"fmla v18.4s, %12.4s, v4.4s \n"
"prfm pldl1keep, [%3, #384] \n"
"ld1 {v0.4s, v1.4s, v2.4s}, [%3] \n"// r20 r21 r22
"fmla v16.4s, %13.4s, v5.4s \n"
"fmla v17.4s, %14.4s, v0.4s \n"
"fmla v18.4s, %15.4s, v1.4s \n"
"fmla v16.4s, %16.4s, v2.4s \n"
"fadd v17.4s, v17.4s, v18.4s \n"
"fadd v16.4s, v16.4s, v17.4s \n"
"add %1, %1, #16 \n"
"faddp v16.4s, v16.4s, v16.4s \n"
"add %2, %2, #16 \n"
"faddp v16.2s, v16.2s, v16.2s \n"
"add %3, %3, #16 \n"
"st1 {v16.s}[0], [%0], #4 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v16", "v17", "v18"
);
#else // __aarch64__
asm volatile(
"pld [%1, #384] \n"
"vldm %1, {d0-d5} \n"// r00 r01 r02
"veor q3, q3 \n"
"vld1.f32 {d6[0]}, [%0] \n"// sum0
"vmul.f32 q4, %q8, q0 \n"
"vmul.f32 q5, %q9, q1 \n"
"vmla.f32 q3, %q10, q2 \n"
"pld [%2, #384] \n"
"vldm %2, {d0-d5} \n"// r10 r11 r12
"vmla.f32 q4, %q11, q0 \n"
"vmla.f32 q5, %q12, q1 \n"
"vmla.f32 q3, %q13, q2 \n"
"pld [%3, #384] \n"
"vldm %3, {d0-d5} \n"// r20 r21 r22
"vmla.f32 q4, %q14, q0 \n"
"vmla.f32 q5, %q15, q1 \n"
"vmla.f32 q3, %q16, q2 \n"
"vadd.f32 q4, q4, q5 \n"
"vadd.f32 q3, q3, q4 \n"
"add %1, %1, #16 \n"
"vadd.f32 d6, d6, d7 \n"
"add %2, %2, #16 \n"
"vpadd.f32 d6, d6, d6 \n"
"add %3, %3, #16 \n"
"vst1.f32 {d6[0]}, [%0]! \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "q0", "q1", "q2", "q3", "q4", "q5"
);
#endif // __aarch64__
}
r0 += 2*4;
r1 += 2*4;
r2 += 2*4;
}
k0 += 9*4;
}
}
}
|
threading_utils.h | /*!
* Copyright 2015-2019 by Contributors
* \file common.h
* \brief Threading utilities
*/
#ifndef XGBOOST_COMMON_THREADING_UTILS_H_
#define XGBOOST_COMMON_THREADING_UTILS_H_
#include <dmlc/common.h>
#include <vector>
#include <algorithm>
#include "xgboost/logging.h"
namespace xgboost {
namespace common {
// Represent simple range of indexes [begin, end)
// Inspired by tbb::blocked_range
class Range1d {
public:
Range1d(size_t begin, size_t end): begin_(begin), end_(end) {
CHECK_LT(begin, end);
}
size_t begin() const { // NOLINT
return begin_;
}
size_t end() const { // NOLINT
return end_;
}
private:
size_t begin_;
size_t end_;
};
// Split 2d space to balanced blocks
// Implementation of the class is inspired by tbb::blocked_range2d
// However, TBB provides only (n x m) 2d range (matrix) separated by blocks. Example:
// [ 1,2,3 ]
// [ 4,5,6 ]
// [ 7,8,9 ]
// But the class is able to work with different sizes in each 'row'. Example:
// [ 1,2 ]
// [ 3,4,5,6 ]
// [ 7,8,9]
// If grain_size is 2: It produces following blocks:
// [1,2], [3,4], [5,6], [7,8], [9]
// The class helps to process data in several tree nodes (non-balanced usually) in parallel
// Using nested parallelism (by nodes and by data in each node)
// it helps to improve CPU resources utilization
class BlockedSpace2d {
public:
// Example of space:
// [ 1,2 ]
// [ 3,4,5,6 ]
// [ 7,8,9]
// BlockedSpace2d will create following blocks (tasks) if grain_size=2:
// 1-block: first_dimension = 0, range of indexes in a 'row' = [0,2) (includes [1,2] values)
// 2-block: first_dimension = 1, range of indexes in a 'row' = [0,2) (includes [3,4] values)
// 3-block: first_dimension = 1, range of indexes in a 'row' = [2,4) (includes [5,6] values)
// 4-block: first_dimension = 2, range of indexes in a 'row' = [0,2) (includes [7,8] values)
// 5-block: first_dimension = 2, range of indexes in a 'row' = [2,3) (includes [9] values)
// Arguments:
// dim1 - size of the first dimension in the space
// getter_size_dim2 - functor to get the second dimensions for each 'row' by row-index
// grain_size - max size of produced blocks
template<typename Func>
BlockedSpace2d(size_t dim1, Func getter_size_dim2, size_t grain_size) {
for (size_t i = 0; i < dim1; ++i) {
const size_t size = getter_size_dim2(i);
const size_t n_blocks = size/grain_size + !!(size % grain_size);
for (size_t iblock = 0; iblock < n_blocks; ++iblock) {
const size_t begin = iblock * grain_size;
const size_t end = std::min(begin + grain_size, size);
AddBlock(i, begin, end);
}
}
}
// Amount of blocks(tasks) in a space
size_t Size() const {
return ranges_.size();
}
// get index of the first dimension of i-th block(task)
size_t GetFirstDimension(size_t i) const {
CHECK_LT(i, first_dimension_.size());
return first_dimension_[i];
}
// get a range of indexes for the second dimension of i-th block(task)
Range1d GetRange(size_t i) const {
CHECK_LT(i, ranges_.size());
return ranges_[i];
}
private:
void AddBlock(size_t first_dimension, size_t begin, size_t end) {
first_dimension_.push_back(first_dimension);
ranges_.emplace_back(begin, end);
}
std::vector<Range1d> ranges_;
std::vector<size_t> first_dimension_;
};
// Wrapper to implement nested parallelism with simple omp parallel for
template <typename Func>
void ParallelFor2d(const BlockedSpace2d& space, int nthreads, Func func) {
const size_t num_blocks_in_space = space.Size();
nthreads = std::min(nthreads, omp_get_max_threads());
nthreads = std::max(nthreads, 1);
dmlc::OMPException omp_exc;
#pragma omp parallel num_threads(nthreads)
{
omp_exc.Run(
[](size_t num_blocks_in_space, const BlockedSpace2d& space, int nthreads, Func func) {
size_t tid = omp_get_thread_num();
size_t chunck_size =
num_blocks_in_space / nthreads + !!(num_blocks_in_space % nthreads);
size_t begin = chunck_size * tid;
size_t end = std::min(begin + chunck_size, num_blocks_in_space);
for (auto i = begin; i < end; i++) {
func(space.GetFirstDimension(i), space.GetRange(i));
}
}, num_blocks_in_space, space, nthreads, func);
}
omp_exc.Rethrow();
}
template <typename Func>
void ParallelFor(size_t size, size_t nthreads, Func fn) {
dmlc::OMPException omp_exc;
#pragma omp parallel for num_threads(nthreads)
for (omp_ulong i = 0; i < size; ++i) {
omp_exc.Run(fn, i);
}
omp_exc.Rethrow();
}
/* \brief Configure parallel threads.
*
* \param p_threads Number of threads, when it's less than or equal to 0, this function
* will change it to number of process on system.
*
* \return Global openmp max threads before configuration.
*/
inline int32_t OmpSetNumThreads(int32_t* p_threads) {
auto& threads = *p_threads;
int32_t nthread_original = omp_get_max_threads();
if (threads <= 0) {
threads = omp_get_num_procs();
}
omp_set_num_threads(threads);
return nthread_original;
}
inline int32_t OmpSetNumThreadsWithoutHT(int32_t* p_threads) {
auto& threads = *p_threads;
int32_t nthread_original = omp_get_max_threads();
if (threads <= 0) {
threads = nthread_original;
}
omp_set_num_threads(threads);
return nthread_original;
}
} // namespace common
} // namespace xgboost
#endif // XGBOOST_COMMON_THREADING_UTILS_H_
|
GB_binop__pair_fp64.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__pair_fp64
// A.*B function (eWiseMult): GB_AemultB__pair_fp64
// A*D function (colscale): GB_AxD__pair_fp64
// D*A function (rowscale): GB_DxB__pair_fp64
// C+=B function (dense accum): GB_Cdense_accumB__pair_fp64
// C+=b function (dense accum): GB_Cdense_accumb__pair_fp64
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__pair_fp64
// C=scalar+B (none)
// C=scalar+B' (none)
// C=A+scalar (none)
// C=A'+scalar (none)
// C type: double
// A type: double
// B,b type: double
// BinaryOp: cij = 1
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// 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) \
;
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
;
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
double 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 = 1 ;
// 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_PAIR || GxB_NO_FP64 || GxB_NO_PAIR_FP64)
//------------------------------------------------------------------------------
// 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__pair_fp64
(
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__pair_fp64
(
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__pair_fp64
(
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 double
double bwork = (*((double *) 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__pair_fp64
(
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
double *GB_RESTRICT Cx = (double *) 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__pair_fp64
(
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
double *GB_RESTRICT Cx = (double *) 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__pair_fp64
(
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__pair_fp64
(
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
//------------------------------------------------------------------------------
#if 0
GrB_Info (none)
(
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
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) 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 ;
; ;
Cx [p] = 1 ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
#if 0
GrB_Info (none)
(
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 ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
; ;
Cx [p] = 1 ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = 1 ; \
}
GrB_Info (none)
(
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 \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
#endif
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = 1 ; \
}
GrB_Info (none)
(
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
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
#endif
|
feature.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF EEEEE AAA TTTTT U U RRRR EEEEE %
% F E A A T U U R R E %
% FFF EEE AAAAA T U U RRRR EEE %
% F E A A T U U R R E %
% F EEEEE A A T UUU R R EEEEE %
% %
% %
% MagickCore Image Feature Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/animate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/compress.h"
#include "MagickCore/constitute.h"
#include "MagickCore/display.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/feature.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/list.h"
#include "MagickCore/image-private.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/matrix.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/morphology-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/signature-private.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/timer.h"
#include "MagickCore/utility.h"
#include "MagickCore/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C a n n y E d g e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CannyEdgeImage() uses a multi-stage algorithm to detect a wide range of
% edges in images.
%
% The format of the CannyEdgeImage method is:
%
% Image *CannyEdgeImage(const Image *image,const double radius,
% const double sigma,const double lower_percent,
% const double upper_percent,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the gaussian smoothing filter.
%
% o sigma: the sigma of the gaussian smoothing filter.
%
% o lower_precent: percentage of edge pixels in the lower threshold.
%
% o upper_percent: percentage of edge pixels in the upper threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _CannyInfo
{
double
magnitude,
intensity;
int
orientation;
ssize_t
x,
y;
} CannyInfo;
static inline MagickBooleanType IsAuthenticPixel(const Image *image,
const ssize_t x,const ssize_t y)
{
if ((x < 0) || (x >= (ssize_t) image->columns))
return(MagickFalse);
if ((y < 0) || (y >= (ssize_t) image->rows))
return(MagickFalse);
return(MagickTrue);
}
static MagickBooleanType TraceEdges(Image *edge_image,CacheView *edge_view,
MatrixInfo *canny_cache,const ssize_t x,const ssize_t y,
const double lower_threshold,ExceptionInfo *exception)
{
CannyInfo
edge,
pixel;
MagickBooleanType
status;
register Quantum
*q;
register ssize_t
i;
q=GetCacheViewAuthenticPixels(edge_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
return(MagickFalse);
*q=QuantumRange;
status=SyncCacheViewAuthenticPixels(edge_view,exception);
if (status == MagickFalse)
return(MagickFalse);;
if (GetMatrixElement(canny_cache,0,0,&edge) == MagickFalse)
return(MagickFalse);
edge.x=x;
edge.y=y;
if (SetMatrixElement(canny_cache,0,0,&edge) == MagickFalse)
return(MagickFalse);
for (i=1; i != 0; )
{
ssize_t
v;
i--;
status=GetMatrixElement(canny_cache,i,0,&edge);
if (status == MagickFalse)
return(MagickFalse);
for (v=(-1); v <= 1; v++)
{
ssize_t
u;
for (u=(-1); u <= 1; u++)
{
if ((u == 0) && (v == 0))
continue;
if (IsAuthenticPixel(edge_image,edge.x+u,edge.y+v) == MagickFalse)
continue;
/*
Not an edge if gradient value is below the lower threshold.
*/
q=GetCacheViewAuthenticPixels(edge_view,edge.x+u,edge.y+v,1,1,
exception);
if (q == (Quantum *) NULL)
return(MagickFalse);
status=GetMatrixElement(canny_cache,edge.x+u,edge.y+v,&pixel);
if (status == MagickFalse)
return(MagickFalse);
if ((GetPixelIntensity(edge_image,q) == 0.0) &&
(pixel.intensity >= lower_threshold))
{
*q=QuantumRange;
status=SyncCacheViewAuthenticPixels(edge_view,exception);
if (status == MagickFalse)
return(MagickFalse);
edge.x+=u;
edge.y+=v;
status=SetMatrixElement(canny_cache,i,0,&edge);
if (status == MagickFalse)
return(MagickFalse);
i++;
}
}
}
}
return(MagickTrue);
}
MagickExport Image *CannyEdgeImage(const Image *image,const double radius,
const double sigma,const double lower_percent,const double upper_percent,
ExceptionInfo *exception)
{
#define CannyEdgeImageTag "CannyEdge/Image"
CacheView
*edge_view;
CannyInfo
element;
char
geometry[MagickPathExtent];
double
lower_threshold,
max,
min,
upper_threshold;
Image
*edge_image;
KernelInfo
*kernel_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MatrixInfo
*canny_cache;
ssize_t
y;
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);
/*
Filter out noise.
*/
(void) FormatLocaleString(geometry,MagickPathExtent,
"blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma);
kernel_info=AcquireKernelInfo(geometry,exception);
if (kernel_info == (KernelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
edge_image=ConvolveImage(image, kernel_info, exception);
kernel_info=DestroyKernelInfo(kernel_info);
if (edge_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageColorspace(edge_image,GRAYColorspace,exception) == MagickFalse)
{
edge_image=DestroyImage(edge_image);
return((Image *) NULL);
}
(void) SetImageAlphaChannel(edge_image,OffAlphaChannel,exception);
/*
Find the intensity gradient of the image.
*/
canny_cache=AcquireMatrixInfo(edge_image->columns,edge_image->rows,
sizeof(CannyInfo),exception);
if (canny_cache == (MatrixInfo *) NULL)
{
edge_image=DestroyImage(edge_image);
return((Image *) NULL);
}
status=MagickTrue;
edge_view=AcquireVirtualCacheView(edge_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(edge_image,edge_image,edge_image->rows,1)
#endif
for (y=0; y < (ssize_t) edge_image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns+1,2,
exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) edge_image->columns; x++)
{
CannyInfo
pixel;
double
dx,
dy;
register const Quantum
*magick_restrict kernel_pixels;
ssize_t
v;
static double
Gx[2][2] =
{
{ -1.0, +1.0 },
{ -1.0, +1.0 }
},
Gy[2][2] =
{
{ +1.0, +1.0 },
{ -1.0, -1.0 }
};
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
dx=0.0;
dy=0.0;
kernel_pixels=p;
for (v=0; v < 2; v++)
{
ssize_t
u;
for (u=0; u < 2; u++)
{
double
intensity;
intensity=GetPixelIntensity(edge_image,kernel_pixels+u);
dx+=0.5*Gx[v][u]*intensity;
dy+=0.5*Gy[v][u]*intensity;
}
kernel_pixels+=edge_image->columns+1;
}
pixel.magnitude=hypot(dx,dy);
pixel.orientation=0;
if (fabs(dx) > MagickEpsilon)
{
double
slope;
slope=dy/dx;
if (slope < 0.0)
{
if (slope < -2.41421356237)
pixel.orientation=0;
else
if (slope < -0.414213562373)
pixel.orientation=1;
else
pixel.orientation=2;
}
else
{
if (slope > 2.41421356237)
pixel.orientation=0;
else
if (slope > 0.414213562373)
pixel.orientation=3;
else
pixel.orientation=2;
}
}
if (SetMatrixElement(canny_cache,x,y,&pixel) == MagickFalse)
continue;
p+=GetPixelChannels(edge_image);
}
}
edge_view=DestroyCacheView(edge_view);
/*
Non-maxima suppression, remove pixels that are not considered to be part
of an edge.
*/
progress=0;
(void) GetMatrixElement(canny_cache,0,0,&element);
max=element.intensity;
min=element.intensity;
edge_view=AcquireAuthenticCacheView(edge_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(edge_image,edge_image,edge_image->rows,1)
#endif
for (y=0; y < (ssize_t) edge_image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(edge_view,0,y,edge_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) edge_image->columns; x++)
{
CannyInfo
alpha_pixel,
beta_pixel,
pixel;
(void) GetMatrixElement(canny_cache,x,y,&pixel);
switch (pixel.orientation)
{
case 0:
default:
{
/*
0 degrees, north and south.
*/
(void) GetMatrixElement(canny_cache,x,y-1,&alpha_pixel);
(void) GetMatrixElement(canny_cache,x,y+1,&beta_pixel);
break;
}
case 1:
{
/*
45 degrees, northwest and southeast.
*/
(void) GetMatrixElement(canny_cache,x-1,y-1,&alpha_pixel);
(void) GetMatrixElement(canny_cache,x+1,y+1,&beta_pixel);
break;
}
case 2:
{
/*
90 degrees, east and west.
*/
(void) GetMatrixElement(canny_cache,x-1,y,&alpha_pixel);
(void) GetMatrixElement(canny_cache,x+1,y,&beta_pixel);
break;
}
case 3:
{
/*
135 degrees, northeast and southwest.
*/
(void) GetMatrixElement(canny_cache,x+1,y-1,&beta_pixel);
(void) GetMatrixElement(canny_cache,x-1,y+1,&alpha_pixel);
break;
}
}
pixel.intensity=pixel.magnitude;
if ((pixel.magnitude < alpha_pixel.magnitude) ||
(pixel.magnitude < beta_pixel.magnitude))
pixel.intensity=0;
(void) SetMatrixElement(canny_cache,x,y,&pixel);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CannyEdgeImage)
#endif
{
if (pixel.intensity < min)
min=pixel.intensity;
if (pixel.intensity > max)
max=pixel.intensity;
}
*q=0;
q+=GetPixelChannels(edge_image);
}
if (SyncCacheViewAuthenticPixels(edge_view,exception) == MagickFalse)
status=MagickFalse;
}
edge_view=DestroyCacheView(edge_view);
/*
Estimate hysteresis threshold.
*/
lower_threshold=lower_percent*(max-min)+min;
upper_threshold=upper_percent*(max-min)+min;
/*
Hysteresis threshold.
*/
edge_view=AcquireAuthenticCacheView(edge_image,exception);
for (y=0; y < (ssize_t) edge_image->rows; y++)
{
register ssize_t
x;
if (status == MagickFalse)
continue;
for (x=0; x < (ssize_t) edge_image->columns; x++)
{
CannyInfo
pixel;
register const Quantum
*magick_restrict p;
/*
Edge if pixel gradient higher than upper threshold.
*/
p=GetCacheViewVirtualPixels(edge_view,x,y,1,1,exception);
if (p == (const Quantum *) NULL)
continue;
status=GetMatrixElement(canny_cache,x,y,&pixel);
if (status == MagickFalse)
continue;
if ((GetPixelIntensity(edge_image,p) == 0.0) &&
(pixel.intensity >= upper_threshold))
status=TraceEdges(edge_image,edge_view,canny_cache,x,y,lower_threshold,
exception);
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CannyEdgeImage)
#endif
proceed=SetImageProgress(image,CannyEdgeImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
edge_view=DestroyCacheView(edge_view);
/*
Free resources.
*/
canny_cache=DestroyMatrixInfo(canny_cache);
return(edge_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e F e a t u r e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageFeatures() returns features for each channel in the image in
% each of four directions (horizontal, vertical, left and right diagonals)
% for the specified distance. The features include the angular second
% moment, contrast, correlation, sum of squares: variance, inverse difference
% moment, sum average, sum varience, sum entropy, entropy, difference variance,% difference entropy, information measures of correlation 1, information
% measures of correlation 2, and maximum correlation coefficient. You can
% access the red channel contrast, for example, like this:
%
% channel_features=GetImageFeatures(image,1,exception);
% contrast=channel_features[RedPixelChannel].contrast[0];
%
% Use MagickRelinquishMemory() to free the features buffer.
%
% The format of the GetImageFeatures method is:
%
% ChannelFeatures *GetImageFeatures(const Image *image,
% const size_t distance,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o distance: the distance.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickLog10(const double x)
{
#define Log10Epsilon (1.0e-11)
if (fabs(x) < Log10Epsilon)
return(log10(Log10Epsilon));
return(log10(fabs(x)));
}
MagickExport ChannelFeatures *GetImageFeatures(const Image *image,
const size_t distance,ExceptionInfo *exception)
{
typedef struct _ChannelStatistics
{
PixelInfo
direction[4]; /* horizontal, vertical, left and right diagonals */
} ChannelStatistics;
CacheView
*image_view;
ChannelFeatures
*channel_features;
ChannelStatistics
**cooccurrence,
correlation,
*density_x,
*density_xy,
*density_y,
entropy_x,
entropy_xy,
entropy_xy1,
entropy_xy2,
entropy_y,
mean,
**Q,
*sum,
sum_squares,
variance;
PixelPacket
gray,
*grays;
MagickBooleanType
status;
register ssize_t
i,
r;
size_t
length;
unsigned int
number_grays;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns < (distance+1)) || (image->rows < (distance+1)))
return((ChannelFeatures *) NULL);
length=MaxPixelChannels+1UL;
channel_features=(ChannelFeatures *) AcquireQuantumMemory(length,
sizeof(*channel_features));
if (channel_features == (ChannelFeatures *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(channel_features,0,length*
sizeof(*channel_features));
/*
Form grays.
*/
grays=(PixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*grays));
if (grays == (PixelPacket *) NULL)
{
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(channel_features);
}
for (i=0; i <= (ssize_t) MaxMap; i++)
{
grays[i].red=(~0U);
grays[i].green=(~0U);
grays[i].blue=(~0U);
grays[i].alpha=(~0U);
grays[i].black=(~0U);
}
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (r=0; r < (ssize_t) image->rows; r++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,r,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
grays[ScaleQuantumToMap(GetPixelRed(image,p))].red=
ScaleQuantumToMap(GetPixelRed(image,p));
grays[ScaleQuantumToMap(GetPixelGreen(image,p))].green=
ScaleQuantumToMap(GetPixelGreen(image,p));
grays[ScaleQuantumToMap(GetPixelBlue(image,p))].blue=
ScaleQuantumToMap(GetPixelBlue(image,p));
if (image->colorspace == CMYKColorspace)
grays[ScaleQuantumToMap(GetPixelBlack(image,p))].black=
ScaleQuantumToMap(GetPixelBlack(image,p));
if (image->alpha_trait != UndefinedPixelTrait)
grays[ScaleQuantumToMap(GetPixelAlpha(image,p))].alpha=
ScaleQuantumToMap(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
{
grays=(PixelPacket *) RelinquishMagickMemory(grays);
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
return(channel_features);
}
(void) ResetMagickMemory(&gray,0,sizeof(gray));
for (i=0; i <= (ssize_t) MaxMap; i++)
{
if (grays[i].red != ~0U)
grays[gray.red++].red=grays[i].red;
if (grays[i].green != ~0U)
grays[gray.green++].green=grays[i].green;
if (grays[i].blue != ~0U)
grays[gray.blue++].blue=grays[i].blue;
if (image->colorspace == CMYKColorspace)
if (grays[i].black != ~0U)
grays[gray.black++].black=grays[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
if (grays[i].alpha != ~0U)
grays[gray.alpha++].alpha=grays[i].alpha;
}
/*
Allocate spatial dependence matrix.
*/
number_grays=gray.red;
if (gray.green > number_grays)
number_grays=gray.green;
if (gray.blue > number_grays)
number_grays=gray.blue;
if (image->colorspace == CMYKColorspace)
if (gray.black > number_grays)
number_grays=gray.black;
if (image->alpha_trait != UndefinedPixelTrait)
if (gray.alpha > number_grays)
number_grays=gray.alpha;
cooccurrence=(ChannelStatistics **) AcquireQuantumMemory(number_grays,
sizeof(*cooccurrence));
density_x=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1),
sizeof(*density_x));
density_xy=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1),
sizeof(*density_xy));
density_y=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1),
sizeof(*density_y));
Q=(ChannelStatistics **) AcquireQuantumMemory(number_grays,sizeof(*Q));
sum=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(*sum));
if ((cooccurrence == (ChannelStatistics **) NULL) ||
(density_x == (ChannelStatistics *) NULL) ||
(density_xy == (ChannelStatistics *) NULL) ||
(density_y == (ChannelStatistics *) NULL) ||
(Q == (ChannelStatistics **) NULL) ||
(sum == (ChannelStatistics *) NULL))
{
if (Q != (ChannelStatistics **) NULL)
{
for (i=0; i < (ssize_t) number_grays; i++)
Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]);
Q=(ChannelStatistics **) RelinquishMagickMemory(Q);
}
if (sum != (ChannelStatistics *) NULL)
sum=(ChannelStatistics *) RelinquishMagickMemory(sum);
if (density_y != (ChannelStatistics *) NULL)
density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y);
if (density_xy != (ChannelStatistics *) NULL)
density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy);
if (density_x != (ChannelStatistics *) NULL)
density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x);
if (cooccurrence != (ChannelStatistics **) NULL)
{
for (i=0; i < (ssize_t) number_grays; i++)
cooccurrence[i]=(ChannelStatistics *)
RelinquishMagickMemory(cooccurrence[i]);
cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(
cooccurrence);
}
grays=(PixelPacket *) RelinquishMagickMemory(grays);
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(channel_features);
}
(void) ResetMagickMemory(&correlation,0,sizeof(correlation));
(void) ResetMagickMemory(density_x,0,2*(number_grays+1)*sizeof(*density_x));
(void) ResetMagickMemory(density_xy,0,2*(number_grays+1)*sizeof(*density_xy));
(void) ResetMagickMemory(density_y,0,2*(number_grays+1)*sizeof(*density_y));
(void) ResetMagickMemory(&mean,0,sizeof(mean));
(void) ResetMagickMemory(sum,0,number_grays*sizeof(*sum));
(void) ResetMagickMemory(&sum_squares,0,sizeof(sum_squares));
(void) ResetMagickMemory(density_xy,0,2*number_grays*sizeof(*density_xy));
(void) ResetMagickMemory(&entropy_x,0,sizeof(entropy_x));
(void) ResetMagickMemory(&entropy_xy,0,sizeof(entropy_xy));
(void) ResetMagickMemory(&entropy_xy1,0,sizeof(entropy_xy1));
(void) ResetMagickMemory(&entropy_xy2,0,sizeof(entropy_xy2));
(void) ResetMagickMemory(&entropy_y,0,sizeof(entropy_y));
(void) ResetMagickMemory(&variance,0,sizeof(variance));
for (i=0; i < (ssize_t) number_grays; i++)
{
cooccurrence[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,
sizeof(**cooccurrence));
Q[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(**Q));
if ((cooccurrence[i] == (ChannelStatistics *) NULL) ||
(Q[i] == (ChannelStatistics *) NULL))
break;
(void) ResetMagickMemory(cooccurrence[i],0,number_grays*
sizeof(**cooccurrence));
(void) ResetMagickMemory(Q[i],0,number_grays*sizeof(**Q));
}
if (i < (ssize_t) number_grays)
{
for (i--; i >= 0; i--)
{
if (Q[i] != (ChannelStatistics *) NULL)
Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]);
if (cooccurrence[i] != (ChannelStatistics *) NULL)
cooccurrence[i]=(ChannelStatistics *)
RelinquishMagickMemory(cooccurrence[i]);
}
Q=(ChannelStatistics **) RelinquishMagickMemory(Q);
cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence);
sum=(ChannelStatistics *) RelinquishMagickMemory(sum);
density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y);
density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy);
density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x);
grays=(PixelPacket *) RelinquishMagickMemory(grays);
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(channel_features);
}
/*
Initialize spatial dependence matrix.
*/
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
for (r=0; r < (ssize_t) image->rows; r++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
ssize_t
offset,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-(ssize_t) distance,r,image->columns+
2*distance,distance+2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
p+=distance*GetPixelChannels(image);;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < 4; i++)
{
switch (i)
{
case 0:
default:
{
/*
Horizontal adjacency.
*/
offset=(ssize_t) distance;
break;
}
case 1:
{
/*
Vertical adjacency.
*/
offset=(ssize_t) (image->columns+2*distance);
break;
}
case 2:
{
/*
Right diagonal adjacency.
*/
offset=(ssize_t) ((image->columns+2*distance)-distance);
break;
}
case 3:
{
/*
Left diagonal adjacency.
*/
offset=(ssize_t) ((image->columns+2*distance)+distance);
break;
}
}
u=0;
v=0;
while (grays[u].red != ScaleQuantumToMap(GetPixelRed(image,p)))
u++;
while (grays[v].red != ScaleQuantumToMap(GetPixelRed(image,p+offset*GetPixelChannels(image))))
v++;
cooccurrence[u][v].direction[i].red++;
cooccurrence[v][u].direction[i].red++;
u=0;
v=0;
while (grays[u].green != ScaleQuantumToMap(GetPixelGreen(image,p)))
u++;
while (grays[v].green != ScaleQuantumToMap(GetPixelGreen(image,p+offset*GetPixelChannels(image))))
v++;
cooccurrence[u][v].direction[i].green++;
cooccurrence[v][u].direction[i].green++;
u=0;
v=0;
while (grays[u].blue != ScaleQuantumToMap(GetPixelBlue(image,p)))
u++;
while (grays[v].blue != ScaleQuantumToMap(GetPixelBlue(image,p+offset*GetPixelChannels(image))))
v++;
cooccurrence[u][v].direction[i].blue++;
cooccurrence[v][u].direction[i].blue++;
if (image->colorspace == CMYKColorspace)
{
u=0;
v=0;
while (grays[u].black != ScaleQuantumToMap(GetPixelBlack(image,p)))
u++;
while (grays[v].black != ScaleQuantumToMap(GetPixelBlack(image,p+offset*GetPixelChannels(image))))
v++;
cooccurrence[u][v].direction[i].black++;
cooccurrence[v][u].direction[i].black++;
}
if (image->alpha_trait != UndefinedPixelTrait)
{
u=0;
v=0;
while (grays[u].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p)))
u++;
while (grays[v].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p+offset*GetPixelChannels(image))))
v++;
cooccurrence[u][v].direction[i].alpha++;
cooccurrence[v][u].direction[i].alpha++;
}
}
p+=GetPixelChannels(image);
}
}
grays=(PixelPacket *) RelinquishMagickMemory(grays);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
{
for (i=0; i < (ssize_t) number_grays; i++)
cooccurrence[i]=(ChannelStatistics *)
RelinquishMagickMemory(cooccurrence[i]);
cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence);
channel_features=(ChannelFeatures *) RelinquishMagickMemory(
channel_features);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(channel_features);
}
/*
Normalize spatial dependence matrix.
*/
for (i=0; i < 4; i++)
{
double
normalize;
register ssize_t
y;
switch (i)
{
case 0:
default:
{
/*
Horizontal adjacency.
*/
normalize=2.0*image->rows*(image->columns-distance);
break;
}
case 1:
{
/*
Vertical adjacency.
*/
normalize=2.0*(image->rows-distance)*image->columns;
break;
}
case 2:
{
/*
Right diagonal adjacency.
*/
normalize=2.0*(image->rows-distance)*(image->columns-distance);
break;
}
case 3:
{
/*
Left diagonal adjacency.
*/
normalize=2.0*(image->rows-distance)*(image->columns-distance);
break;
}
}
normalize=PerceptibleReciprocal(normalize);
for (y=0; y < (ssize_t) number_grays; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
cooccurrence[x][y].direction[i].red*=normalize;
cooccurrence[x][y].direction[i].green*=normalize;
cooccurrence[x][y].direction[i].blue*=normalize;
if (image->colorspace == CMYKColorspace)
cooccurrence[x][y].direction[i].black*=normalize;
if (image->alpha_trait != UndefinedPixelTrait)
cooccurrence[x][y].direction[i].alpha*=normalize;
}
}
}
/*
Compute texture features.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
register ssize_t
y;
for (y=0; y < (ssize_t) number_grays; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
/*
Angular second moment: measure of homogeneity of the image.
*/
channel_features[RedPixelChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].red*
cooccurrence[x][y].direction[i].red;
channel_features[GreenPixelChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].green*
cooccurrence[x][y].direction[i].green;
channel_features[BluePixelChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].blue*
cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].black*
cooccurrence[x][y].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].angular_second_moment[i]+=
cooccurrence[x][y].direction[i].alpha*
cooccurrence[x][y].direction[i].alpha;
/*
Correlation: measure of linear-dependencies in the image.
*/
sum[y].direction[i].red+=cooccurrence[x][y].direction[i].red;
sum[y].direction[i].green+=cooccurrence[x][y].direction[i].green;
sum[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
sum[y].direction[i].black+=cooccurrence[x][y].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
sum[y].direction[i].alpha+=cooccurrence[x][y].direction[i].alpha;
correlation.direction[i].red+=x*y*cooccurrence[x][y].direction[i].red;
correlation.direction[i].green+=x*y*
cooccurrence[x][y].direction[i].green;
correlation.direction[i].blue+=x*y*
cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
correlation.direction[i].black+=x*y*
cooccurrence[x][y].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
correlation.direction[i].alpha+=x*y*
cooccurrence[x][y].direction[i].alpha;
/*
Inverse Difference Moment.
*/
channel_features[RedPixelChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].red/((y-x)*(y-x)+1);
channel_features[GreenPixelChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].green/((y-x)*(y-x)+1);
channel_features[BluePixelChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].blue/((y-x)*(y-x)+1);
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].black/((y-x)*(y-x)+1);
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].inverse_difference_moment[i]+=
cooccurrence[x][y].direction[i].alpha/((y-x)*(y-x)+1);
/*
Sum average.
*/
density_xy[y+x+2].direction[i].red+=
cooccurrence[x][y].direction[i].red;
density_xy[y+x+2].direction[i].green+=
cooccurrence[x][y].direction[i].green;
density_xy[y+x+2].direction[i].blue+=
cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
density_xy[y+x+2].direction[i].black+=
cooccurrence[x][y].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
density_xy[y+x+2].direction[i].alpha+=
cooccurrence[x][y].direction[i].alpha;
/*
Entropy.
*/
channel_features[RedPixelChannel].entropy[i]-=
cooccurrence[x][y].direction[i].red*
MagickLog10(cooccurrence[x][y].direction[i].red);
channel_features[GreenPixelChannel].entropy[i]-=
cooccurrence[x][y].direction[i].green*
MagickLog10(cooccurrence[x][y].direction[i].green);
channel_features[BluePixelChannel].entropy[i]-=
cooccurrence[x][y].direction[i].blue*
MagickLog10(cooccurrence[x][y].direction[i].blue);
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].entropy[i]-=
cooccurrence[x][y].direction[i].black*
MagickLog10(cooccurrence[x][y].direction[i].black);
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].entropy[i]-=
cooccurrence[x][y].direction[i].alpha*
MagickLog10(cooccurrence[x][y].direction[i].alpha);
/*
Information Measures of Correlation.
*/
density_x[x].direction[i].red+=cooccurrence[x][y].direction[i].red;
density_x[x].direction[i].green+=cooccurrence[x][y].direction[i].green;
density_x[x].direction[i].blue+=cooccurrence[x][y].direction[i].blue;
if (image->alpha_trait != UndefinedPixelTrait)
density_x[x].direction[i].alpha+=
cooccurrence[x][y].direction[i].alpha;
if (image->colorspace == CMYKColorspace)
density_x[x].direction[i].black+=
cooccurrence[x][y].direction[i].black;
density_y[y].direction[i].red+=cooccurrence[x][y].direction[i].red;
density_y[y].direction[i].green+=cooccurrence[x][y].direction[i].green;
density_y[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
density_y[y].direction[i].black+=
cooccurrence[x][y].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
density_y[y].direction[i].alpha+=
cooccurrence[x][y].direction[i].alpha;
}
mean.direction[i].red+=y*sum[y].direction[i].red;
sum_squares.direction[i].red+=y*y*sum[y].direction[i].red;
mean.direction[i].green+=y*sum[y].direction[i].green;
sum_squares.direction[i].green+=y*y*sum[y].direction[i].green;
mean.direction[i].blue+=y*sum[y].direction[i].blue;
sum_squares.direction[i].blue+=y*y*sum[y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
{
mean.direction[i].black+=y*sum[y].direction[i].black;
sum_squares.direction[i].black+=y*y*sum[y].direction[i].black;
}
if (image->alpha_trait != UndefinedPixelTrait)
{
mean.direction[i].alpha+=y*sum[y].direction[i].alpha;
sum_squares.direction[i].alpha+=y*y*sum[y].direction[i].alpha;
}
}
/*
Correlation: measure of linear-dependencies in the image.
*/
channel_features[RedPixelChannel].correlation[i]=
(correlation.direction[i].red-mean.direction[i].red*
mean.direction[i].red)/(sqrt(sum_squares.direction[i].red-
(mean.direction[i].red*mean.direction[i].red))*sqrt(
sum_squares.direction[i].red-(mean.direction[i].red*
mean.direction[i].red)));
channel_features[GreenPixelChannel].correlation[i]=
(correlation.direction[i].green-mean.direction[i].green*
mean.direction[i].green)/(sqrt(sum_squares.direction[i].green-
(mean.direction[i].green*mean.direction[i].green))*sqrt(
sum_squares.direction[i].green-(mean.direction[i].green*
mean.direction[i].green)));
channel_features[BluePixelChannel].correlation[i]=
(correlation.direction[i].blue-mean.direction[i].blue*
mean.direction[i].blue)/(sqrt(sum_squares.direction[i].blue-
(mean.direction[i].blue*mean.direction[i].blue))*sqrt(
sum_squares.direction[i].blue-(mean.direction[i].blue*
mean.direction[i].blue)));
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].correlation[i]=
(correlation.direction[i].black-mean.direction[i].black*
mean.direction[i].black)/(sqrt(sum_squares.direction[i].black-
(mean.direction[i].black*mean.direction[i].black))*sqrt(
sum_squares.direction[i].black-(mean.direction[i].black*
mean.direction[i].black)));
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].correlation[i]=
(correlation.direction[i].alpha-mean.direction[i].alpha*
mean.direction[i].alpha)/(sqrt(sum_squares.direction[i].alpha-
(mean.direction[i].alpha*mean.direction[i].alpha))*sqrt(
sum_squares.direction[i].alpha-(mean.direction[i].alpha*
mean.direction[i].alpha)));
}
/*
Compute more texture features.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
register ssize_t
x;
for (x=2; x < (ssize_t) (2*number_grays); x++)
{
/*
Sum average.
*/
channel_features[RedPixelChannel].sum_average[i]+=
x*density_xy[x].direction[i].red;
channel_features[GreenPixelChannel].sum_average[i]+=
x*density_xy[x].direction[i].green;
channel_features[BluePixelChannel].sum_average[i]+=
x*density_xy[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].sum_average[i]+=
x*density_xy[x].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].sum_average[i]+=
x*density_xy[x].direction[i].alpha;
/*
Sum entropy.
*/
channel_features[RedPixelChannel].sum_entropy[i]-=
density_xy[x].direction[i].red*
MagickLog10(density_xy[x].direction[i].red);
channel_features[GreenPixelChannel].sum_entropy[i]-=
density_xy[x].direction[i].green*
MagickLog10(density_xy[x].direction[i].green);
channel_features[BluePixelChannel].sum_entropy[i]-=
density_xy[x].direction[i].blue*
MagickLog10(density_xy[x].direction[i].blue);
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].sum_entropy[i]-=
density_xy[x].direction[i].black*
MagickLog10(density_xy[x].direction[i].black);
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].sum_entropy[i]-=
density_xy[x].direction[i].alpha*
MagickLog10(density_xy[x].direction[i].alpha);
/*
Sum variance.
*/
channel_features[RedPixelChannel].sum_variance[i]+=
(x-channel_features[RedPixelChannel].sum_entropy[i])*
(x-channel_features[RedPixelChannel].sum_entropy[i])*
density_xy[x].direction[i].red;
channel_features[GreenPixelChannel].sum_variance[i]+=
(x-channel_features[GreenPixelChannel].sum_entropy[i])*
(x-channel_features[GreenPixelChannel].sum_entropy[i])*
density_xy[x].direction[i].green;
channel_features[BluePixelChannel].sum_variance[i]+=
(x-channel_features[BluePixelChannel].sum_entropy[i])*
(x-channel_features[BluePixelChannel].sum_entropy[i])*
density_xy[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].sum_variance[i]+=
(x-channel_features[BlackPixelChannel].sum_entropy[i])*
(x-channel_features[BlackPixelChannel].sum_entropy[i])*
density_xy[x].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].sum_variance[i]+=
(x-channel_features[AlphaPixelChannel].sum_entropy[i])*
(x-channel_features[AlphaPixelChannel].sum_entropy[i])*
density_xy[x].direction[i].alpha;
}
}
/*
Compute more texture features.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
register ssize_t
y;
for (y=0; y < (ssize_t) number_grays; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
/*
Sum of Squares: Variance
*/
variance.direction[i].red+=(y-mean.direction[i].red+1)*
(y-mean.direction[i].red+1)*cooccurrence[x][y].direction[i].red;
variance.direction[i].green+=(y-mean.direction[i].green+1)*
(y-mean.direction[i].green+1)*cooccurrence[x][y].direction[i].green;
variance.direction[i].blue+=(y-mean.direction[i].blue+1)*
(y-mean.direction[i].blue+1)*cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
variance.direction[i].black+=(y-mean.direction[i].black+1)*
(y-mean.direction[i].black+1)*cooccurrence[x][y].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
variance.direction[i].alpha+=(y-mean.direction[i].alpha+1)*
(y-mean.direction[i].alpha+1)*
cooccurrence[x][y].direction[i].alpha;
/*
Sum average / Difference Variance.
*/
density_xy[MagickAbsoluteValue(y-x)].direction[i].red+=
cooccurrence[x][y].direction[i].red;
density_xy[MagickAbsoluteValue(y-x)].direction[i].green+=
cooccurrence[x][y].direction[i].green;
density_xy[MagickAbsoluteValue(y-x)].direction[i].blue+=
cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
density_xy[MagickAbsoluteValue(y-x)].direction[i].black+=
cooccurrence[x][y].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
density_xy[MagickAbsoluteValue(y-x)].direction[i].alpha+=
cooccurrence[x][y].direction[i].alpha;
/*
Information Measures of Correlation.
*/
entropy_xy.direction[i].red-=cooccurrence[x][y].direction[i].red*
MagickLog10(cooccurrence[x][y].direction[i].red);
entropy_xy.direction[i].green-=cooccurrence[x][y].direction[i].green*
MagickLog10(cooccurrence[x][y].direction[i].green);
entropy_xy.direction[i].blue-=cooccurrence[x][y].direction[i].blue*
MagickLog10(cooccurrence[x][y].direction[i].blue);
if (image->colorspace == CMYKColorspace)
entropy_xy.direction[i].black-=cooccurrence[x][y].direction[i].black*
MagickLog10(cooccurrence[x][y].direction[i].black);
if (image->alpha_trait != UndefinedPixelTrait)
entropy_xy.direction[i].alpha-=
cooccurrence[x][y].direction[i].alpha*MagickLog10(
cooccurrence[x][y].direction[i].alpha);
entropy_xy1.direction[i].red-=(cooccurrence[x][y].direction[i].red*
MagickLog10(density_x[x].direction[i].red*density_y[y].direction[i].red));
entropy_xy1.direction[i].green-=(cooccurrence[x][y].direction[i].green*
MagickLog10(density_x[x].direction[i].green*
density_y[y].direction[i].green));
entropy_xy1.direction[i].blue-=(cooccurrence[x][y].direction[i].blue*
MagickLog10(density_x[x].direction[i].blue*density_y[y].direction[i].blue));
if (image->colorspace == CMYKColorspace)
entropy_xy1.direction[i].black-=(
cooccurrence[x][y].direction[i].black*MagickLog10(
density_x[x].direction[i].black*density_y[y].direction[i].black));
if (image->alpha_trait != UndefinedPixelTrait)
entropy_xy1.direction[i].alpha-=(
cooccurrence[x][y].direction[i].alpha*MagickLog10(
density_x[x].direction[i].alpha*density_y[y].direction[i].alpha));
entropy_xy2.direction[i].red-=(density_x[x].direction[i].red*
density_y[y].direction[i].red*MagickLog10(density_x[x].direction[i].red*
density_y[y].direction[i].red));
entropy_xy2.direction[i].green-=(density_x[x].direction[i].green*
density_y[y].direction[i].green*MagickLog10(density_x[x].direction[i].green*
density_y[y].direction[i].green));
entropy_xy2.direction[i].blue-=(density_x[x].direction[i].blue*
density_y[y].direction[i].blue*MagickLog10(density_x[x].direction[i].blue*
density_y[y].direction[i].blue));
if (image->colorspace == CMYKColorspace)
entropy_xy2.direction[i].black-=(density_x[x].direction[i].black*
density_y[y].direction[i].black*MagickLog10(
density_x[x].direction[i].black*density_y[y].direction[i].black));
if (image->alpha_trait != UndefinedPixelTrait)
entropy_xy2.direction[i].alpha-=(density_x[x].direction[i].alpha*
density_y[y].direction[i].alpha*MagickLog10(
density_x[x].direction[i].alpha*density_y[y].direction[i].alpha));
}
}
channel_features[RedPixelChannel].variance_sum_of_squares[i]=
variance.direction[i].red;
channel_features[GreenPixelChannel].variance_sum_of_squares[i]=
variance.direction[i].green;
channel_features[BluePixelChannel].variance_sum_of_squares[i]=
variance.direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].variance_sum_of_squares[i]=
variance.direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].variance_sum_of_squares[i]=
variance.direction[i].alpha;
}
/*
Compute more texture features.
*/
(void) ResetMagickMemory(&variance,0,sizeof(variance));
(void) ResetMagickMemory(&sum_squares,0,sizeof(sum_squares));
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
/*
Difference variance.
*/
variance.direction[i].red+=density_xy[x].direction[i].red;
variance.direction[i].green+=density_xy[x].direction[i].green;
variance.direction[i].blue+=density_xy[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
variance.direction[i].black+=density_xy[x].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
variance.direction[i].alpha+=density_xy[x].direction[i].alpha;
sum_squares.direction[i].red+=density_xy[x].direction[i].red*
density_xy[x].direction[i].red;
sum_squares.direction[i].green+=density_xy[x].direction[i].green*
density_xy[x].direction[i].green;
sum_squares.direction[i].blue+=density_xy[x].direction[i].blue*
density_xy[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
sum_squares.direction[i].black+=density_xy[x].direction[i].black*
density_xy[x].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
sum_squares.direction[i].alpha+=density_xy[x].direction[i].alpha*
density_xy[x].direction[i].alpha;
/*
Difference entropy.
*/
channel_features[RedPixelChannel].difference_entropy[i]-=
density_xy[x].direction[i].red*
MagickLog10(density_xy[x].direction[i].red);
channel_features[GreenPixelChannel].difference_entropy[i]-=
density_xy[x].direction[i].green*
MagickLog10(density_xy[x].direction[i].green);
channel_features[BluePixelChannel].difference_entropy[i]-=
density_xy[x].direction[i].blue*
MagickLog10(density_xy[x].direction[i].blue);
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].difference_entropy[i]-=
density_xy[x].direction[i].black*
MagickLog10(density_xy[x].direction[i].black);
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].difference_entropy[i]-=
density_xy[x].direction[i].alpha*
MagickLog10(density_xy[x].direction[i].alpha);
/*
Information Measures of Correlation.
*/
entropy_x.direction[i].red-=(density_x[x].direction[i].red*
MagickLog10(density_x[x].direction[i].red));
entropy_x.direction[i].green-=(density_x[x].direction[i].green*
MagickLog10(density_x[x].direction[i].green));
entropy_x.direction[i].blue-=(density_x[x].direction[i].blue*
MagickLog10(density_x[x].direction[i].blue));
if (image->colorspace == CMYKColorspace)
entropy_x.direction[i].black-=(density_x[x].direction[i].black*
MagickLog10(density_x[x].direction[i].black));
if (image->alpha_trait != UndefinedPixelTrait)
entropy_x.direction[i].alpha-=(density_x[x].direction[i].alpha*
MagickLog10(density_x[x].direction[i].alpha));
entropy_y.direction[i].red-=(density_y[x].direction[i].red*
MagickLog10(density_y[x].direction[i].red));
entropy_y.direction[i].green-=(density_y[x].direction[i].green*
MagickLog10(density_y[x].direction[i].green));
entropy_y.direction[i].blue-=(density_y[x].direction[i].blue*
MagickLog10(density_y[x].direction[i].blue));
if (image->colorspace == CMYKColorspace)
entropy_y.direction[i].black-=(density_y[x].direction[i].black*
MagickLog10(density_y[x].direction[i].black));
if (image->alpha_trait != UndefinedPixelTrait)
entropy_y.direction[i].alpha-=(density_y[x].direction[i].alpha*
MagickLog10(density_y[x].direction[i].alpha));
}
/*
Difference variance.
*/
channel_features[RedPixelChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].red)-
(variance.direction[i].red*variance.direction[i].red))/
((double) number_grays*number_grays*number_grays*number_grays);
channel_features[GreenPixelChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].green)-
(variance.direction[i].green*variance.direction[i].green))/
((double) number_grays*number_grays*number_grays*number_grays);
channel_features[BluePixelChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].blue)-
(variance.direction[i].blue*variance.direction[i].blue))/
((double) number_grays*number_grays*number_grays*number_grays);
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].black)-
(variance.direction[i].black*variance.direction[i].black))/
((double) number_grays*number_grays*number_grays*number_grays);
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].difference_variance[i]=
(((double) number_grays*number_grays*sum_squares.direction[i].alpha)-
(variance.direction[i].alpha*variance.direction[i].alpha))/
((double) number_grays*number_grays*number_grays*number_grays);
/*
Information Measures of Correlation.
*/
channel_features[RedPixelChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].red-entropy_xy1.direction[i].red)/
(entropy_x.direction[i].red > entropy_y.direction[i].red ?
entropy_x.direction[i].red : entropy_y.direction[i].red);
channel_features[GreenPixelChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].green-entropy_xy1.direction[i].green)/
(entropy_x.direction[i].green > entropy_y.direction[i].green ?
entropy_x.direction[i].green : entropy_y.direction[i].green);
channel_features[BluePixelChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].blue-entropy_xy1.direction[i].blue)/
(entropy_x.direction[i].blue > entropy_y.direction[i].blue ?
entropy_x.direction[i].blue : entropy_y.direction[i].blue);
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].black-entropy_xy1.direction[i].black)/
(entropy_x.direction[i].black > entropy_y.direction[i].black ?
entropy_x.direction[i].black : entropy_y.direction[i].black);
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].measure_of_correlation_1[i]=
(entropy_xy.direction[i].alpha-entropy_xy1.direction[i].alpha)/
(entropy_x.direction[i].alpha > entropy_y.direction[i].alpha ?
entropy_x.direction[i].alpha : entropy_y.direction[i].alpha);
channel_features[RedPixelChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].red-
entropy_xy.direction[i].red)))));
channel_features[GreenPixelChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].green-
entropy_xy.direction[i].green)))));
channel_features[BluePixelChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].blue-
entropy_xy.direction[i].blue)))));
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].black-
entropy_xy.direction[i].black)))));
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].measure_of_correlation_2[i]=
(sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].alpha-
entropy_xy.direction[i].alpha)))));
}
/*
Compute more texture features.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,number_grays,1)
#endif
for (i=0; i < 4; i++)
{
ssize_t
z;
for (z=0; z < (ssize_t) number_grays; z++)
{
register ssize_t
y;
ChannelStatistics
pixel;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) number_grays; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) number_grays; x++)
{
/*
Contrast: amount of local variations present in an image.
*/
if (((y-x) == z) || ((x-y) == z))
{
pixel.direction[i].red+=cooccurrence[x][y].direction[i].red;
pixel.direction[i].green+=cooccurrence[x][y].direction[i].green;
pixel.direction[i].blue+=cooccurrence[x][y].direction[i].blue;
if (image->colorspace == CMYKColorspace)
pixel.direction[i].black+=cooccurrence[x][y].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
pixel.direction[i].alpha+=
cooccurrence[x][y].direction[i].alpha;
}
/*
Maximum Correlation Coefficient.
*/
Q[z][y].direction[i].red+=cooccurrence[z][x].direction[i].red*
cooccurrence[y][x].direction[i].red/density_x[z].direction[i].red/
density_y[x].direction[i].red;
Q[z][y].direction[i].green+=cooccurrence[z][x].direction[i].green*
cooccurrence[y][x].direction[i].green/
density_x[z].direction[i].green/density_y[x].direction[i].red;
Q[z][y].direction[i].blue+=cooccurrence[z][x].direction[i].blue*
cooccurrence[y][x].direction[i].blue/density_x[z].direction[i].blue/
density_y[x].direction[i].blue;
if (image->colorspace == CMYKColorspace)
Q[z][y].direction[i].black+=cooccurrence[z][x].direction[i].black*
cooccurrence[y][x].direction[i].black/
density_x[z].direction[i].black/density_y[x].direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
Q[z][y].direction[i].alpha+=
cooccurrence[z][x].direction[i].alpha*
cooccurrence[y][x].direction[i].alpha/
density_x[z].direction[i].alpha/
density_y[x].direction[i].alpha;
}
}
channel_features[RedPixelChannel].contrast[i]+=z*z*
pixel.direction[i].red;
channel_features[GreenPixelChannel].contrast[i]+=z*z*
pixel.direction[i].green;
channel_features[BluePixelChannel].contrast[i]+=z*z*
pixel.direction[i].blue;
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].contrast[i]+=z*z*
pixel.direction[i].black;
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].contrast[i]+=z*z*
pixel.direction[i].alpha;
}
/*
Maximum Correlation Coefficient.
Future: return second largest eigenvalue of Q.
*/
channel_features[RedPixelChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
channel_features[GreenPixelChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
channel_features[BluePixelChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
if (image->colorspace == CMYKColorspace)
channel_features[BlackPixelChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
if (image->alpha_trait != UndefinedPixelTrait)
channel_features[AlphaPixelChannel].maximum_correlation_coefficient[i]=
sqrt((double) -1.0);
}
/*
Relinquish resources.
*/
sum=(ChannelStatistics *) RelinquishMagickMemory(sum);
for (i=0; i < (ssize_t) number_grays; i++)
Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]);
Q=(ChannelStatistics **) RelinquishMagickMemory(Q);
density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y);
density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy);
density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x);
for (i=0; i < (ssize_t) number_grays; i++)
cooccurrence[i]=(ChannelStatistics *)
RelinquishMagickMemory(cooccurrence[i]);
cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence);
return(channel_features);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H o u g h L i n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Use HoughLineImage() in conjunction with any binary edge extracted image (we
% recommand Canny) to identify lines in the image. The algorithm accumulates
% counts for every white pixel for every possible orientation (for angles from
% 0 to 179 in 1 degree increments) and distance from the center of the image to
% the corner (in 1 px increments) and stores the counts in an accumulator matrix
% of angle vs distance. The size of the accumulator is 180x(diagonal/2). Next
% it searches this space for peaks in counts and converts the locations of the
% peaks to slope and intercept in the normal x,y input image space. Use the
% slope/intercepts to find the endpoints clipped to the bounds of the image. The
% lines are then drawn. The counts are a measure of the length of the lines
%
% The format of the HoughLineImage method is:
%
% Image *HoughLineImage(const Image *image,const size_t width,
% const size_t height,const size_t threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width, height: find line pairs as local maxima in this neighborhood.
%
% o threshold: the line count threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickRound(double x)
{
/*
Round the fraction to nearest integer.
*/
if ((x-floor(x)) < (ceil(x)-x))
return(floor(x));
return(ceil(x));
}
static Image *RenderHoughLines(const ImageInfo *image_info,const size_t columns,
const size_t rows,ExceptionInfo *exception)
{
#define BoundingBox "viewbox"
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
/*
Open image.
*/
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->columns=columns;
image->rows=rows;
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->affine.sx=image->resolution.x == 0.0 ? 1.0 : image->resolution.x/
DefaultResolution;
draw_info->affine.sy=image->resolution.y == 0.0 ? 1.0 : image->resolution.y/
DefaultResolution;
image->columns=(size_t) (draw_info->affine.sx*image->columns);
image->rows=(size_t) (draw_info->affine.sy*image->rows);
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Render drawing.
*/
if (GetBlobStreamData(image) == (unsigned char *) NULL)
draw_info->primitive=FileToString(image->filename,~0UL,exception);
else
{
draw_info->primitive=(char *) AcquireMagickMemory((size_t)
GetBlobSize(image)+1);
if (draw_info->primitive != (char *) NULL)
{
(void) CopyMagickMemory(draw_info->primitive,GetBlobStreamData(image),
(size_t) GetBlobSize(image));
draw_info->primitive[GetBlobSize(image)]='\0';
}
}
(void) DrawImage(image,draw_info,exception);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
MagickExport Image *HoughLineImage(const Image *image,const size_t width,
const size_t height,const size_t threshold,ExceptionInfo *exception)
{
#define HoughLineImageTag "HoughLine/Image"
CacheView
*image_view;
char
message[MagickPathExtent],
path[MagickPathExtent];
const char
*artifact;
double
hough_height;
Image
*lines_image = NULL;
ImageInfo
*image_info;
int
file;
MagickBooleanType
status;
MagickOffsetType
progress;
MatrixInfo
*accumulator;
PointInfo
center;
register ssize_t
y;
size_t
accumulator_height,
accumulator_width,
line_count;
/*
Create the accumulator.
*/
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);
accumulator_width=180;
hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ?
image->rows : image->columns))/2.0);
accumulator_height=(size_t) (2.0*hough_height);
accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height,
sizeof(double),exception);
if (accumulator == (MatrixInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
if (NullMatrix(accumulator) == MagickFalse)
{
accumulator=DestroyMatrixInfo(accumulator);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Populate the accumulator.
*/
status=MagickTrue;
progress=0;
center.x=(double) image->columns/2.0;
center.y=(double) image->rows/2.0;
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 == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelIntensity(image,p) > (QuantumRange/2.0))
{
register ssize_t
i;
for (i=0; i < 180; i++)
{
double
count,
radius;
radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+
(((double) y-center.y)*sin(DegreesToRadians((double) i)));
(void) GetMatrixElement(accumulator,i,(ssize_t)
MagickRound(radius+hough_height),&count);
count++;
(void) SetMatrixElement(accumulator,i,(ssize_t)
MagickRound(radius+hough_height),&count);
}
}
p+=GetPixelChannels(image);
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CannyEdgeImage)
#endif
proceed=SetImageProgress(image,CannyEdgeImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
{
accumulator=DestroyMatrixInfo(accumulator);
return((Image *) NULL);
}
/*
Generate line segments from accumulator.
*/
file=AcquireUniqueFileResource(path);
if (file == -1)
{
accumulator=DestroyMatrixInfo(accumulator);
return((Image *) NULL);
}
(void) FormatLocaleString(message,MagickPathExtent,
"# Hough line transform: %.20gx%.20g%+.20g\n",(double) width,
(double) height,(double) threshold);
if (write(file,message,strlen(message)) != (ssize_t) strlen(message))
status=MagickFalse;
(void) FormatLocaleString(message,MagickPathExtent,
"viewbox 0 0 %.20g %.20g\n",(double) image->columns,(double) image->rows);
if (write(file,message,strlen(message)) != (ssize_t) strlen(message))
status=MagickFalse;
line_count=image->columns > image->rows ? image->columns/4 : image->rows/4;
if (threshold != 0)
line_count=threshold;
for (y=0; y < (ssize_t) accumulator_height; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) accumulator_width; x++)
{
double
count;
(void) GetMatrixElement(accumulator,x,y,&count);
if (count >= (double) line_count)
{
double
maxima;
SegmentInfo
line;
ssize_t
v;
/*
Is point a local maxima?
*/
maxima=count;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((u != 0) || (v !=0))
{
(void) GetMatrixElement(accumulator,x+u,y+v,&count);
if (count > maxima)
{
maxima=count;
break;
}
}
}
if (u < (ssize_t) (width/2))
break;
}
(void) GetMatrixElement(accumulator,x,y,&count);
if (maxima > count)
continue;
if ((x >= 45) && (x <= 135))
{
/*
y = (r-x cos(t))/sin(t)
*/
line.x1=0.0;
line.y1=((double) (y-(accumulator_height/2.0))-((line.x1-
(image->columns/2.0))*cos(DegreesToRadians((double) x))))/
sin(DegreesToRadians((double) x))+(image->rows/2.0);
line.x2=(double) image->columns;
line.y2=((double) (y-(accumulator_height/2.0))-((line.x2-
(image->columns/2.0))*cos(DegreesToRadians((double) x))))/
sin(DegreesToRadians((double) x))+(image->rows/2.0);
}
else
{
/*
x = (r-y cos(t))/sin(t)
*/
line.y1=0.0;
line.x1=((double) (y-(accumulator_height/2.0))-((line.y1-
(image->rows/2.0))*sin(DegreesToRadians((double) x))))/
cos(DegreesToRadians((double) x))+(image->columns/2.0);
line.y2=(double) image->rows;
line.x2=((double) (y-(accumulator_height/2.0))-((line.y2-
(image->rows/2.0))*sin(DegreesToRadians((double) x))))/
cos(DegreesToRadians((double) x))+(image->columns/2.0);
}
(void) FormatLocaleString(message,MagickPathExtent,
"line %g,%g %g,%g # %g\n",line.x1,line.y1,line.x2,line.y2,maxima);
if (write(file,message,strlen(message)) != (ssize_t) strlen(message))
status=MagickFalse;
}
}
}
(void) close(file);
/*
Render lines to image canvas.
*/
image_info=AcquireImageInfo();
image_info->background_color=image->background_color;
(void) FormatLocaleString(image_info->filename,MagickPathExtent,"%s",path);
artifact=GetImageArtifact(image,"background");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"background",artifact);
artifact=GetImageArtifact(image,"fill");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"fill",artifact);
artifact=GetImageArtifact(image,"stroke");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"stroke",artifact);
artifact=GetImageArtifact(image,"strokewidth");
if (artifact != (const char *) NULL)
(void) SetImageOption(image_info,"strokewidth",artifact);
lines_image=RenderHoughLines(image_info,image->columns,image->rows,exception);
artifact=GetImageArtifact(image,"hough-lines:accumulator");
if ((lines_image != (Image *) NULL) &&
(IsStringTrue(artifact) != MagickFalse))
{
Image
*accumulator_image;
accumulator_image=MatrixToImage(accumulator,exception);
if (accumulator_image != (Image *) NULL)
AppendImageToList(&lines_image,accumulator_image);
}
/*
Free resources.
*/
accumulator=DestroyMatrixInfo(accumulator);
image_info=DestroyImageInfo(image_info);
(void) RelinquishUniqueFileResource(path);
return(GetFirstImageInList(lines_image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M e a n S h i f t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MeanShiftImage() delineate arbitrarily shaped clusters in the image. For
% each pixel, it visits all the pixels in the neighborhood specified by
% the window centered at the pixel and excludes those that are outside the
% radius=(window-1)/2 surrounding the pixel. From those pixels, it finds those
% that are within the specified color distance from the current mean, and
% computes a new x,y centroid from those coordinates and a new mean. This new
% x,y centroid is used as the center for a new window. This process iterates
% until it converges and the final mean is replaces the (original window
% center) pixel value. It repeats this process for the next pixel, etc.,
% until it processes all pixels in the image. Results are typically better with
% colorspaces other than sRGB. We recommend YIQ, YUV or YCbCr.
%
% The format of the MeanShiftImage method is:
%
% Image *MeanShiftImage(const Image *image,const size_t width,
% const size_t height,const double color_distance,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width, height: find pixels in this neighborhood.
%
% o color_distance: the color distance.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
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);
mean_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse)
{
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status,progress) \
magick_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
PixelInfo
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetPixelInfo(image,&mean_pixel);
GetPixelInfoPixel(image,p,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
PixelInfo
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetPixelInfo(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelInfo
pixel;
status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.alpha+=pixel.alpha;
count++;
}
}
}
}
gamma=1.0/count;
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.alpha=gamma*sum_pixel.alpha;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q);
SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q);
SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q);
SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(mean_image);
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_MeanShiftImage)
#endif
proceed=SetImageProgress(image,MeanShiftImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
}
|
tpi_openmp.c | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the program and library */
/* SCIP --- Solving Constraint Integer Programs */
/* */
/* Copyright (C) 2002-2019 Konrad-Zuse-Zentrum */
/* fuer Informationstechnik Berlin */
/* */
/* SCIP is distributed under the terms of the ZIB Academic License. */
/* */
/* You should have received a copy of the ZIB Academic License */
/* along with SCIP; see the file COPYING. If not visit scip.zib.de. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file tpi_openmp.c
* @ingroup TASKINTERFACE
* @brief the interface functions for openmp
* @author Stephen J. Maher
* @author Robert Lion Gottwald
*/
/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
#include "tpi/tpi.h"
#include "blockmemshell/memory.h"
/** A job added to the queue */
struct SCIP_Job
{
int jobid; /**< id to identify jobs from a common process */
struct SCIP_Job* nextjob; /**< pointer to the next job in the queue */
SCIP_RETCODE (*jobfunc)(void* args);/**< pointer to the job function */
void* args; /**< pointer to the function arguements */
SCIP_RETCODE retcode; /**< return code of the job */
};
/** the thread pool job queue */
struct SCIP_JobQueue
{
SCIP_JOB* firstjob; /**< pointer to the first job in the queue */
SCIP_JOB* lastjob; /**< pointer to the last job in the queue */
int njobs; /**< number of jobs in the queue */
};
typedef struct SCIP_JobQueue SCIP_JOBQUEUE;
struct SCIP_JobQueues
{
SCIP_JOBQUEUE jobqueue; /**< queue of unprocessed jobs */
SCIP_JOB** currentjobs; /**< array with slot for each thread to store the currently running job */
int ncurrentjobs; /**< number of currently running jobs */
int nthreads; /**< number of threads */
SCIP_JOBQUEUE finishedjobs; /**< jobqueue containing the finished jobs */
SCIP_LOCK lock; /**< lock to protect this stucture from concurrent access */
SCIP_CONDITION jobfinished; /**< condition to signal if a job was finished */
};
typedef struct SCIP_JobQueues SCIP_JOBQUEUES;
static SCIP_JOBQUEUES* _jobqueues = NULL;
static
SCIP_RETCODE createJobQueue(
int nthreads, /**< the number of threads */
int qsize, /**< the queue size */
SCIP_Bool blockwhenfull /**< should the queue be blocked from new jobs when full */
)
{
int i;
assert(nthreads >= 0);
assert(qsize >= 0);
SCIP_UNUSED( blockwhenfull );
/* allocting memory for the job queue */
SCIP_ALLOC( BMSallocMemory(&_jobqueues) );
_jobqueues->jobqueue.firstjob = NULL;
_jobqueues->jobqueue.lastjob = NULL;
_jobqueues->jobqueue.njobs = 0;
_jobqueues->finishedjobs.firstjob = NULL;
_jobqueues->finishedjobs.lastjob = NULL;
_jobqueues->finishedjobs.njobs = 0;
_jobqueues->ncurrentjobs = 0;
_jobqueues->nthreads = nthreads;
SCIP_ALLOC( BMSallocMemoryArray(&_jobqueues->currentjobs, nthreads) );
for( i = 0; i < nthreads; ++i )
_jobqueues->currentjobs[i] = NULL;
SCIP_CALL( SCIPtpiInitLock(&_jobqueues->lock) );
SCIP_CALL( SCIPtpiInitCondition(&_jobqueues->jobfinished) );
return SCIP_OKAY;
}
static
SCIP_RETCODE freeJobQueue(
void
)
{
assert(_jobqueues != NULL);
SCIPtpiDestroyLock(&_jobqueues->lock);
SCIPtpiDestroyCondition(&_jobqueues->jobfinished);
BMSfreeMemoryArray(&_jobqueues->currentjobs);
BMSfreeMemory(&_jobqueues);
return SCIP_OKAY;
}
static
void executeJob(
SCIP_JOB* job /**< the job to be executed in parallel */
)
{
int threadnum;
threadnum = SCIPtpiGetThreadNum();
SCIP_CALL_ABORT( SCIPtpiAcquireLock(&_jobqueues->lock) );
_jobqueues->currentjobs[threadnum] = job;
SCIP_CALL_ABORT( SCIPtpiReleaseLock(&_jobqueues->lock) );
job->retcode = (*(job->jobfunc))(job->args);
SCIP_CALL_ABORT( SCIPtpiAcquireLock(&_jobqueues->lock) );
_jobqueues->ncurrentjobs--;
_jobqueues->currentjobs[threadnum] = NULL;
/* insert job into finished jobs */
if( _jobqueues->finishedjobs.njobs == 0 )
{
_jobqueues->finishedjobs.firstjob = job;
_jobqueues->finishedjobs.lastjob = job;
}
else
{
_jobqueues->finishedjobs.lastjob->nextjob = job;
_jobqueues->finishedjobs.lastjob = job;
}
++_jobqueues->finishedjobs.njobs;
SCIP_CALL_ABORT( SCIPtpiBroadcastCondition(&_jobqueues->jobfinished) );
SCIP_CALL_ABORT( SCIPtpiReleaseLock(&_jobqueues->lock) );
}
/** this is a job that will be executed on to process the job queue
*
* The job will only be added when the number of active jobs is equal to the number of threads.
* As such, there will always be number of threads + 1 tasks available for the scheduler to run.
*/
static
void jobQueueProcessJob(
void
)
{
SCIP_JOB* job;
SCIP_CALL_ABORT( SCIPtpiAcquireLock(&_jobqueues->lock) );
while( _jobqueues->ncurrentjobs == SCIPtpiGetNumThreads() )
{
SCIP_CALL_ABORT( SCIPtpiWaitCondition(&_jobqueues->jobfinished, &_jobqueues->lock) );
}
if( _jobqueues->jobqueue.njobs == 1 )
{
job = _jobqueues->jobqueue.firstjob;
_jobqueues->jobqueue.firstjob = NULL;
_jobqueues->jobqueue.lastjob = NULL;
--_jobqueues->jobqueue.njobs;
}
else if( _jobqueues->jobqueue.njobs > 1 )
{
job = _jobqueues->jobqueue.firstjob;
_jobqueues->jobqueue.firstjob = job->nextjob;
--_jobqueues->jobqueue.njobs;
}
else
{
job = NULL;
}
++_jobqueues->ncurrentjobs;
SCIP_CALL_ABORT( SCIPtpiReleaseLock(&_jobqueues->lock) );
if( job )
{
executeJob(job);
}
}
/** adding a job to the job queue.
*
* This gives some more flexibility in the handling of new jobs.
* IMPORTANT: This function MUST be called from within a mutex.
*/
static
SCIP_RETCODE jobQueueAddJob(
SCIP_JOB* newjob
)
{
/* @todo we want to work out what to do with a full job queue. Is there a problem if the limit is hit? */
/* @note it is important to have a queuesize. This will stop the code submitting infinitely many jobs. */
assert(newjob != NULL);
newjob->nextjob = NULL;
/* this function queries the current job list. This could change by other threads writing to the list. So a lock is
* required to ensure that the current joblist remains static. */
SCIP_CALL( SCIPtpiAcquireLock(&_jobqueues->lock) );
/* checking the status of the job queue */
if( _jobqueues->ncurrentjobs == SCIPtpiGetNumThreads() )
{
if( _jobqueues->jobqueue.njobs == 0 )
{
_jobqueues->jobqueue.firstjob = newjob;
_jobqueues->jobqueue.lastjob = newjob;
}
else /* it is assumed that the jobqueue is not full */
{
_jobqueues->jobqueue.lastjob->nextjob = newjob;
_jobqueues->jobqueue.lastjob = newjob;
}
_jobqueues->jobqueue.njobs++;
SCIP_CALL( SCIPtpiReleaseLock(&_jobqueues->lock) );
#pragma omp task
jobQueueProcessJob();
}
else
{
assert(_jobqueues->ncurrentjobs < SCIPtpiGetNumThreads());
_jobqueues->ncurrentjobs++;
SCIP_CALL( SCIPtpiReleaseLock(&_jobqueues->lock) );
/* running the new job */
#pragma omp task firstprivate(newjob)
executeJob(newjob);
}
return SCIP_OKAY;
}
SCIP_RETCODE SCIPtpiSignalCondition(
SCIP_CONDITION* condition
)
{
SCIP_CALL( SCIPtpiAcquireLock(&condition->_lock) );
if( condition->_waitnum > condition->_signals )
++condition->_signals;
SCIP_CALL( SCIPtpiReleaseLock(&condition->_lock) );
return SCIP_OKAY;
}
SCIP_RETCODE SCIPtpiBroadcastCondition(
SCIP_CONDITION* condition
)
{
SCIP_CALL( SCIPtpiAcquireLock(&condition->_lock) );
condition->_signals = condition->_waitnum;
SCIP_CALL( SCIPtpiReleaseLock(&condition->_lock) );
return SCIP_OKAY;
}
SCIP_RETCODE SCIPtpiWaitCondition(
SCIP_CONDITION* condition,
SCIP_LOCK* lock
)
{
int waitnum;
SCIP_CALL( SCIPtpiReleaseLock(lock) );
SCIP_CALL( SCIPtpiAcquireLock(&condition->_lock) );
waitnum = ++condition->_waitnum;
++condition->_waiters;
do
{
SCIP_CALL( SCIPtpiReleaseLock(&condition->_lock) );
#pragma omp taskyield
SCIP_CALL( SCIPtpiAcquireLock(&condition->_lock) );
}
while( condition->_signals < waitnum );
--condition->_waiters;
if( condition->_waiters == 0 )
{
condition->_signals = 0;
condition->_waitnum = 0;
}
SCIP_CALL( SCIPtpiReleaseLock(&condition->_lock) );
SCIP_CALL( SCIPtpiAcquireLock(lock) );
return SCIP_OKAY;
}
/** Returns the number of threads */
int SCIPtpiGetNumThreads(
)
{
return omp_get_num_threads();
}
/** Returns the thread number */
int SCIPtpiGetThreadNum(
)
{
return omp_get_thread_num();
}
/** creates a job for parallel processing*/
SCIP_RETCODE SCIPtpiCreateJob(
SCIP_JOB** job, /**< pointer to the job that will be created */
int jobid, /**< the id for the current job */
SCIP_RETCODE (*jobfunc)(void* args),/**< pointer to the job function */
void* jobarg /**< the job's argument */
)
{
SCIP_ALLOC( BMSallocMemory(job) );
(*job)->jobid = jobid;
(*job)->jobfunc = jobfunc;
(*job)->args = jobarg;
(*job)->nextjob = NULL;
return SCIP_OKAY;
}
/** get a new job id for the new set of submitted jobs */
int SCIPtpiGetNewJobID(
void
)
{
static int currentjobid = 0;
int jobid;
#pragma omp atomic capture
jobid = ++currentjobid;
return jobid;
}
/** submit a job for parallel processing
*
* the return is a globally defined status
*/
SCIP_RETCODE SCIPtpiSumbitJob(
SCIP_JOB* job, /**< pointer to the job to be submitted */
SCIP_SUBMITSTATUS* status /**< pointer to store the submit status */
)
{
assert(_jobqueues != NULL);
*status = SCIP_SUBMIT_SUCCESS;
SCIP_CALL( jobQueueAddJob(job) );
return SCIP_OKAY;
}
static
SCIP_Bool isJobRunning(
int jobid
)
{
int i;
if( _jobqueues->ncurrentjobs > 0 )
{
for( i = 0; i < _jobqueues->nthreads; ++i )
{
if( _jobqueues->currentjobs[i] != NULL && _jobqueues->currentjobs[i]->jobid == jobid )
return TRUE;
}
}
return FALSE;
}
static
SCIP_Bool isJobWaiting(
int jobid
)
{
if( _jobqueues->jobqueue.njobs > 0 )
{
SCIP_JOB* currjob;
currjob = _jobqueues->jobqueue.firstjob;
do
{
if( currjob->jobid == jobid )
return TRUE;
if( currjob == _jobqueues->jobqueue.lastjob )
break;
currjob = currjob->nextjob;
}
while( TRUE ); /*lint !e506*/
}
return FALSE;
}
/** Blocks until all jobs of the given jobid have finished
* and then returns the smallest SCIP_RETCODE of all the jobs */
SCIP_RETCODE SCIPtpiCollectJobs(
int jobid
)
{
SCIP_RETCODE retcode;
retcode = SCIP_OKAY;
SCIP_CALL( SCIPtpiAcquireLock(&_jobqueues->lock) );
while( isJobRunning(jobid) || isJobWaiting(jobid) )
{
SCIP_CALL( SCIPtpiWaitCondition(&_jobqueues->jobfinished, &_jobqueues->lock) );
}
if( _jobqueues->finishedjobs.njobs > 0 )
{
SCIP_JOB* currjob = _jobqueues->finishedjobs.firstjob;
SCIP_JOB* prevjob = NULL;
/* finding the location of the processed job in the currentjobs queue */
do
{
if( currjob->jobid == jobid )
{
SCIP_JOB* nextjob;
/* if the job has the right jobid collect its retcode, remove it from the finished job list, and free it */
retcode = MIN(retcode, currjob->retcode);
/* removing the finished job from finished jobs list */
if( currjob == _jobqueues->finishedjobs.firstjob )
_jobqueues->finishedjobs.firstjob = currjob->nextjob;
else
prevjob->nextjob = currjob->nextjob; /*lint !e613*/
if( currjob == _jobqueues->finishedjobs.lastjob )
_jobqueues->finishedjobs.lastjob = prevjob;
_jobqueues->finishedjobs.njobs--;
/* update currjob and free finished job; prevjob stays the same */
nextjob = currjob->nextjob;
BMSfreeMemory(&currjob);
currjob = nextjob;
}
else
{
prevjob = currjob;
currjob = prevjob->nextjob;
}
}
while( prevjob != _jobqueues->finishedjobs.lastjob );
}
else
{
/* given jobid was not submitted */
printf("err1");
retcode = SCIP_ERROR;
}
SCIP_CALL_ABORT( SCIPtpiReleaseLock(&_jobqueues->lock) );
return retcode;
}
/** initializes tpi */
SCIP_RETCODE SCIPtpiInit(
int nthreads,
int queuesize,
SCIP_Bool blockwhenfull
)
{
omp_set_num_threads(nthreads);
assert(_jobqueues == NULL);
SCIP_CALL( createJobQueue(nthreads, queuesize, blockwhenfull) );
return SCIP_OKAY;
}
/** deinitializes tpi */
SCIP_RETCODE SCIPtpiExit(
void
)
{
assert(_jobqueues != NULL);
assert(_jobqueues->finishedjobs.njobs == 0);
assert(_jobqueues->jobqueue.njobs == 0);
assert(_jobqueues->ncurrentjobs == 0);
SCIP_CALL( freeJobQueue() );
return SCIP_OKAY;
}
|
mujoco_deriv_struct.c | // -*- evil-shift-width: 4 -*-
/* Copyright © 2018, Roboti LLC
This file is licensed under the MuJoCo Resource 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://www.roboti.us/resourcelicense.txt
*/
#include "mujoco.h"
#include <stdio.h>
#include <errno.h> /* errno, perror */
#include <string.h>
#include <sys/time.h>
#include <math.h>
#include <assert.h>
#include "mujoco_deriv_struct.h"
// global variables: user-defined, with defaults
#define MAXTHREAD 64 // maximum number of threads allowed
#define MAXSTATEN 8 // max allowed state members
// enable compilation with and without OpenMP support
#if defined(_OPENMP)
#include <omp.h>
#else
// omp timer replacement
double omp_get_wtime(void)
{
struct timeval start;
struct timezone tz;
gettimeofday(&start, &tz);
struct timeval end;
gettimeofday(&end, &tz);
return (double)start.tv_sec + 1e-6 * (double)start.tv_usec;
}
// omp functions used below
void omp_set_dynamic(int x) {}
void omp_set_num_threads(int x) {}
int omp_get_num_procs(void) {return 1;}
#endif
mjtNum* alloc_deriv(const mjModel* m)
{
// allocate derivatives
return (mjtNum*) mju_malloc(6*sizeof(mjtNum)*m->nv*m->nv);
}
void mj_copyStateCtrlData(mjData* d, const mjModel* m, const mjData* dmain) {
d->time = dmain->time;
mju_copy(d->qpos, dmain->qpos, m->nq);
mju_copy(d->qvel, dmain->qvel, m->nv);
mju_copy(d->qacc, dmain->qacc, m->nv);
mju_copy(d->qacc_warmstart, dmain->qacc_warmstart, m->nv);
mju_copy(d->qfrc_applied, dmain->qfrc_applied, m->nv);
mju_copy(d->xfrc_applied, dmain->xfrc_applied, 6*m->nbody);
mju_copy(d->ctrl, dmain->ctrl, m->nu);
}
////////////////////////////////////////////////////////////////////////////////
// mjData Getters
////////////////////////////////////////////////////////////////////////////////
#define MJDATA_GET_PTR(attr) &mjd_get_ ## attr
#define MJDATA_GETTER(attr) \
mjtNum* mjd_get_ ## attr(const mjData* d) \
{ \
return d-> attr; \
}
MJDATA_GETTER(ctrl)
MJDATA_GETTER(qpos)
MJDATA_GETTER(qvel)
MJDATA_GETTER(qacc)
MJDATA_GETTER(qfrc_inverse)
MJDATA_GETTER(qfrc_applied)
void mjDGetters_free(mjDGetters* g)
{
mju_free(g->fs);
mju_free(g);
}
mjDGetter* mjd_enum2getter(const MJDGetter_enum mjdg)
{
switch (mjdg)
{
case MJDGetter_ctrl:
return MJDATA_GET_PTR(ctrl);
case MJDGetter_qpos:
return MJDATA_GET_PTR(qpos);
case MJDGetter_qvel:
return MJDATA_GET_PTR(qvel);
case MJDGetter_qacc:
return MJDATA_GET_PTR(qacc);
case MJDGetter_qfrc_inverse:
return MJDATA_GET_PTR(qfrc_inverse);
case MJDGetter_qfrc_applied:
return MJDATA_GET_PTR(qfrc_applied);
default:
printf("Error: Bad enum %d", mjdg);
exit(EXIT_FAILURE);
break;
}
}
char* mjd_getter2str(mjDGetter* mjdg)
{
if (MJDATA_GET_PTR(ctrl) == mjdg)
return "ctrl";
else if (MJDATA_GET_PTR(qpos) == mjdg)
return "qpos";
else if (MJDATA_GET_PTR(qvel) == mjdg)
return "qvel";
else if (MJDATA_GET_PTR(qacc) == mjdg)
return "qacc";
else if (MJDATA_GET_PTR(qfrc_inverse) == mjdg)
return "qfrc_inverse";
else if (MJDATA_GET_PTR(qfrc_applied) == mjdg)
return "qfrc_applied";
else {
printf("Error: Bad getter %p", (void*) mjdg);
exit(EXIT_FAILURE);
}
}
void mjDGetters_print(const mjDGetters* mjdg)
{
for (size_t i = 0; i < mjdg->len; i++)
printf("%s %s", i ? "," : "", mjd_getter2str(mjdg->fs[i]));
printf("\n");
}
mjDGetters* mjDGetters_new(size_t len, MJDGetter_enum* attr)
{
mjDGetters* g = (mjDGetters*) mju_malloc(sizeof(mjDGetters));
g->len = len;
g->fs = (mjDGetter**) mju_malloc(len * sizeof(mjDGetter*));
for (size_t i = 0; i < len; i++)
g->fs[i] = mjd_enum2getter(attr[i]);
g->free = &mjDGetters_free;
return g;
}
// mj_warmup_t
void mj_warmup_fwd(const mjModel* m, mjData* d, int nwarmup) {
mj_forward(m, d);
// extra solver iterations to improve warmstart (qacc) at center point
for( int rep=1; rep<nwarmup; rep++ )
mj_forwardSkip(m, d, mjSTAGE_VEL, 1);
}
// mj_warmup_t
void mj_warmup_inv(const mjModel* m, mjData* d, int nwarmup) {
mj_inverse(m, d);
}
size_t mjDeriv_deriv_size(const mjModel* m, int xN, int fN)
{
int nv = m->nv;
return fN*xN*nv*nv;
}
// An implementation of mj_moveSkip
void mj_warmFowardSkip(const mjModel* m,
mjData* d,
mjtStage stage,
int n,
mjtNum* warmstart)
{
mju_copy(d->qacc_warmstart, warmstart, m->nv);
mj_forwardSkip(m, d, stage, n);
}
// An implementation of mj_moveSkip
void mj_invSkip(const mjModel* m,
mjData* d,
mjtStage stage,
int n,
mjtNum* warmstart)
{
mj_inverseSkip(m, d, stage, n);
}
void perturb_fwd_inv(mjDeriv* deriv,
int xk,
int threadid,
int i,
mj_moveSkip move)
{
mjtNum* warmstart = deriv->warmstart;
mjtStage stage = deriv->stages[xk];
mjtNum eps = deriv->eps;
const mjModel* m = deriv->m;
mjData* d = deriv->d[threadid];
// save output for center point and warmstart (needed in forward only)
mjtNum* target = deriv->xs->fs[xk](d);
const mjtNum originali = deriv->xs->fs[xk](deriv->dmain)[i];
// perturb selected target
target[i] += eps;
// move forward or backward by
(*move)(m, d, stage, 1, warmstart);
// undo perturbation
target[i] = originali;
}
// perturb_t interface
void perturb_fwd(mjDeriv* deriv,
int xk,
int threadid,
int i)
{
perturb_fwd_inv(deriv, xk, threadid, i, &mj_warmFowardSkip);
}
// perturb_t interface
void perturb_inv(mjDeriv* deriv,
int xk,
int threadid,
int i)
{
perturb_fwd_inv(deriv, xk, threadid, i, &mj_invSkip);
}
void perturb_fwd_inv_pos(mjDeriv* deriv,
int xk,
int threadid,
int i,
mj_moveSkip* move)
{
mjtNum* warmstart = deriv->warmstart;
mjtStage stage = deriv->stages[xk];
mjtNum eps = deriv->eps;
const mjModel* m = deriv->m;
mjData* d = deriv->d[threadid];
const mjData* dmain = deriv->dmain;
// get joint id for this dof
int jid = m->dof_jntid[i];
// get quaternion address and dof position within quaternion (-1: not in quaternion)
int quatadr = -1, dofpos = 0;
if( m->jnt_type[jid]==mjJNT_BALL )
{
quatadr = m->jnt_qposadr[jid];
dofpos = i - m->jnt_dofadr[jid];
}
else if( m->jnt_type[jid]==mjJNT_FREE && i>=m->jnt_dofadr[jid]+3 )
{
quatadr = m->jnt_qposadr[jid] + 3;
dofpos = i - m->jnt_dofadr[jid] - 3;
}
// apply quaternion or simple perturbation
if( quatadr>=0 )
{
mjtNum angvel[3] = {0,0,0};
angvel[dofpos] = eps;
mju_quatIntegrate(d->qpos+quatadr, angvel, 1);
}
else
d->qpos[m->jnt_qposadr[jid] + i - m->jnt_dofadr[jid]] += eps;
// evaluate dynamics, with center warmstart
move(m, d, stage, 1, warmstart);
// undo perturbation
mju_copy(d->qpos, dmain->qpos, m->nq);
}
// perturb_t interface
void perturb_fwd_pos(mjDeriv* deriv,
int xk,
int threadid,
int i)
{
perturb_fwd_inv_pos(deriv, xk, threadid, i, &mj_warmFowardSkip);
}
// perturb_t interface
void perturb_inv_pos(mjDeriv* deriv,
int xk,
int threadid,
int i)
{
perturb_fwd_inv_pos(deriv, xk, threadid, i, &mj_invSkip);
}
perturb_t mjd_enum2perturber(MJDGetter_enum attr, int isforward)
{
if (isforward) {
if (MJDGetter_qpos == attr)
return &perturb_fwd_pos;
else
return &perturb_fwd;
} else {
if (MJDGetter_qpos == attr)
return &perturb_inv_pos;
else
return &perturb_inv;
}
}
perturb_t* mjPerturb_new(size_t len, MJDGetter_enum* attrs, int isforward)
{
perturb_t* perturbers = (perturb_t*) mju_malloc(len * sizeof(perturb_t));
for (int i = 0; i < len; i++)
perturbers[i] = mjd_enum2perturber(attrs[i], isforward);
return perturbers;
}
void mjPerturb_free(perturb_t* perturbers)
{
mju_free(perturbers);
}
mjtStage mjd_enum2stage(MJDGetter_enum attr)
{
switch (attr)
{
case MJDGetter_qpos:
return mjSTAGE_NONE;
case MJDGetter_qvel:
return mjSTAGE_POS;
default:
return mjSTAGE_VEL;
}
}
mjtStage* mjStages_new(size_t len, MJDGetter_enum* attrs)
{
mjtStage* stages = (mjtStage*) mju_malloc(len * sizeof(mjtStage));
for (int i = 0; i < len; i++)
stages[i] = mjd_enum2stage(attrs[i]);
return stages;
}
void mjStages_print(mjtStage* stages, size_t len)
{
for (size_t i = 0; i < len; i++)
printf("%s%d", i ? ", " : "", stages[i]);
printf("\n");
}
void mjStages_free(mjtStage* stages)
{
mju_free(stages);
}
void mjDeriv_compute(mjDeriv* deriv, int threadid)
{
mjData* d = deriv->d[threadid];
const mjModel* m = deriv->m;
const mjData* dmain = deriv->dmain;
mjDGetters* fs = deriv->fs;
mjDGetters* xs = deriv->xs;
int nthread = deriv->nthread;
mjtNum eps = deriv->eps;
int nv = m->nv;
// allocate stack space for result at center
mjMARKSTACK
mjtNum* center = mj_stackAlloc(d, nv);
mjtNum* warmstart = mj_stackAlloc(d, nv);
// prepare static schedule: range of derivative columns to be computed by this thread
int chunk = (m->nv + nthread-1) / nthread;
int istart = threadid * chunk;
int iend = mjMIN(istart + chunk, m->nv);
// copy state and control from dmain to thread-specific d
mj_copyStateCtrlData(d, m, dmain);
// run full computation at center point (usually faster than copying dmain)
(*deriv->warmer)(m, d, deriv->nwarmup);
for (int fk=0; fk < fs->len; fk++) {
// select target vector and original vector for force or acceleration derivative
mjtNum* output = fs->fs[fk](d); // d->qacc
// save output for center point and warmstart (needed in forward only)
mju_copy(center, output, nv);
mju_copy(warmstart, d->qacc_warmstart, nv);
for (int xk=0; xk < xs->len; xk++) {
deriv->warmstart = warmstart;
for( int i=istart; i<iend; i++ ) {
(deriv->perturbers[xk])(deriv, xk, threadid, i);
// compute column i of derivative 2
for( int j=0; j<nv; j++ ) {
size_t idx = (fk*xs->len + xs->len-xk-1)*nv*nv + j*nv + i;
deriv->deriv[idx] = (output[j] - center[j])/eps;
}
}
}
}
mjFREESTACK
}
void mjDeriv_print(mjDeriv* mjd)
{
printf("mjd->m->nv: %d\n", mjd->m->nv);
printf("mjd->dmain->nefc: %d\n", mjd->dmain->nefc);
printf("mjd->deriv: %p\n", (void*) mjd->deriv);
printf("mjd->fs: "); mjDGetters_print(mjd->fs);
printf("mjd->xs: "); mjDGetters_print(mjd->xs);
printf("mjd->stages:"); mjStages_print(mjd->stages, mjd->xs->len);
printf("mjd->eps: %f\n", mjd->eps);
printf("mjd->nthread: %d\n", mjd->nthread);
printf("mjd->nwarmup: %d\n", mjd->nwarmup);
printf("mjd->warmer: %s\n", mjd->warmer == mj_warmup_fwd ? "fwd" :
(mjd->warmer == mj_warmup_inv ? "inv" : "error"));
}
void mjDeriv_compute_mp(mjDeriv* deriv)
{
int nthread = deriv->nthread;
const mjModel* m = deriv->m;
// set up OpenMP (if not enabled, this does nothing)
omp_set_dynamic(0);
omp_set_num_threads(nthread);
//mjData** d = deriv->d;
mjData* d[MAXTHREAD];
for( int n=0; n<nthread; n++ ) {
mjData* dn = mj_makeData(m);
d[n] = dn;
if ( d[n] == NULL ) {
perror("Unable to allocate memory\n");
exit(EXIT_FAILURE);
}
}
deriv->d = d;
// run worker threads in parallel if OpenMP is enabled
#pragma omp parallel for schedule(static)
for( int n=0; n<nthread; n++ ) {
(*deriv->compute)(deriv, n);
}
for( int n=0; n<nthread; n++ )
mj_deleteData(d[n]);
}
void mjDeriv_free(mjDeriv* mjderiv)
{
mju_free(mjderiv);
}
mjDeriv* mjDeriv_new(const mjModel* m, const mjData* dmain, mjtNum* deriv,
mjDGetters* fs, mjDGetters* xs, perturb_t* perturbers,
mjtStage* stages,
mj_warmup_t* warmer, int nwarmup, double eps, int nthread)
{
mjDeriv* mjd = (mjDeriv*) mju_malloc(sizeof(mjDeriv));
mjd->m = m;
mjd->dmain = dmain;
mjd->deriv = deriv;
mjd->fs = fs;
mjd->xs = fs;
mjd->perturbers = perturbers;
mjd->nwarmup = nwarmup;
mjd->warmer = warmer;
mjd->xs = xs;
mjd->perturbers = perturbers;
mjd->stages = stages;
mjd->nthread = nthread;
// mjd->d = (mjData**) mju_malloc(nthread * sizeof(mjData*));
mjd->eps = eps;
mjd->compute = &mjDeriv_compute;
mjd->compute_mp = &mjDeriv_compute_mp;
mjd->free = &mjDeriv_free;
return mjd;
}
void mjDeriv_free_default(mjDeriv* mjderiv)
{
// mju_free(mjderiv->d);
mju_free(mjderiv->stages);
mju_free(mjderiv->perturbers);
(*mjderiv->xs->free)(mjderiv->xs);
(*mjderiv->fs->free)(mjderiv->fs);
mju_free(mjderiv);
}
mjDeriv* mjDeriv_new_default(const mjModel* m, const mjData* dmain, mjtNum* deriv,
int isforward, int nwarmup, double eps, int nthread)
{
size_t fN = 1;
size_t xN = 3;
mjDeriv* mjd = (mjDeriv*) mju_malloc(sizeof(mjDeriv));
mjd->m = m;
mjd->dmain = dmain;
mjd->deriv = deriv;
MJDGetter_enum fs_attr[1] = { MJDGetter_qacc };
if (isforward) {
fs_attr[0] = MJDGetter_qacc ;
} else {
fs_attr[0] = MJDGetter_qfrc_inverse;
}
mjDGetters* fs = mjDGetters_new(fN, fs_attr);
mjd->fs = fs;
MJDGetter_enum xs_attr[3] = { MJDGetter_qfrc_applied, MJDGetter_qvel, MJDGetter_qpos };
if (isforward) {
xs_attr[0] = MJDGetter_qfrc_applied;
} else {
xs_attr[0] = MJDGetter_qacc;
}
mjDGetters* xs = mjDGetters_new(xN, xs_attr);
perturb_t* perturbers = (perturb_t*) mju_malloc(xN * sizeof(perturb_t));
if (isforward) {
perturbers[0] = &perturb_fwd;
perturbers[1] = &perturb_fwd;
perturbers[2] = &perturb_fwd_pos;
mjd->nwarmup = nwarmup;
mjd->warmer = &mj_warmup_fwd;
} else {
perturbers[0] = &perturb_inv;
perturbers[1] = &perturb_inv;
perturbers[2] = &perturb_inv_pos;
mjd->nwarmup = 0;
mjd->warmer = &mj_warmup_inv;
}
mjd->xs = xs;
mjd->perturbers = perturbers;
mjd->stages = (mjtStage*) mju_malloc(xN * sizeof(mjtStage));
mjd->stages[0] = mjSTAGE_VEL;
mjd->stages[1] = mjSTAGE_POS;
mjd->stages[2] = mjSTAGE_NONE;
mjd->nthread = nthread;
// mjd->d = (mjData**) mju_malloc(nthread * sizeof(mjData*));
mjd->eps = eps;
mjd->compute = &mjDeriv_compute;
mjd->compute_mp = &mjDeriv_compute_mp;
mjd->free = &mjDeriv_free_default;
return mjd;
}
double relnorm(mjtNum* residual, mjtNum* base, int n)
{
mjtNum L1res = 0, L1base = 0;
for( int i=0; i<n; i++ )
{
L1res += mju_abs(residual[i]);
L1base += mju_abs(base[i]);
}
return (double) mju_log10(mju_max(mjMINVAL,L1res/mju_max(mjMINVAL,L1base)));
}
// names of residuals for accuracy check
const char* accuracy[8] = {
"G2*F2 - I ",
"G2 - G2' ",
"G1 - G1' ",
"F2 - F2' ",
"G1 + G2*F1",
"G0 + G2*F0",
"F1 + F2*G1",
"F0 + F2*G0"
};
// check accuracy of derivatives using known mathematical identities
void checkderiv(const mjModel* m, mjtNum* deriv, mjtNum error[8])
{
mjData* d = mj_makeData(m);
int nv = m->nv;
// allocate space
mjMARKSTACK
mjtNum* mat = mj_stackAlloc(d, nv*nv);
// get pointers to derivative matrices
mjtNum* G0 = deriv; // dinv/dpos
mjtNum* G1 = deriv + nv*nv; // dinv/dvel
mjtNum* G2 = deriv + 2*nv*nv; // dinv/dacc = dqfrc_inverse / dacc
mjtNum* F0 = deriv + 3*nv*nv; // dacc/dpos
mjtNum* F1 = deriv + 4*nv*nv; // dacc/dvel
mjtNum* F2 = deriv + 5*nv*nv; // dacc/dfrc = dacc / dfrc_applied
// G2*F2 - I
mju_mulMatMat(mat, G2, F2, nv, nv, nv);
for( int i=0; i<nv; i++ )
mat[i*(nv+1)] -= 1;
error[0] = relnorm(mat, G2, nv*nv);
// G2 - G2'
mju_transpose(mat, G2, nv, nv);
mju_sub(mat, mat, G2, nv*nv);
error[1] = relnorm(mat, G2, nv*nv);
// G1 - G1'
mju_transpose(mat, G1, nv, nv);
mju_sub(mat, mat, G1, nv*nv);
error[2] = relnorm(mat, G1, nv*nv);
// F2 - F2'
mju_transpose(mat, F2, nv, nv);
mju_sub(mat, mat, F2, nv*nv);
error[3] = relnorm(mat, F2, nv*nv);
// G1 + G2*F1
mju_mulMatMat(mat, G2, F1, nv, nv, nv);
mju_addTo(mat, G1, nv*nv);
error[4] = relnorm(mat, G1, nv*nv);
// G0 + G2*F0
mju_mulMatMat(mat, G2, F0, nv, nv, nv);
mju_addTo(mat, G0, nv*nv);
error[5] = relnorm(mat, G0, nv*nv);
// F1 + F2*G1
mju_mulMatMat(mat, F2, G1, nv, nv, nv);
mju_addTo(mat, F1, nv*nv);
error[6] = relnorm(mat, F1, nv*nv);
// F0 + F2*G0
mju_mulMatMat(mat, F2, G0, nv, nv, nv);
mju_addTo(mat, F0, nv*nv);
error[7] = relnorm(mat, F0, nv*nv);
mjFREESTACK
mj_deleteData(d);
}
int main(int argc, char** argv)
{
// gloval variables: internal
const int MAXEPOCH = 100; // maximum number of epochs
mjtNum* deriv = 0; // dynamics derivatives (6*nv*nv):
// dinv/dpos, dinv/dvel, dinv/dacc, dacc/dpos, dacc/dvel, dacc/dfrc
int nthread = 0;
int niter = 30; // fixed number of solver iterations for finite-differencing
int nwarmup = 3; // center point repetitions to improve warmstart
int nepoch = 20; // number of timing epochs
int nstep = 500; // number of simulation steps per epoch
double eps = 1e-6; // finite-difference epsilon
// print help if not enough arguments
if( argc<2 )
{
printf("\n Arguments: modelfile [nthread niter nwarmup nepoch nstep eps]\n\n");
return 1;
}
// default nthread = number of logical cores (usually optimal)
nthread = omp_get_num_procs();
// get numeric command-line arguments
if( argc>2 )
sscanf(argv[2], "%d", &nthread);
if( argc>3 )
sscanf(argv[3], "%d", &niter);
if( argc>4 )
sscanf(argv[4], "%d", &nwarmup);
if( argc>5 )
sscanf(argv[5], "%d", &nepoch);
if( argc>6 )
sscanf(argv[6], "%d", &nstep);
if( argc>7 )
sscanf(argv[7], "%lf", &eps);
// check number of threads
if( nthread<1 || nthread>MAXTHREAD )
{
printf("nthread must be between 1 and %d\n", MAXTHREAD);
return 1;
}
// check number of epochs
if( nepoch<1 || nepoch>MAXEPOCH )
{
printf("nepoch must be between 1 and %d\n", MAXEPOCH);
return 1;
}
// activate and load model
mj_activate("mjkey.txt");
mjModel* m = 0;
if( strlen(argv[1])>4 && !strcmp(argv[1]+strlen(argv[1])-4, ".mjb") )
m = mj_loadModel(argv[1], NULL);
else
m = mj_loadXML(argv[1], NULL, NULL, 0);
if( !m )
{
printf("Could not load modelfile '%s'\n", argv[1]);
return 1;
}
// print arguments
#if defined(_OPENMP)
printf("\nnthread : %d (OpenMP)\n", nthread);
#else
printf("\nnthread : %d (serial)\n", nthread);
#endif
printf("niter : %d\n", niter);
printf("nwarmup : %d\n", nwarmup);
printf("nepoch : %d\n", nepoch);
printf("nstep : %d\n", nstep);
printf("eps : %g\n\n", eps);
// make mjData: main, per-thread
mjData* dmain = mj_makeData(m);
int nv = m->nv;
deriv = alloc_deriv(m);
mjDeriv* mjderiv_inv = mjDeriv_new_default(m, dmain, deriv, 0, nwarmup, eps, nthread);
mjDeriv* mjderiv_fwd = mjDeriv_new_default(m, dmain, deriv + 3*nv*nv, 1, nwarmup, eps, nthread);
mjDeriv* mj_derivs[2] = {mjderiv_inv, mjderiv_fwd};
// save solver options
int save_iterations = m->opt.iterations;
mjtNum save_tolerance = m->opt.tolerance;
// allocate statistics
int nefc = 0;
double cputm[MAXEPOCH][2];
mjtNum error[MAXEPOCH][8];
// run epochs, collect statistics
for( int epoch=0; epoch<nepoch; epoch++ )
{
// set solver options for main simulation
m->opt.iterations = save_iterations;
m->opt.tolerance = save_tolerance;
// advance main simulation for nstep
for( int i=0; i<nstep; i++ )
mj_step(m, dmain);
// count number of active constraints
nefc += dmain->nefc;
// set solver options for finite differences
m->opt.iterations = niter;
m->opt.tolerance = 0;
// start timer
double starttm = omp_get_wtime();
// test forward and inverse
for( int isforward=0; isforward<2; isforward++ ) {
mjDeriv* mjderiv = mj_derivs[isforward];
(*mjderiv->compute_mp)(mjderiv);
// record duration in ms
cputm[epoch][isforward] = 1000*(omp_get_wtime() - starttm);
}
// check derivatives
checkderiv(m, deriv, error[epoch]);
}
// compute statistics
double mcputm[2] = {0,0}, merror[8] = {0,0,0,0,0,0,0,0};
for( int epoch=0; epoch<nepoch; epoch++ )
{
mcputm[0] += cputm[epoch][0];
mcputm[1] += cputm[epoch][1];
for( int ie=0; ie<8; ie++ )
merror[ie] += error[epoch][ie];
}
// print sizes, timing, accuracy
printf("sizes : nv %d, nefc %d\n\n", m->nv, nefc/nepoch);
printf("inverse : %.2f ms\n", mcputm[0]/nepoch);
printf("forward : %.2f ms\n\n", mcputm[1]/nepoch);
printf("accuracy: log10(residual L1 relnorm)\n");
printf("------------------------------------\n");
for( int ie=0; ie<8; ie++ )
printf(" %s : %.2g\n", accuracy[ie], merror[ie]/nepoch);
printf("\n");
// shut down
for (int isforward = 0; isforward < 2; isforward++) {
mjDeriv* mjderiv = mj_derivs[isforward];
(*mjderiv->free)(mjderiv);
}
mju_free(deriv);
mj_deleteData(dmain);
mj_deleteModel(m);
mj_deactivate();
return 0;
}
|
ark_heat1D_omp.c | /*---------------------------------------------------------------
* Programmer(s): Shelby Lockhart @ LLNL
*---------------------------------------------------------------
* Based on the serial code ark_heat1D.c developed by
* Daniel R. Reynolds @ SMU 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 problem:
*
* The following test simulates a simple 1D heat equation,
* u_t = k*u_xx + f
* for t in [0, 10], x in [0, 1], with initial conditions
* u(0,x) = 0
* Dirichlet boundary conditions, i.e.
* u_t(t,0) = u_t(t,1) = 0,
* and a point-source heating term,
* f = 1 for x=0.5.
*
* The spatial derivatives are computed using second-order
* centered differences, with the data distributed over N points
* on a uniform spatial grid.
*
* This program solves the problem with either an ERK or DIRK
* method. For the DIRK method, we use a Newton iteration with
* the SUNPCG linear solver, and a user-supplied Jacobian-vector
* product routine.
*
* 100 outputs are printed at equal intervals, and run statistics
* are printed at the end.
*---------------------------------------------------------------*/
/* Header files */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <arkode/arkode_arkstep.h> /* prototypes for ARKStep fcts., consts */
#include <nvector/nvector_openmp.h> /* OpenMP N_Vector types, fcts., macros */
#include <sunlinsol/sunlinsol_pcg.h> /* access to PCG SUNLinearSolver */
#include <sundials/sundials_types.h> /* defs. of realtype, sunindextype, etc */
#ifdef _OPENMP
#include <omp.h> /* OpenMP function defs. */
#endif
#if defined(SUNDIALS_EXTENDED_PRECISION)
#define GSYM "Lg"
#define ESYM "Le"
#define FSYM "Lf"
#else
#define GSYM "g"
#define ESYM "e"
#define FSYM "f"
#endif
/* user data structure */
typedef struct {
sunindextype N; /* number of intervals */
int nthreads; /* number of OpenMP threads */
realtype dx; /* mesh spacing */
realtype k; /* diffusion coefficient */
} *UserData;
/* User-supplied Functions Called by the Solver */
static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data);
static int Jac(N_Vector v, N_Vector Jv, realtype t, N_Vector y,
N_Vector fy, void *user_data, N_Vector tmp);
/* Private function to check function return values */
static int check_flag(void *flagvalue, const char *funcname, int opt);
/* Main Program */
int main(int argc, char *argv[]) {
/* general problem parameters */
realtype T0 = RCONST(0.0); /* initial time */
realtype Tf = RCONST(1.0); /* final time */
int Nt = 10; /* total number of output times */
realtype rtol = 1.e-6; /* relative tolerance */
realtype atol = 1.e-10; /* absolute tolerance */
UserData udata = NULL;
realtype *data;
sunindextype N = 201; /* spatial mesh size */
realtype k = 0.5; /* heat conductivity */
sunindextype i;
/* general problem variables */
int flag; /* reusable error-checking flag */
N_Vector y = NULL; /* empty vector for storing solution */
SUNLinearSolver LS = NULL; /* empty linear solver object */
void *arkode_mem = NULL; /* empty ARKStep memory structure */
FILE *FID, *UFID;
realtype t, dTout, tout;
int iout, num_threads;
long int nst, nst_a, nfe, nfi, nsetups, nli, nJv, nlcf, nni, ncfn, netf;
/* 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) /* overwrite with command line value, if supplied */
num_threads = (int) strtol(argv[1], NULL, 0);
/* allocate and fill udata structure */
udata = (UserData) malloc(sizeof(*udata));
udata->N = N;
udata->k = k;
udata->dx = RCONST(1.0)/(N-1); /* mesh spacing */
udata->nthreads = num_threads;
/* Initial problem output */
printf("\n1D Heat PDE test problem:\n");
printf(" N = %li\n", (long int) udata->N);
printf(" diffusion coefficient: k = %"GSYM"\n", udata->k);
/* Initialize data structures */
y = N_VNew_OpenMP(N, num_threads); /* Create OpenMP vector for solution */
if (check_flag((void *) y, "N_VNew_OpenMP", 0)) return 1;
N_VConst(0.0, y); /* Set initial conditions */
arkode_mem = ARKStepCreate(NULL, f, T0, y); /* Create the solver memory */
if (check_flag((void *) arkode_mem, "ARKStepCreate", 0)) return 1;
/* Set routines */
flag = ARKStepSetUserData(arkode_mem, (void *) udata); /* Pass udata to user functions */
if (check_flag(&flag, "ARKStepSetUserData", 1)) return 1;
flag = ARKStepSetMaxNumSteps(arkode_mem, 10000); /* Increase max num steps */
if (check_flag(&flag, "ARKStepSetMaxNumSteps", 1)) return 1;
flag = ARKStepSetPredictorMethod(arkode_mem, 1); /* Specify maximum-order predictor */
if (check_flag(&flag, "ARKStepSetPredictorMethod", 1)) return 1;
flag = ARKStepSStolerances(arkode_mem, rtol, atol); /* Specify tolerances */
if (check_flag(&flag, "ARKStepSStolerances", 1)) return 1;
/* Initialize PCG solver -- no preconditioning, with up to N iterations */
LS = SUNLinSol_PCG(y, 0, (int) N);
if (check_flag((void *)LS, "SUNLinSol_PCG", 0)) return 1;
/* Linear solver interface -- set user-supplied J*v routine (no 'jtsetup' required) */
flag = ARKStepSetLinearSolver(arkode_mem, LS, NULL); /* Attach linear solver to ARKStep */
if (check_flag(&flag, "ARKStepSetLinearSolver", 1)) return 1;
flag = ARKStepSetJacTimes(arkode_mem, NULL, Jac); /* Set the Jacobian routine */
if (check_flag(&flag, "ARKStepSetJacTimes", 1)) return 1;
/* Specify linearly implicit RHS, with non-time-dependent Jacobian */
flag = ARKStepSetLinear(arkode_mem, 0);
if (check_flag(&flag, "ARKStepSetLinear", 1)) return 1;
/* output mesh to disk */
FID=fopen("heat_mesh.txt","w");
for (i=0; i<N; i++) fprintf(FID," %.16"ESYM"\n", udata->dx*i);
fclose(FID);
/* Open output stream for results, access data array */
UFID=fopen("heat1D.txt","w");
data = N_VGetArrayPointer(y);
/* output initial condition to disk */
for (i=0; i<N; i++) fprintf(UFID," %.16"ESYM"", data[i]);
fprintf(UFID,"\n");
/* Main time-stepping loop: calls ARKStep to perform the integration, then
prints results. Stops when the final time has been reached */
t = T0;
dTout = (Tf-T0)/Nt;
tout = T0+dTout;
printf(" t ||u||_rms\n");
printf(" -------------------------\n");
printf(" %10.6"FSYM" %10.6f\n", t, sqrt(N_VDotProd(y,y)/N));
for (iout=0; iout<Nt; iout++) {
flag = ARKStepEvolve(arkode_mem, tout, y, &t, ARK_NORMAL); /* call integrator */
if (check_flag(&flag, "ARKStepEvolve", 1)) break;
printf(" %10.6"FSYM" %10.6f\n", t, sqrt(N_VDotProd(y,y)/N)); /* print solution stats */
if (flag >= 0) { /* successful solve: update output time */
tout += dTout;
tout = (tout > Tf) ? Tf : tout;
} else { /* unsuccessful solve: break */
fprintf(stderr,"Solver failure, stopping integration\n");
break;
}
/* output results to disk */
for (i=0; i<N; i++) fprintf(UFID," %.16"ESYM"", data[i]);
fprintf(UFID,"\n");
}
printf(" -------------------------\n");
fclose(UFID);
/* Print some final statistics */
flag = ARKStepGetNumSteps(arkode_mem, &nst);
check_flag(&flag, "ARKStepGetNumSteps", 1);
flag = ARKStepGetNumStepAttempts(arkode_mem, &nst_a);
check_flag(&flag, "ARKStepGetNumStepAttempts", 1);
flag = ARKStepGetNumRhsEvals(arkode_mem, &nfe, &nfi);
check_flag(&flag, "ARKStepGetNumRhsEvals", 1);
flag = ARKStepGetNumLinSolvSetups(arkode_mem, &nsetups);
check_flag(&flag, "ARKStepGetNumLinSolvSetups", 1);
flag = ARKStepGetNumErrTestFails(arkode_mem, &netf);
check_flag(&flag, "ARKStepGetNumErrTestFails", 1);
flag = ARKStepGetNumNonlinSolvIters(arkode_mem, &nni);
check_flag(&flag, "ARKStepGetNumNonlinSolvIters", 1);
flag = ARKStepGetNumNonlinSolvConvFails(arkode_mem, &ncfn);
check_flag(&flag, "ARKStepGetNumNonlinSolvConvFails", 1);
flag = ARKStepGetNumLinIters(arkode_mem, &nli);
check_flag(&flag, "ARKStepGetNumLinIters", 1);
flag = ARKStepGetNumJtimesEvals(arkode_mem, &nJv);
check_flag(&flag, "ARKStepGetNumJtimesEvals", 1);
flag = ARKStepGetNumLinConvFails(arkode_mem, &nlcf);
check_flag(&flag, "ARKStepGetNumLinConvFails", 1);
printf("\nFinal Solver Statistics:\n");
printf(" Internal solver steps = %li (attempted = %li)\n", nst, nst_a);
printf(" Total RHS evals: Fe = %li, Fi = %li\n", nfe, nfi);
printf(" Total linear solver setups = %li\n", nsetups);
printf(" Total linear iterations = %li\n", nli);
printf(" Total number of Jacobian-vector products = %li\n", nJv);
printf(" Total number of linear solver convergence failures = %li\n", nlcf);
printf(" Total number of Newton iterations = %li\n", nni);
printf(" Total number of nonlinear solver convergence failures = %li\n", ncfn);
printf(" Total number of error test failures = %li\n", netf);
/* Clean up and return with successful completion */
N_VDestroy(y); /* Free vectors */
free(udata); /* Free user data */
ARKStepFree(&arkode_mem); /* Free integrator memory */
SUNLinSolFree(LS); /* Free linear solver */
return 0;
}
/*--------------------------------
* Functions called by the solver
*--------------------------------*/
/* f routine to compute the ODE RHS function f(t,y). */
static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data)
{
UserData udata = (UserData) user_data; /* access problem data */
sunindextype N = udata->N; /* set variable shortcuts */
realtype k = udata->k;
realtype dx = udata->dx;
realtype *Y=NULL, *Ydot=NULL;
realtype c1, c2;
sunindextype i, isource;
Y = N_VGetArrayPointer(y); /* access data arrays */
if (check_flag((void *) Y, "N_VGetArrayPointer", 0)) return 1;
Ydot = N_VGetArrayPointer(ydot);
if (check_flag((void *) Ydot, "N_VGetArrayPointer", 0)) return 1;
N_VConst(0.0, ydot); /* Initialize ydot to zero */
/* iterate over domain, computing all equations */
c1 = k/dx/dx;
c2 = -RCONST(2.0)*k/dx/dx;
isource = N/2;
Ydot[0] = 0.0; /* left boundary condition */
#pragma omp parallel for default(shared) private(i) schedule(static) num_threads(udata->nthreads)
for (i=1; i<N-1; i++)
Ydot[i] = c1*Y[i-1] + c2*Y[i] + c1*Y[i+1];
Ydot[N-1] = 0.0; /* right boundary condition */
Ydot[isource] += 0.01/dx; /* source term */
return 0; /* Return with success */
}
/* Jacobian routine to compute J(t,y) = df/dy. */
static int Jac(N_Vector v, N_Vector Jv, realtype t, N_Vector y,
N_Vector fy, void *user_data, N_Vector tmp)
{
UserData udata = (UserData) user_data; /* variable shortcuts */
sunindextype N = udata->N;
realtype k = udata->k;
realtype dx = udata->dx;
realtype *V=NULL, *JV=NULL;
realtype c1, c2;
sunindextype i;
V = N_VGetArrayPointer(v); /* access data arrays */
if (check_flag((void *) V, "N_VGetArrayPointer", 0)) return 1;
JV = N_VGetArrayPointer(Jv);
if (check_flag((void *) JV, "N_VGetArrayPointer", 0)) return 1;
N_VConst(0.0, Jv); /* initialize Jv product to zero */
/* iterate over domain, computing all Jacobian-vector products */
c1 = k/dx/dx;
c2 = -RCONST(2.0)*k/dx/dx;
JV[0] = 0.0;
#pragma omp parallel for default(shared) private(i) schedule(static) num_threads(udata->nthreads)
for (i=1; i<N-1; i++)
JV[i] = c1*V[i-1] + c2*V[i] + c1*V[i+1];
JV[N-1] = 0.0;
return 0; /* Return with success */
}
/*-------------------------------
* Private helper functions
*-------------------------------*/
/* 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;
}
/*---- end of file ----*/
|
idasFoodWeb_kry_omp.c | /*
* -----------------------------------------------------------------
* Programmer(s): Daniel R. Reynolds and Ting Yan @ SMU
* -----------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2020, 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 program for IDAS: Food web problem, OpenMP, GMRES,
* user-supplied preconditioner
*
* This example program uses SUNLinSol_SPGMR as the linear
* solver, and IDACalcIC for initial condition calculation.
*
* The mathematical problem solved in this example is a DAE system
* that arises from a system of partial differential equations after
* spatial discretization. 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:
*
* 1 2 ns
* c = (c , c , ..., c ) , ns = 2 * np
*
* and the PDE's are as follows:
*
* i i i
* dc /dt = d(i)*(c + c ) + R (x,y,c) (i = 1,...,np)
* xx yy i
*
* i i
* 0 = d(i)*(c + c ) + R (x,y,c) (i = np+1,...,ns)
* xx yy i
*
* where the reaction terms R are:
*
* i ns j
* R (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 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)
* all other a(i,j) = 0
* b(i) = BB*(1+ alpha * x*y + beta*sin(4 pi x)*sin(4 pi y)) (i <= np)
* b(i) =-BB*(1+ alpha * x*y + beta*sin(4 pi x)*sin(4 pi y)) (i > np)
* d(i) = DPREY (i <= np)
* d(i) = DPRED (i > np)
*
* The various scalar parameters required are set using '#define'
* statements or directly in routine InitUserData. In this program,
* np = 1, ns = 2. The boundary conditions are homogeneous Neumann:
* normal derivative = 0.
*
* A polynomial in x and y is used to set the initial values of the
* first np variables (the prey variables) at each x,y location,
* while initial values for the remaining (predator) variables are
* set to a flat value, which is corrected by IDACalcIC.
*
* The PDEs are discretized by central differencing on a MX by MY
* mesh.
*
* The DAE system is solved by IDAS using the SUNLinSol_SPGMR linear solver.
* Output is printed at t = 0, .001, .01, .1, .4, .7, 1.
*
* Optionally, we can set the number of threads from environment
* variable or command line. To check the current value for number
* of threads from environment:
* % echo $OMP_NUM_THREADS
*
* Execution:
*
* To use the default value for the number of threads from
* the OMP_NUM_THREADS environment value:
* % ./idasFoodWeb_kry_omp
* To specify the number of threads at the command line, use
* % ./idasFoodWeb_kry_omp num_threads
* where num_threads is the desired number of threads.
*
* -----------------------------------------------------------------
* References:
* [1] Peter N. Brown and Alan C. Hindmarsh,
* Reduced Storage Matrix Methods in Stiff ODE systems, Journal
* of Applied Mathematics and Computation, Vol. 31 (May 1989),
* pp. 40-91.
*
* [2] Peter N. Brown, Alan C. Hindmarsh, and Linda R. Petzold,
* Using Krylov Methods in the Solution of Large-Scale
* Differential-Algebraic Systems, SIAM J. Sci. Comput., 15
* (1994), pp. 1467-1488.
*
* [3] Peter N. Brown, Alan C. Hindmarsh, and Linda R. Petzold,
* Consistent Initial Condition Calculation for Differential-
* Algebraic Systems, SIAM J. Sci. Comput., 19 (1998),
* pp. 1495-1512.
* -----------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <idas/idas.h>
#include <sunlinsol/sunlinsol_spgmr.h>
#include <nvector/nvector_openmp.h>
#include <sundials/sundials_dense.h>
#include <sundials/sundials_types.h>
#ifdef _OPENMP
#include <omp.h>
#endif
/* helpful macros */
#ifndef MAX
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#endif
/* Problem Constants. */
#define NPREY 1 /* No. of prey (= no. of predators). */
#define NUM_SPECIES 2*NPREY
#define PI RCONST(3.1415926535898)
#define FOURPI (RCONST(4.0)*PI)
#define MX 20 /* MX = number of x mesh points */
#define MY 20 /* MY = number of y mesh points */
#define NSMX (NUM_SPECIES * MX)
#define NEQ (NUM_SPECIES*MX*MY)
#define AA RCONST(1.0) /* Coefficient in above eqns. for a */
#define EE RCONST(10000.) /* Coefficient in above eqns. for a */
#define GG RCONST(0.5e-6) /* Coefficient in above eqns. for a */
#define BB RCONST(1.0) /* Coefficient in above eqns. for b */
#define DPREY RCONST(1.0) /* Coefficient in above eqns. for d */
#define DPRED RCONST(0.05) /* Coefficient in above eqns. for d */
#define ALPHA RCONST(50.) /* Coefficient alpha in above eqns. */
#define BETA RCONST(1000.) /* Coefficient beta in above eqns. */
#define AX RCONST(1.0) /* Total range of x variable */
#define AY RCONST(1.0) /* Total range of y variable */
#define RTOL RCONST(1.e-5) /* Relative tolerance */
#define ATOL RCONST(1.e-5) /* Absolute tolerance */
#define NOUT 6 /* Number of output times */
#define TMULT RCONST(10.0) /* Multiplier for tout values */
#define TADD RCONST(0.3) /* Increment for tout values */
#define ZERO RCONST(0.)
#define ONE RCONST(1.0)
/*
* User-defined vector and accessor macro: IJ_Vptr.
* IJ_Vptr is defined in order to express the underlying 3-D structure of
* the dependent variable vector from its underlying 1-D storage (an N_Vector).
* IJ_Vptr(vv,i,j) returns a pointer to the location in vv corresponding to
* species index is = 0, x-index ix = i, and y-index jy = j.
*/
#define IJ_Vptr(vv,i,j) (&NV_Ith_OMP(vv, (i)*NUM_SPECIES + (j)*NSMX))
/* Type: UserData. Contains problem constants, etc. */
typedef struct {
sunindextype Neq, ns, np, mx, my;
realtype dx, dy, **acoef;
realtype cox[NUM_SPECIES], coy[NUM_SPECIES], bcoef[NUM_SPECIES];
realtype **PP[MX][MY];
sunindextype *pivot[MX][MY];
N_Vector rates;
N_Vector ewt;
void *ida_mem;
int nthreads;
} *UserData;
/* Prototypes for functions called by the IDA Solver. */
static int resweb(realtype time, N_Vector cc, N_Vector cp, N_Vector resval,
void *user_data);
static int Precond(realtype tt, N_Vector cc, N_Vector cp,
N_Vector rr, realtype cj, void *user_data);
static int PSolve(realtype tt, N_Vector cc, N_Vector cp,
N_Vector rr, N_Vector rvec, N_Vector zvec,
realtype cj, realtype delta, void *user_data);
/* Prototypes for private Helper Functions. */
static void InitUserData(UserData webdata);
static void SetInitialProfiles(N_Vector cc, N_Vector cp, N_Vector id,
UserData webdata);
static void PrintHeader(int maxl, realtype rtol, realtype atol);
static void PrintOutput(void *ida_mem, N_Vector c, realtype t);
static void PrintFinalStats(void *ida_mem);
static void Fweb(realtype tcalc, N_Vector cc, N_Vector crate, UserData webdata);
static void WebRates(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy,
UserData webdata);
static realtype dotprod(sunindextype size, realtype *x1, realtype *x2);
static int check_retval(void *returnvalue, char *funcname, int opt);
/*
*--------------------------------------------------------------------
* MAIN PROGRAM
*--------------------------------------------------------------------
*/
int main(int argc, char *argv[])
{
void *ida_mem;
SUNLinearSolver LS;
UserData webdata;
N_Vector cc, cp, id;
int iout, jx, jy, retval;
int maxl;
realtype rtol, atol, t0, tout, tret;
int num_threads;
ida_mem = NULL;
LS = NULL;
webdata = NULL;
cc = cp = id = NULL;
/* 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 */
#endif
if (argc > 1)
num_threads = (int) strtol(argv[1], NULL, 0);
/* Allocate and initialize user data block webdata. */
webdata = (UserData) malloc(sizeof *webdata);
webdata->rates = N_VNew_OpenMP(NEQ, num_threads);
webdata->acoef = newDenseMat(NUM_SPECIES, NUM_SPECIES);
webdata->ewt = N_VNew_OpenMP(NEQ, num_threads);
for (jx = 0; jx < MX; jx++) {
for (jy = 0; jy < MY; jy++) {
(webdata->pivot)[jx][jy] = newIndexArray(NUM_SPECIES);
(webdata->PP)[jx][jy] = newDenseMat(NUM_SPECIES, NUM_SPECIES);
}
}
webdata->nthreads = num_threads;
InitUserData(webdata);
/* Allocate N-vectors and initialize cc, cp, and id. */
cc = N_VNew_OpenMP(NEQ, num_threads);
if(check_retval((void *)cc, "N_VNew_OpenMP", 0)) return(1);
cp = N_VNew_OpenMP(NEQ, num_threads);
if(check_retval((void *)cp, "N_VNew_OpenMP", 0)) return(1);
id = N_VNew_OpenMP(NEQ, num_threads);
if(check_retval((void *)id, "N_VNew_OpenMP", 0)) return(1);
SetInitialProfiles(cc, cp, id, webdata);
/* Set remaining inputs to IDAMalloc. */
t0 = ZERO;
rtol = RTOL;
atol = ATOL;
/* Call IDACreate and IDAMalloc to initialize IDA. */
ida_mem = IDACreate();
if(check_retval((void *)ida_mem, "IDACreate", 0)) return(1);
retval = IDASetUserData(ida_mem, webdata);
if(check_retval(&retval, "IDASetUserData", 1)) return(1);
retval = IDASetId(ida_mem, id);
if(check_retval(&retval, "IDASetId", 1)) return(1);
retval = IDAInit(ida_mem, resweb, t0, cc, cp);
if(check_retval(&retval, "IDAInit", 1)) return(1);
retval = IDASStolerances(ida_mem, rtol, atol);
if(check_retval(&retval, "IDASStolerances", 1)) return(1);
webdata->ida_mem = ida_mem;
/* Create SUNLinSol_SPGMR linear solver, attach to IDA, and set
preconditioning routines. */
maxl = 16; /* max dimension of the Krylov subspace */
LS = SUNLinSol_SPGMR(cc, PREC_LEFT, maxl); /* IDA only allows left preconditioning */
if(check_retval((void *)LS, "SUNLinSol_SPGMR", 0)) return(1);
retval = IDASetLinearSolver(ida_mem, LS, NULL);
if(check_retval(&retval, "IDASetLinearSolver", 1)) return(1);
retval = IDASetPreconditioner(ida_mem, Precond, PSolve);
if(check_retval(&retval, "IDASetPreconditioner", 1)) return(1);
/* Call IDACalcIC (with default options) to correct the initial values. */
tout = RCONST(0.001);
retval = IDACalcIC(ida_mem, IDA_YA_YDP_INIT, tout);
if(check_retval(&retval, "IDACalcIC", 1)) return(1);
/* Print heading, basic parameters, and initial values. */
PrintHeader(maxl, rtol, atol);
PrintOutput(ida_mem, cc, ZERO);
/* Loop over iout, call IDASolve (normal mode), print selected output. */
for (iout = 1; iout <= NOUT; iout++) {
retval = IDASolve(ida_mem, tout, &tret, cc, cp, IDA_NORMAL);
if(check_retval(&retval, "IDASolve", 1)) return(retval);
PrintOutput(ida_mem, cc, tret);
if (iout < 3) tout *= TMULT; else tout += TADD;
}
/* Print final statistics and free memory. */
PrintFinalStats(ida_mem);
printf("num_threads = %i\n\n", num_threads);
/* Free memory */
IDAFree(&ida_mem);
SUNLinSolFree(LS);
N_VDestroy(cc);
N_VDestroy(cp);
N_VDestroy(id);
destroyMat(webdata->acoef);
N_VDestroy(webdata->rates);
N_VDestroy(webdata->ewt);
for (jx = 0; jx < MX; jx++) {
for (jy = 0; jy < MY; jy ++) {
destroyArray((webdata->pivot)[jx][jy]);
destroyMat((webdata->PP)[jx][jy]);
}
}
free(webdata);
return(0);
}
/* Define lines for readability in later routines */
#define acoef (webdata->acoef)
#define bcoef (webdata->bcoef)
#define cox (webdata->cox)
#define coy (webdata->coy)
/*
*--------------------------------------------------------------------
* FUNCTIONS CALLED BY IDA
*--------------------------------------------------------------------
*/
/*
* resweb: System residual function for predator-prey system.
* This routine calls Fweb to get all the right-hand sides of the
* equations, then loads the residual vector accordingly,
* using cp in the case of prey species.
*/
static int resweb(realtype tt, N_Vector cc, N_Vector cp,
N_Vector res, void *user_data)
{
sunindextype jx, jy, is, yloc, loc, np;
realtype *resv, *cpv;
UserData webdata;
jx = jy = is = 0;
webdata = (UserData)user_data;
cpv = NV_DATA_OMP(cp);
resv = NV_DATA_OMP(res);
np = webdata->np;
/* Call Fweb to set res to vector of right-hand sides. */
Fweb(tt, cc, res, webdata);
/* Loop over all grid points, setting residual values appropriately
for differential or algebraic components. */
#pragma omp parallel for default(shared) private(jy, jx, is, yloc, loc) schedule(static) num_threads(webdata->nthreads)
for (jy = 0; jy < MY; jy++) {
yloc = NSMX * jy;
for (jx = 0; jx < MX; jx++) {
loc = yloc + NUM_SPECIES * jx;
for (is = 0; is < NUM_SPECIES; is++) {
if (is < np)
resv[loc+is] = cpv[loc+is] - resv[loc+is];
else
resv[loc+is] = -resv[loc+is];
}
}
}
return(0);
}
static int Precond(realtype tt, N_Vector cc, N_Vector cp,
N_Vector rr, realtype cj, void *user_data)
{
int retval;
sunindextype ret;
realtype uround, xx, yy, del_x, del_y;
realtype **Pxy, *ratesxy, *Pxycol, *cxy, *cpxy, *ewtxy, cctmp;
realtype inc, fac, sqru, perturb_rates[NUM_SPECIES];
int is, js, jx, jy;
void *ida_mem;
N_Vector ewt;
realtype hh;
UserData webdata;
webdata = (UserData) user_data;
del_x = webdata->dx;
del_y = webdata->dy;
uround = UNIT_ROUNDOFF;
sqru = sqrt(uround);
ida_mem = webdata->ida_mem;
ewt = webdata->ewt;
retval = IDAGetErrWeights(ida_mem, ewt);
if(check_retval(&retval, "IDAGetErrWeights", 1)) return(1);
retval = IDAGetCurrentStep(ida_mem, &hh);
if(check_retval(&retval, "IDAGetCurrentStep", 1)) return(1);
for (jy = 0; jy < MY; jy++) {
yy = jy * del_y;
for (jx = 0; jx < MX; jx++) {
xx = jx * del_x;
Pxy = (webdata->PP)[jx][jy];
cxy = IJ_Vptr(cc, jx, jy);
cpxy = IJ_Vptr(cp, jx, jy);
ewtxy = IJ_Vptr(ewt, jx, jy);
ratesxy = IJ_Vptr((webdata->rates), jx, jy);
for (js = 0; js < NUM_SPECIES; js++) {
inc = sqru*(MAX(fabs(cxy[js]), MAX(hh*fabs(cpxy[js]), ONE/ewtxy[js])));
cctmp = cxy[js];
cxy[js] += inc;
fac = -ONE/inc;
WebRates(xx, yy, cxy, perturb_rates, webdata);
Pxycol = Pxy[js];
for (is = 0; is < NUM_SPECIES; is++)
Pxycol[is] = (perturb_rates[is] - ratesxy[is])*fac;
if (js < 1) Pxycol[js] += cj;
cxy[js] = cctmp;
}
ret = denseGETRF(Pxy, NUM_SPECIES, NUM_SPECIES, (webdata->pivot)[jx][jy]);
if (ret != 0) return(1);
}
}
return(0);
}
static int PSolve(realtype tt, N_Vector cc, N_Vector cp,
N_Vector rr, N_Vector rvec, N_Vector zvec,
realtype cj, realtype dalta, void *user_data)
{
realtype **Pxy, *zxy;
sunindextype *pivot;
sunindextype jx, jy;
UserData webdata;
jx = jy = 0;
webdata = (UserData) user_data;
N_VScale(ONE, rvec, zvec);
#pragma omp parallel for collapse(2) default(shared) private(jx, jy, zxy, Pxy, pivot) schedule(static) num_threads(webdata->nthreads)
for (jx = 0; jx < MX; jx++) {
for (jy = 0; jy <MY; jy++) {
zxy = IJ_Vptr(zvec, jx, jy);
Pxy = (webdata->PP)[jx][jy];
pivot = (webdata->pivot)[jx][jy];
denseGETRS(Pxy, NUM_SPECIES, pivot, zxy);
}
}
return(0);
}
/*
*--------------------------------------------------------------------
* PRIVATE FUNCTIONS
*--------------------------------------------------------------------
*/
/*
* InitUserData: Load problem constants in webdata (of type UserData).
*/
static void InitUserData(UserData webdata)
{
sunindextype i, j, np;
realtype *a1,*a2, *a3, *a4, dx2, dy2;
webdata->mx = MX;
webdata->my = MY;
webdata->ns = NUM_SPECIES;
webdata->np = NPREY;
webdata->dx = AX/(MX-1);
webdata->dy = AY/(MY-1);
webdata->Neq= NEQ;
/* Set up the coefficients a and b, and others found in the equations. */
np = webdata->np;
dx2 = (webdata->dx)*(webdata->dx); dy2 = (webdata->dy)*(webdata->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;
}
/* Reset the diagonal elements of acoef to -AA. */
acoef[i][i] = -AA; acoef[i+np][i+np] = -AA;
/* Set coefficients for b and diffusion terms. */
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;
}
}
/*
* SetInitialProfiles: Set initial conditions in cc, cp, and id.
* A polynomial profile is used for the prey cc values, and a constant
* (1.0e5) is loaded as the initial guess for the predator cc values.
* The id values are set to 1 for the prey and 0 for the predators.
* The prey cp values are set according to the given system, and
* the predator cp values are set to zero.
*/
static void SetInitialProfiles(N_Vector cc, N_Vector cp, N_Vector id,
UserData webdata)
{
sunindextype loc, yloc, is, jx, jy, np;
realtype xx, yy, xyfactor;
realtype *ccv, *cpv, *idv;
ccv = NV_DATA_OMP(cc);
cpv = NV_DATA_OMP(cp);
idv = NV_DATA_OMP(id);
np = webdata->np;
/* Loop over grid, load cc values and id values. */
for (jy = 0; jy < MY; jy++) {
yy = jy * webdata->dy;
yloc = NSMX * jy;
for (jx = 0; jx < MX; jx++) {
xx = jx * webdata->dx;
xyfactor = RCONST(16.0)*xx*(ONE-xx)*yy*(ONE-yy);
xyfactor *= xyfactor;
loc = yloc + NUM_SPECIES*jx;
for (is = 0; is < NUM_SPECIES; is++) {
if (is < np) {
ccv[loc+is] = RCONST(10.0) + (realtype)(is+1) * xyfactor;
idv[loc+is] = ONE;
}
else {
ccv[loc+is] = RCONST(1.0e5);
idv[loc+is] = ZERO;
}
}
}
}
/* Set c' for the prey by calling the function Fweb. */
Fweb(ZERO, cc, cp, webdata);
/* Set c' for predators to 0. */
for (jy = 0; jy < MY; jy++) {
yloc = NSMX * jy;
for (jx = 0; jx < MX; jx++) {
loc = yloc + NUM_SPECIES * jx;
for (is = np; is < NUM_SPECIES; is++) {
cpv[loc+is] = ZERO;
}
}
}
}
/*
* Print first lines of output (problem description)
*/
static void PrintHeader(int maxl, realtype rtol, realtype atol)
{
printf("\nidasFoodWeb_kry_omp: Predator-prey DAE OpenMP example problem using Krylov solver for IDAS \n\n");
printf("Number of species ns: %d", NUM_SPECIES);
printf(" Mesh dimensions: %d x %d", MX, MY);
printf(" System size: %d\n", NEQ);
#if defined(SUNDIALS_EXTENDED_PRECISION)
printf("Tolerance parameters: rtol = %Lg atol = %Lg\n", rtol, atol);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
printf("Tolerance parameters: rtol = %g atol = %g\n", rtol, atol);
#else
printf("Tolerance parameters: rtol = %g atol = %g\n", rtol, atol);
#endif
printf("Linear solver: SUNLinSol_SPGMR, maxl = %d\n", maxl);
printf("CalcIC called to correct initial predator concentrations.\n\n");
printf("-----------------------------------------------------------\n");
printf(" t bottom-left top-right");
printf(" | nst k h\n");
printf("-----------------------------------------------------------\n\n");
}
/*
* PrintOutput: Print output values at output time t = tt.
* Selected run statistics are printed. Then values of the concentrations
* are printed for the bottom left and top right grid points only.
*/
static void PrintOutput(void *ida_mem, N_Vector c, realtype t)
{
int i, kused, retval;
long int nst;
realtype *c_bl, *c_tr, hused;
retval = IDAGetLastOrder(ida_mem, &kused);
check_retval(&retval, "IDAGetLastOrder", 1);
retval = IDAGetNumSteps(ida_mem, &nst);
check_retval(&retval, "IDAGetNumSteps", 1);
retval = IDAGetLastStep(ida_mem, &hused);
check_retval(&retval, "IDAGetLastStep", 1);
c_bl = IJ_Vptr(c,0,0);
c_tr = IJ_Vptr(c,MX-1,MY-1);
#if defined(SUNDIALS_EXTENDED_PRECISION)
printf("%8.2Le %12.4Le %12.4Le | %3ld %1d %12.4Le\n",
t, c_bl[0], c_tr[0], nst, kused, hused);
for (i=1;i<NUM_SPECIES;i++)
printf(" %12.4Le %12.4Le |\n",c_bl[i],c_tr[i]);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
printf("%8.2e %12.4e %12.4e | %3ld %1d %12.4e\n",
t, c_bl[0], c_tr[0], nst, kused, hused);
for (i=1;i<NUM_SPECIES;i++)
printf(" %12.4e %12.4e |\n",c_bl[i],c_tr[i]);
#else
printf("%8.2e %12.4e %12.4e | %3ld %1d %12.4e\n",
t, c_bl[0], c_tr[0], nst, kused, hused);
for (i=1;i<NUM_SPECIES;i++)
printf(" %12.4e %12.4e |\n",c_bl[i],c_tr[i]);
#endif
printf("\n");
}
/*
* PrintFinalStats: Print final run data contained in iopt.
*/
static void PrintFinalStats(void *ida_mem)
{
long int nst, nre, sli, netf, nps, npevals, nrevalsLS;
int retval;
retval = IDAGetNumSteps(ida_mem, &nst);
check_retval(&retval, "IDAGetNumSteps", 1);
retval = IDAGetNumLinIters(ida_mem, &sli);
check_retval(&retval, "IDAGetNumLinIters", 1);
retval = IDAGetNumResEvals(ida_mem, &nre);
check_retval(&retval, "IDAGetNumResEvals", 1);
retval = IDAGetNumErrTestFails(ida_mem, &netf);
check_retval(&retval, "IDAGetNumErrTestFails", 1);
retval = IDAGetNumPrecSolves(ida_mem, &nps);
check_retval(&retval, "IDAGetNumPrecSolves", 1);
retval = IDAGetNumPrecEvals(ida_mem, &npevals);
check_retval(&retval, "IDAGetNumPrecEvals", 1);
retval = IDAGetNumLinResEvals(ida_mem, &nrevalsLS);
check_retval(&retval, "IDAGetNumLinResEvals", 1);
printf("-----------------------------------------------------------\n");
printf("Final run statistics: \n\n");
printf("Number of steps = %ld\n", nst);
printf("Number of residual evaluations = %ld\n", nre);
printf("Number of Preconditioner evaluations = %ld\n", npevals);
printf("Number of linear iterations = %ld\n", sli);
printf("Number of error test failures = %ld\n", netf);
printf("Number of precond solve fun called = %ld\n", nps);
}
/*
* Fweb: Rate function for the food-web problem.
* This routine computes the right-hand sides of the system equations,
* consisting of the diffusion term and interaction term.
* The interaction term is computed by the function WebRates.
*/
static void Fweb(realtype tcalc, N_Vector cc, N_Vector crate,
UserData webdata)
{
sunindextype jx, jy, is, idyu, idyl, idxu, idxl;
realtype xx, yy, *cxy, *ratesxy, *cratexy, dcyli, dcyui, dcxli, dcxui;
/* Loop over grid points, evaluate interaction vector (length ns),
form diffusion difference terms, and load crate. */
jx = jy = is = 0;
for (jy = 0; jy < MY; jy++) {
yy = (webdata->dy) * jy ;
idyu = (jy!=MY-1) ? NSMX : -NSMX;
idyl = (jy!= 0 ) ? NSMX : -NSMX;
for (jx = 0; jx < MX; jx++) {
xx = (webdata->dx) * jx;
idxu = (jx!= MX-1) ? NUM_SPECIES : -NUM_SPECIES;
idxl = (jx!= 0 ) ? NUM_SPECIES : -NUM_SPECIES;
cxy = IJ_Vptr(cc,jx,jy);
ratesxy = IJ_Vptr(webdata->rates,jx,jy);
cratexy = IJ_Vptr(crate,jx,jy);
/* Get interaction vector at this grid point. */
WebRates(xx, yy, cxy, ratesxy, webdata);
/* Loop over species, do differencing, load crate segment. */
#pragma omp parallel for default(shared) private(is, dcyli, dcyui, dcxli, dcxui) schedule(static) num_threads(webdata->nthreads)
for (is = 0; is < NUM_SPECIES; is++) {
/* Differencing in y. */
dcyli = *(cxy+is) - *(cxy - idyl + is) ;
dcyui = *(cxy + idyu + is) - *(cxy+is);
/* Differencing in x. */
dcxli = *(cxy+is) - *(cxy - idxl + is);
dcxui = *(cxy + idxu +is) - *(cxy+is);
/* Compute the crate values at (xx,yy). */
cratexy[is] = coy[is] * (dcyui - dcyli) +
cox[is] * (dcxui - dcxli) + ratesxy[is];
} /* End is loop */
} /* End of jx loop */
} /* End of jy loop */
}
/*
* WebRates: Evaluate reaction rates at a given spatial point.
* At a given (x,y), evaluate the array of ns reaction terms R.
*/
static void WebRates(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy,
UserData webdata)
{
int is;
realtype fac;
for (is = 0; is < NUM_SPECIES; is++)
ratesxy[is] = dotprod(NUM_SPECIES, cxy, acoef[is]);
fac = ONE + ALPHA*xx*yy + BETA*sin(FOURPI*xx)*sin(FOURPI*yy);
for (is = 0; is < NUM_SPECIES; is++)
ratesxy[is] = cxy[is]*( bcoef[is]*fac + ratesxy[is] );
}
/*
* dotprod: dot product routine for realtype arrays, for use by WebRates.
*/
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);
}
/*
* Check function return value...
* opt == 0 means SUNDIALS function allocates memory so check if
* returned NULL pointer
* opt == 1 means SUNDIALS function returns an integer value so check if
* retval < 0
* opt == 2 means function allocates memory so check if returned
* NULL pointer
*/
static int check_retval(void *returnvalue, char *funcname, int opt)
{
int *retval;
if (opt == 0 && returnvalue == NULL) {
/* Check if SUNDIALS function returned NULL pointer - no memory allocated */
fprintf(stderr,
"\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1);
} else if (opt == 1) {
/* Check if retval < 0 */
retval = (int *) returnvalue;
if (*retval < 0) {
fprintf(stderr,
"\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n",
funcname, *retval);
return(1);
}
} else if (opt == 2 && returnvalue == NULL) {
/* Check if function returned NULL pointer - no memory allocated */
fprintf(stderr,
"\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1);
}
return(0);
}
|
GB_binop__second_int64.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__second_int64)
// A.*B function (eWiseMult): GB (_AemultB_08__second_int64)
// A.*B function (eWiseMult): GB (_AemultB_02__second_int64)
// A.*B function (eWiseMult): GB (_AemultB_04__second_int64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__second_int64)
// A*D function (colscale): GB (_AxD__second_int64)
// D*A function (rowscale): GB (_DxB__second_int64)
// C+=B function (dense accum): GB (_Cdense_accumB__second_int64)
// C+=b function (dense accum): GB (_Cdense_accumb__second_int64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_int64)
// C=scalar+B GB ((none))
// C=scalar+B' GB ((none))
// C=A+scalar GB ((none))
// C=A'+scalar GB ((none))
// C type: int64_t
// A type: int64_t
// A pattern? 1
// B type: int64_t
// B pattern? 0
// BinaryOp: cij = bij
#define GB_ATYPE \
int64_t
#define GB_BTYPE \
int64_t
#define GB_CTYPE \
int64_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) \
;
// true if values of A are not used
#define GB_A_IS_PATTERN \
1 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int64_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) \
int64_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 = y ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
1
// 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_SECOND || GxB_NO_INT64 || GxB_NO_SECOND_INT64)
//------------------------------------------------------------------------------
// 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__second_int64)
(
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__second_int64)
(
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__second_int64)
(
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 int64_t
int64_t bwork = (*((int64_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__second_int64)
(
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
int64_t *restrict Cx = (int64_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__second_int64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_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__second_int64)
(
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) ;
int64_t alpha_scalar ;
int64_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int64_t *) alpha_scalar_in)) ;
beta_scalar = (*((int64_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__second_int64)
(
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__second_int64)
(
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__second_int64)
(
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__second_int64)
(
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
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
int64_t *Cx = (int64_t *) Cx_output ;
int64_t x = (*((int64_t *) x_input)) ;
int64_t *Bx = (int64_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 ;
int64_t bij = GBX (Bx, p, false) ;
Cx [p] = bij ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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 ;
int64_t *Cx = (int64_t *) Cx_output ;
int64_t *Ax = (int64_t *) Ax_input ;
int64_t y = (*((int64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
; ;
Cx [p] = y ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = aij ; \
}
GrB_Info GB ((none))
(
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 \
int64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t x = (*((const int64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int64_t
}
#endif
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = y ; \
}
GrB_Info GB ((none))
(
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
int64_t y = (*((const int64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
#endif
|
pslangb.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/pzlangb.c, normal z -> s, Fri Sep 28 17:38:12 2018
*
**/
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_types.h"
#include "plasma_workspace.h"
#include <plasma_core_blas.h>
#include "core_lapack.h"
#define A(m, n) (float*)plasma_tile_addr(A, m, n)
/***************************************************************************//**
* Parallel tile calculation of max, one, infinity or Frobenius matrix norm
* for a general band matrix.
******************************************************************************/
void plasma_pslangb(plasma_enum_t norm,
plasma_desc_t A, float *work, float *value,
plasma_sequence_t *sequence, plasma_request_t *request)
{
// Return if failed sequence.
if (sequence->status != PlasmaSuccess)
return;
float stub;
int wcnt = 0;
int ldwork, klt, kut;
float *workspace, *scale, *sumsq;
switch (norm) {
//================
// PlasmaMaxNorm
//================
case PlasmaMaxNorm:
wcnt = 0;
for (int n = 0; n < A.nt; n++ ) {
int nvan = plasma_tile_nview(A, n);
int m_start = (imax(0, n*A.nb-A.ku)) / A.nb;
int m_end = (imin(A.m-1, (n+1)*A.nb+A.kl-1)) / A.nb;
for (int m = m_start; m <= m_end; m++ ) {
int ldam = plasma_tile_mmain_band(A, m, n);
int mvam = plasma_tile_mview(A, m);
plasma_core_omp_slange(PlasmaMaxNorm,
mvam, nvan,
A(m, n), ldam,
&stub, &work[wcnt],
sequence, request);
wcnt++;
}
}
#pragma omp taskwait
plasma_core_omp_slange(PlasmaMaxNorm,
1, wcnt,
work, 1,
&stub, value,
sequence, request);
break;
//================
// PlasmaOneNorm
//================
case PlasmaOneNorm:
// # of tiles in upper band (not including diagonal)
kut = (A.ku+A.nb-1)/A.nb;
// # of tiles in lower band (not including diagonal)
klt = (A.kl+A.nb-1)/A.nb;
ldwork = kut+klt+1;
for (int n = 0; n < A.nt; n++ ) {
int nvan = plasma_tile_nview(A, n);
int m_start = (imax(0, n*A.nb-A.ku)) / A.nb;
int m_end = (imin(A.m-1, (n+1)*A.nb+A.kl-1)) / A.nb;
for (int m = m_start; m <= m_end; m++ ) {
int ldam = plasma_tile_mmain_band(A, m, n);
int mvam = plasma_tile_mview(A, m);
plasma_core_omp_slange_aux(PlasmaOneNorm,
mvam, nvan,
A(m,n), ldam,
&work[(m-m_start)*A.n+n*A.nb],
sequence, request);
}
}
#pragma omp taskwait
workspace = &work[A.n*ldwork];
plasma_core_omp_slange(PlasmaInfNorm,
A.n, ldwork,
work, A.n,
workspace, value,
sequence, request);
break;
//================
// PlasmaInfNorm
//================
case PlasmaInfNorm:
ldwork = A.mb*A.mt;
for (int n = 0; n < A.nt; n++ ) {
int nvan = plasma_tile_nview(A, n);
int m_start = (imax(0, n*A.nb-A.ku)) / A.nb;
int m_end = (imin(A.m-1, (n+1)*A.nb+A.kl-1)) / A.nb;
for (int m = m_start; m <= m_end; m++ ) {
int ldam = plasma_tile_mmain_band(A, m, n);
int mvam = plasma_tile_mview(A, m);
plasma_core_omp_slange_aux(PlasmaInfNorm,
mvam, nvan,
A(m,n), ldam,
&work[m*A.mb+n*ldwork],
sequence, request);
}
}
#pragma omp taskwait
//nwork = A.nt;
workspace = &work[ldwork*A.nt];
plasma_core_omp_slange(PlasmaInfNorm,
ldwork, A.nt,
work, ldwork,
workspace, value,
sequence, request);
break;
//======================
// PlasmaFrobeniusNorm
//======================
case PlasmaFrobeniusNorm:
kut = (A.ku+A.nb-1)/A.nb; // # of tiles in upper band (not including diagonal)
klt = (A.kl+A.nb-1)/A.nb; // # of tiles in lower band (not including diagonal)
ldwork = kut+klt+1;
scale = work;
sumsq = &work[ldwork*A.nt];
for (int n = 0; n < A.nt; n++ ) {
int nvan = plasma_tile_nview(A, n);
int m_start = (imax(0, n*A.nb-A.ku)) / A.nb;
int m_end = (imin(A.m-1, (n+1)*A.nb+A.kl-1)) / A.nb;
for (int m = m_start; m <= m_end; m++ ) {
int ldam = plasma_tile_mmain_band(A, m, n);
int mvam = plasma_tile_mview(A, m);
plasma_core_omp_sgessq(mvam, nvan,
A(m,n), ldam,
&scale[n*ldwork+m-m_start],
&sumsq[n*ldwork+m-m_start],
sequence, request);
}
}
#pragma omp taskwait
plasma_core_omp_sgessq_aux(ldwork*A.nt, scale, sumsq,
value, sequence, request);
break;
default:
assert(0);
}
}
|
matrix_mul.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
typedef double TYPE;
#define MIN 1
#define MAX 1000
void printMatrix(int, TYPE*, FILE*);
TYPE* generateMatrix(int);
TYPE* generateEmptyMatrix(int);
TYPE* matrixMulParOne(int, TYPE*, TYPE*, TYPE*, int);
TYPE* matrixMulParTwo(int, TYPE*, TYPE*, TYPE*, int);
TYPE* matrixMulParThree(int, TYPE*, TYPE*, TYPE*, int);
TYPE* generateMatrix(int dims){
TYPE* M = (TYPE *)malloc(dims*dims*sizeof(TYPE));
struct timeval t;
gettimeofday(&t, NULL);
unsigned long long u = t.tv_sec*1000000 + t.tv_usec;
srand(u);
for(int i=0; i<dims; ++i){
for(int j=0; j<dims; ++j){
M[i*dims+j] = (TYPE)(rand()%MAX+ MIN);
}
}
return M;
}
TYPE* generateEmptyMatrix(int dims){
return (TYPE *)calloc(dims*dims, sizeof(TYPE));
}
void clearMatrix(int dims, TYPE *C){
for(int i=0; i<dims; ++i){
for(int j=0; j<dims; ++j){
C[i*dims+j] = 0;
}
}
}
TYPE* matrixMulParOne(int dims, TYPE* A, TYPE* B, TYPE* C, int threads){
#pragma omp parallel for collapse(1) num_threads(threads)
for(int i=0; i<dims; ++i){
for(int j=0; j<dims; ++j){
for(int k=0; k<dims; ++k){
C[i*dims+j] += A[i*dims+k]*B[k*dims+j];
}
}
}
return C;
}
TYPE* matrixMulParTwo(int dims, TYPE* A, TYPE* B, TYPE* C, int threads){
#pragma omp parallel for collapse(2) num_threads(threads)
for(int i=0; i<dims; ++i){
for(int j=0; j<dims; ++j){
for(int k=0; k<dims; ++k){
C[i*dims+j] += A[i*dims+k]*B[k*dims+j];
}
}
}
return C;
}
TYPE* matrixMulParThree(int dims, TYPE* A, TYPE* B, TYPE* C, int threads){
#pragma omp parallel for collapse(3) num_threads(threads)
for(int i=0; i<dims; ++i){
for(int j=0; j<dims; ++j){
for(int k=0; k<dims; ++k){
C[i*dims+j] += A[i*dims+k]*B[k*dims+j];
}
}
}
return C;
}
void printMatrix(int dims, TYPE* M, FILE* fp){
fprintf(fp, "Dimensions of matrix = %d %d\n", dims, dims);
fprintf(fp, "Matrix: \n");
for(int i=0; i<dims; ++i){
for(int j=0; j<dims; ++j){
fprintf(fp, "%.0f ", M[i*dims+j]);
}
fprintf(fp, "\n");
}
}
int main(int argc, char* argv[]){
int dims, threads;
unsigned long long delta_us;
struct timeval start, end;
FILE *input = fopen("generated_input.txt", "w");
FILE *output = fopen("output.txt", "w");
printf("Enter matrix dimensions\n");
scanf("%d", &dims);
printf("Enter number of threads\n");
scanf("%d", &threads);
TYPE *A = generateMatrix(dims);
printMatrix(dims, A, input);
TYPE *B = generateMatrix(dims);
printMatrix(dims, B, input);
fclose(input);
TYPE *C = generateEmptyMatrix(dims);
gettimeofday(&start, NULL);
C = matrixMulParOne(dims, A, B, C, threads);
gettimeofday(&end, NULL);
delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec);
printf("Time taken if only outermost loop parallelized = %llu microseconds\n", delta_us);
printMatrix(dims, C, output);
clearMatrix(dims, C);
gettimeofday(&start, NULL);
C = matrixMulParTwo(dims, A, B, C, threads);
gettimeofday(&end, NULL);
delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec);
printf("Time taken if the two outer loops are parallelized = %llu microseconds\n", delta_us);
printMatrix(dims, C, output);
clearMatrix(dims, C);
gettimeofday(&start, NULL);
C = matrixMulParThree(dims, A, B, C, threads);
gettimeofday(&end, NULL);
delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec);
printf("Time taken if all threee loops are parallelized = %llu microseconds\n", delta_us);
printMatrix(dims, C, output);
fclose(output);
return 0;
} |
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_triangles() 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++)
{
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))
{
for (auto& triangle : aabb.get_triangles())
{
payload payload = intersection_shader(triangle, ray);
if (payload.t > min_t && payload.t < closest_hit_payload.t)
{
closest_hit_payload = payload;
closest_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 epsilon = 1e-8f;
if (abs(det) < epsilon)
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_triangles() 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 |
construction.h | /*
An Experimental Study on Hub Labeling based Shortest Path Algorithms [Experiments and Analyses]
Authors: Ye Li, Leong Hou U, Man Lung Yiu, Ngai Meng Kou
Contact: yb47438@umac.mo
Affiliation: University of Macau
The MIT License (MIT)
Copyright (c) 2016 University of Macau
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#ifndef CONSTRUCTION_H
#define CONSTRUCTION_H
#include <queue>
#include <set>
#include "graph.h"
#include "paras.h"
#include "labels.h"
#include "ordering.h"
#include "heap.h"
#include "graph_search.h"
#include <omp.h>
#include <unordered_map>
#define numOfVertices SP_Constants::numOfVertices
#define numOfEdges SP_Constants::numOfEdges
#define INF_WEIGHT SP_Constants::INF_WEIGHT
class construction {
public:
Label labels;
DLabel dlabels;
PLabel plabels;
DPLabel dplabels;
CLabel clabels;
Ordering orders;
};
class PL : public construction {
public:
vector<double> iteration_generated;
vector<double> pruning_power;
PL(Graph &graph, Ordering &orders) {
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t>& index_ = labels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
//vector<vector<NodeID> > &adj = graph.adj;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<bool> vis(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
index_t &idx_v = index_[inv[v]];
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
if (td <= d) {
pruning_power[w]++;
goto pruned;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];*/
for (EdgeID eid = graph.vertices[v]; eid < graph.vertices[v + 1]; ++eid){
NodeID w = graph.edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
// Added by Johnpzh 02/13/2019
uint64_t amount = 0;
// Ended by Johnpzh
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k - 1;
// Ended by Johnpzh
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
}
// Added by Johnpzh 02/13/2019
// amount = (double)(amount) / 2;
cout << "avg_label_size: " << (double)(amount)/(double)numOfVertices << endl;
// Ended by Johnpzh
}
PL(Graph &graph, Ordering &orders, bool D_FLAGS) {
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t>& index_ = dlabels.index_;
vector<index_t>& bindex_ = dlabels.bindex_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
/* vector<vector<NodeID> > &adj = graph.adj;
vector<vector<NodeID> > &r_adj = graph.r_adj;*/
// Array Representation
vector<EdgeID>& vertices = graph.vertices;
vector<EdgeID>& r_vertices = graph.r_vertices;
vector<NodeID>& edges = graph.edges;
vector<NodeID>& r_edges = graph.r_edges;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT))); // Backward labels.
vector<bool> vis(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT); // Forward labels of root.
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT); // Backward labels of root.
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
// Forward search.
// Initialize forward labels of r.
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_v = r_tmp_idx[v];
//index_t &idx_v = index_[inv[v]];
if (usd[v]) continue;
// Pruned by the forward labels of r and backward labels of v in the forward search from r when reaching v.
for (size_t i = 0; i < r_tmp_idx_v.first.size(); ++i) {
NodeID w = r_tmp_idx_v.first[i];
EdgeWeight td = r_tmp_idx_v.second[i] + dst_r[w];
if (td <= d) {
pruning_power[w]++;
goto pruned_forward;
}
}
// Traverse
r_tmp_idx_v.first.back() = r;
r_tmp_idx_v.second.back() = d;
r_tmp_idx_v.first.push_back(numOfVertices);
r_tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];*/
// Array Representation
for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid){
NodeID w = edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned_forward:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
// Backward search.
// Initialize backward labels of r.
const pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_r = r_tmp_idx[r];
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i) {
r_dst_r[r_tmp_idx_r.first[i]] = r_tmp_idx_r.second[i];
}
que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
//index_t &idx_v = index_[inv[v]];
if (usd[v]) continue;
// Pruned by the backward labels of r and forward labels of v in the backward search from r when reaching v (v->r path).
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + r_dst_r[w];
if (td <= d) {
pruning_power[w]++;
goto pruned_backward;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < r_adj[v].size(); ++i) {
NodeID w = r_adj[v][i];*/
// Array Representation
for (EdgeID eid = r_vertices[v]; eid < r_vertices[v + 1]; ++eid) {
NodeID w = r_edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned_backward:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i)
r_dst_r[r_tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
// Added by Johnpzh 02/13/2019
uint64_t amount = 0;
// Ended by Johnpzh
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k;
// Ended by Johnpzh
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
k = r_tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k;
// Ended by Johnpzh
bindex_[inv[v]].spt_v.resize(k);
bindex_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_v[i] = r_tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_d[i] = r_tmp_idx[v].second[i];
r_tmp_idx[v].first.clear();
r_tmp_idx[v].second.clear();
r_tmp_idx[v].first.shrink_to_fit();
r_tmp_idx[v].second.shrink_to_fit();
}
// Added by Johnpzh 02/13/2019
amount = (double)(amount) / 2;
cout << "avg_label_size: " << (double)(amount)/(double)numOfVertices - 1 << endl;
// Ended by Johnpzh
}
void TD_BP_UNDIRECTED(Graph& graph, Ordering &orderes, int kNumBitParallelRoots, bool directed = false, bool bp = true) {
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t>& index_ = labels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
//vector<vector<NodeID> > &adj = graph.adj;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<bool> vis(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
index_t &idx_v = index_[inv[v]];
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
if (td <= d) {
pruning_power[w]++;
goto pruned;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];*/
for (EdgeID eid = graph.vertices[v]; eid < graph.vertices[v + 1]; ++eid) {
NodeID w = graph.edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
}
}
void TP_path(Graph &graph, Ordering &orders) {
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t_path>& index_ = plabels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
//vector<vector<NodeID> > &adj = graph.adj;
vector<bool> usd(numOfVertices, false);
vector<NodeID> parents(numOfVertices, numOfVertices);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<NodeID> > >
tmp_idx_parents(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<NodeID>(1, numOfVertices)));
vector<bool> vis(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
parents[r] = inv[r];
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
pair<vector<NodeID>, vector<NodeID> > &tmp_idx_parent_v = tmp_idx_parents[v];
index_t_path &idx_v = index_[inv[v]];
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
if (td <= d) {
pruning_power[w]++;
goto pruned;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
tmp_idx_parent_v.first.back() = r;
tmp_idx_parent_v.second.back() = parents[v];
tmp_idx_parent_v.first.push_back(numOfVertices);
tmp_idx_parent_v.second.push_back(numOfVertices);
iteration_generated[r]++;
/*for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];*/
for (EdgeID eid = graph.vertices[v]; eid < graph.vertices[v + 1]; ++eid) {
NodeID w = graph.edges[eid];
if (!vis[w]) {
parents[w] = inv[v];
que[que_h++] = w;
vis[w] = true;
}
}
pruned:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) {
vis[que[i]] = false;
parents[que[i]] = numOfVertices;
}
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
index_[inv[v]].spt_p.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_p[i] = tmp_idx_parents[v].second[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
tmp_idx_parents[v].first.clear();
tmp_idx_parents[v].second.clear();
tmp_idx_parents[v].first.shrink_to_fit();
tmp_idx_parents[v].second.shrink_to_fit();
}
}
void TP_path_d(Graph &graph, Ordering &orders) {
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t_path>& index_ = dplabels.index_;
vector<index_t_path>& bindex_ = dplabels.bindex_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
/* vector<vector<NodeID> > &adj = graph.adj;
vector<vector<NodeID> > &r_adj = graph.r_adj;*/
// Array Representation
vector<EdgeID>& vertices = graph.vertices;
vector<EdgeID>& r_vertices = graph.r_vertices;
vector<NodeID>& edges = graph.edges;
vector<NodeID>& r_edges = graph.r_edges;
vector<bool> usd(numOfVertices, false);
vector<NodeID> parents(numOfVertices, numOfVertices);
vector<NodeID> r_parents(numOfVertices, numOfVertices);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx_parent(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<NodeID> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<NodeID>(1, numOfVertices))); // Backward labels.
vector<pair<vector<NodeID>, vector<NodeID> > >
r_tmp_idx_parent(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<NodeID>(1, numOfVertices))); // Backward labels.
vector<bool> vis(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT); // Forward labels of root.
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT); // Backward labels of root.
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
// Forward search.
// Initialize forward labels of r.
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
parents[r] = inv[r];
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_v = r_tmp_idx[v];
pair<vector<NodeID>, vector<NodeID> > &r_tmp_idx_parent_v = r_tmp_idx_parent[v];
//index_t &idx_v = index_[inv[v]];
if (usd[v]) continue;
// Pruned by the forward labels of r and backward labels of v in the forward search from r when reaching v.
for (size_t i = 0; i < r_tmp_idx_v.first.size(); ++i) {
NodeID w = r_tmp_idx_v.first[i];
EdgeWeight td = r_tmp_idx_v.second[i] + dst_r[w];
if (td <= d) {
pruning_power[w]++;
goto pruned_forward;
}
}
// Traverse
r_tmp_idx_v.first.back() = r;
r_tmp_idx_v.second.back() = d;
r_tmp_idx_v.first.push_back(numOfVertices);
r_tmp_idx_v.second.push_back(INF_WEIGHT);
r_tmp_idx_parent_v.first.back() = r;
r_tmp_idx_parent_v.second.back() = parents[v];
r_tmp_idx_parent_v.first.push_back(numOfVertices);
r_tmp_idx_parent_v.second.push_back(numOfVertices);
iteration_generated[r]++;
/*for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];*/
// Array Representation
for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid) {
NodeID w = edges[eid];
if (!vis[w]) {
parents[w] = inv[v];
que[que_h++] = w;
vis[w] = true;
}
}
pruned_forward:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) {
vis[que[i]] = false;
parents[que[i]] = numOfVertices;
}
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
parents[r] = inv[r];
// Backward search.
// Initialize backward labels of r.
const pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_r = r_tmp_idx[r];
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i) {
r_dst_r[r_tmp_idx_r.first[i]] = r_tmp_idx_r.second[i];
}
que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
pair<vector<NodeID>, vector<NodeID> > &tmp_idx_parent_v = tmp_idx_parent[v];
//index_t &idx_v = index_[inv[v]];
if (usd[v]) continue;
// Pruned by the backward labels of r and forward labels of v in the backward search from r when reaching v (v->r path).
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + r_dst_r[w];
if (td <= d) {
pruning_power[w]++;
goto pruned_backward;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < r_adj[v].size(); ++i) {
NodeID w = r_adj[v][i];*/
// Array Representation
for (EdgeID eid = r_vertices[v]; eid < r_vertices[v + 1]; ++eid) {
NodeID w = r_edges[eid];
if (!vis[w]) {
parents[w] = inv[v];
que[que_h++] = w;
vis[w] = true;
}
}
pruned_backward:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) {
vis[que[i]] = false;
parents[que[i]] = numOfVertices;
}
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i)
r_dst_r[r_tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
index_[inv[v]].spt_p.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_p[i] = tmp_idx_parent[v].second[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx_parent[v].first.clear();
tmp_idx_parent[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
tmp_idx_parent[v].first.shrink_to_fit();
tmp_idx_parent[v].second.shrink_to_fit();
k = r_tmp_idx[v].first.size();
bindex_[inv[v]].spt_v.resize(k);
bindex_[inv[v]].spt_d.resize(k);
bindex_[inv[v]].spt_p.resize(k);
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_v[i] = r_tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_p[i] = r_tmp_idx_parent[v].second[i];
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_d[i] = r_tmp_idx[v].second[i];
r_tmp_idx[v].first.clear();
r_tmp_idx[v].second.clear();
r_tmp_idx_parent[v].first.clear();
r_tmp_idx_parent[v].second.clear();
r_tmp_idx[v].first.shrink_to_fit();
r_tmp_idx[v].second.shrink_to_fit();
r_tmp_idx_parent[v].first.shrink_to_fit();
r_tmp_idx_parent[v].second.shrink_to_fit();
}
}
PL(Graph &graph, Ordering &orders, bool path_flags, bool directed_flags) {
if (path_flags == true) {
if (directed_flags == true) {
TP_path_d(graph, orders);
}
else {
TP_path(graph, orders);
}
}
}
/* PL(Graph &graph, Ordering &orders, bool path_flags, bool directed_flags, bool bp_flags, int kNumBitParallelRoots) {
if (path_flags == true) {
if (directed_flags == true) {
TP_path_d(graph, orders);
}
else {
TP_path(graph, orders);
}
}
else {
if (directed_flags == false) {
TP_BP(graph, orders, kNumBitParallelRoots);
}
}
}
*/
};
template<int kNumBitParallelRoots = 50>
class BPL {
//typedef BPLabel<kNumBitParallelRoots>::index_t_bp index_t_bp;
public:
BPLabel<kNumBitParallelRoots> bplabels;
DBPLabel<kNumBitParallelRoots> dbplabels;
BPL(Graph &graph, Ordering &orders) {
//bplabels = BPLabel(kNumBitParallelRoots);
//kNumBitParallelRoots = 64;
//bplabels.setParas(kNumBitParallelRoots);
// iteration_generated.resize(numOfVertices);
// pruning_power.resize(numOfVertices);
index_t_bp<kNumBitParallelRoots>*& index_ = bplabels.index_bp;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
//vector<vector<NodeID> > &adj = graph.adj;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<bool> vis(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
{
vector<EdgeWeight> tmp_d(numOfVertices);
vector<std::pair<uint64_t, uint64_t> > tmp_s(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<std::pair<NodeID, NodeID> > sibling_es(numOfEdges);
vector<std::pair<NodeID, NodeID> > child_es(numOfEdges);
cout << "Building BP labels" << endl;
index_ = (index_t_bp<kNumBitParallelRoots>*)memalign(64, numOfVertices * sizeof(index_t_bp<kNumBitParallelRoots>));
//for (NodeID v = 0; v < numOfVertices; ++v) {
// index_t_bp &idx = index_[v];
// idx.bpspt_d = (EdgeWeight*)memalign(64, kNumBitParallelRoots * sizeof(EdgeWeight));
// idx.bpspt_s = (uint64_t*)memalign(64, kNumBitParallelRoots * 2 * sizeof(uint64_t));
// /*for (int i = 0; i < kNumBitParallelRoots; ++i) {
// idx.bpspt_s[i] = (uint64_t*)memalign(64, 2 * sizeof(uint64_t));
// }*/
//}
int r = 0;
for (int i_bpspt = 0; i_bpspt < kNumBitParallelRoots; ++i_bpspt) {
while (r < numOfVertices && usd[r]) ++r;
if (r == numOfVertices) {
for (NodeID v = 0; v < numOfVertices; ++v) index_[v].bpspt_d[i_bpspt] = INF_WEIGHT;
continue;
}
usd[r] = true;
fill(tmp_d.begin(), tmp_d.end(), INF_WEIGHT);
fill(tmp_s.begin(), tmp_s.end(), std::make_pair(0, 0));
int que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
tmp_d[r] = 0;
que_t1 = que_h;
int ns = 0;
vector<int> vs;
vector<NodeID> adj_r(graph.vertices[r + 1] - graph.vertices[r]);
for (EdgeID eid = graph.vertices[r]; eid < graph.vertices[r + 1]; eid++) {
adj_r[eid - graph.vertices[r]] = graph.edges[eid];
}
sort(adj_r.begin(), adj_r.end());
for (size_t i = 0; i < adj_r.size(); ++i) {
NodeID v = adj_r[i];
if (!usd[v]) {
usd[v] = true;
que[que_h++] = v;
tmp_d[v] = 1;
tmp_s[v].first = 1ULL << ns;
vs.push_back(v);
if (++ns == 64) break;
}
}
for (EdgeWeight d = 0; que_t0 < que_h; ++d) {
int num_sibling_es = 0, num_child_es = 0;
for (int que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
for (EdgeID eid = graph.vertices[v]; eid < graph.vertices[v + 1]; eid++) {
NodeID tv = graph.edges[eid];
EdgeWeight td = d + 1;
if (d > tmp_d[tv]);
else if (d == tmp_d[tv]) {
if (v < tv) {
sibling_es[num_sibling_es].first = v;
sibling_es[num_sibling_es].second = tv;
++num_sibling_es;
}
}
else {
if (tmp_d[tv] == INF_WEIGHT) {
que[que_h++] = tv;
tmp_d[tv] = td;
}
child_es[num_child_es].first = v;
child_es[num_child_es].second = tv;
++num_child_es;
}
}
}
for (int i = 0; i < num_sibling_es; ++i) {
int v = sibling_es[i].first, w = sibling_es[i].second;
tmp_s[v].second |= tmp_s[w].first;
tmp_s[w].second |= tmp_s[v].first;
}
for (int i = 0; i < num_child_es; ++i) {
int v = child_es[i].first, c = child_es[i].second;
tmp_s[c].first |= tmp_s[v].first;
tmp_s[c].second |= tmp_s[v].second;
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (NodeID v = 0; v < numOfVertices; ++v) {
index_[inv[v]].bpspt_d[i_bpspt] = tmp_d[v];
index_[inv[v]].bpspt_s[i_bpspt][0] = tmp_s[v].first;
index_[inv[v]].bpspt_s[i_bpspt][1] = tmp_s[v].second & ~tmp_s[v].first;
}
}
}
cout << "Building normal labels" << endl;
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
index_t_bp<kNumBitParallelRoots> &idx_r = index_[inv[r]];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
index_t_bp<kNumBitParallelRoots> &idx_v = index_[inv[v]];
// Prefetch
_mm_prefetch(&idx_v.bpspt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_v.bpspt_s[0][0], _MM_HINT_T0);
_mm_prefetch(&tmp_idx_v.first[0], _MM_HINT_T0);
_mm_prefetch(&tmp_idx_v.second[0], _MM_HINT_T0);
if (usd[v]) continue;
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight td = idx_r.bpspt_d[i] + idx_v.bpspt_d[i];
if (td - 2 <= d) {
/*td +=
(idx_r.bpspt_s[i][0] & idx_v.bpspt_s[i][0]) ? -2 :
((idx_r.bpspt_s[i][0] & idx_v.bpspt_s[i][1]) |
(idx_r.bpspt_s[i][1] & idx_v.bpspt_s[i][0]))
? -1 : 0;*/
td +=
(idx_r.bpspt_s[i][0] & idx_v.bpspt_s[i][0]) ? -2 :
((idx_r.bpspt_s[i][0] & idx_v.bpspt_s[i][1]) |
(idx_r.bpspt_s[i][1] & idx_v.bpspt_s[i][0]))
? -1 : 0;
if (td <= d) goto pruned;
}
}
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
if (td <= d) {
//pruning_power[w]++;
goto pruned;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
//iteration_generated[r]++;
/*for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];*/
for (EdgeID eid = graph.vertices[v]; eid < graph.vertices[v + 1]; ++eid) {
NodeID w = graph.edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
// Added by Johnpzh 02/13/2019
uint64_t amount = 0;
// Ended by Johnpzh
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k - 1;
// Ended by Johnpzh
//index_[inv[v]].spt_v.resize(k);
//index_[inv[v]].spt_d.resize(k);
index_[inv[v]].spt_v = (NodeID*)memalign(64, k * sizeof(NodeID));
index_[inv[v]].spt_d = (EdgeWeight*)memalign(64, k * sizeof(EdgeWeight));
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
}
// Added by Johnpzh 02/13/2019
// amount = (double)(amount) / 2;
cout << "avg_label_size: " << (double)(amount)/(double)numOfVertices << endl;
// Ended by Johnpzh
}
BPL(Graph &graph, Ordering &orders, bool directed_flags) {
//bplabels = BPLabel(kNumBitParallelRoots);
//kNumBitParallelRoots = 64;
//bplabels.setParas(kNumBitParallelRoots);
// iteration_generated.resize(numOfVertices);
// pruning_power.resize(numOfVertices);
if (directed_flags == false)
return;
index_t_bp<kNumBitParallelRoots>*& index_ = dbplabels.index_bp;
index_t_bp<kNumBitParallelRoots>*& bindex_ = dbplabels.bindex_bp;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
//vector<vector<NodeID> > &adj = graph.adj;
vector<bool> usd(numOfVertices, false);
vector<bool> r_usd(numOfVertices, false);
// vector<bool> bp_usd(numOfVertices, false);
// vector<bool> r_bp_usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<bool> vis(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT); // Backward labels of root.
{
vector<EdgeWeight> tmp_d(numOfVertices);
vector<std::pair<uint64_t, uint64_t> > tmp_s(numOfVertices);
vector<EdgeWeight> r_tmp_d(numOfVertices);
vector<std::pair<uint64_t, uint64_t> > r_tmp_s(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<std::pair<NodeID, NodeID> > sibling_es(numOfEdges);
vector<std::pair<NodeID, NodeID> > child_es(numOfEdges);
vector<std::pair<NodeID, NodeID> > r_sibling_es(numOfEdges);
vector<std::pair<NodeID, NodeID> > r_child_es(numOfEdges);
cout << "Building BP labels" << endl;
index_ = (index_t_bp<kNumBitParallelRoots>*)memalign(64, numOfVertices * sizeof(index_t_bp<kNumBitParallelRoots>));
bindex_ = (index_t_bp<kNumBitParallelRoots>*)memalign(64, numOfVertices * sizeof(index_t_bp<kNumBitParallelRoots>));
//for (NodeID v = 0; v < numOfVertices; ++v) {
// index_t_bp &idx = index_[v];
// idx.bpspt_d = (EdgeWeight*)memalign(64, kNumBitParallelRoots * sizeof(EdgeWeight));
// idx.bpspt_s = (uint64_t*)memalign(64, kNumBitParallelRoots * 2 * sizeof(uint64_t));
// /*for (int i = 0; i < kNumBitParallelRoots; ++i) {
// idx.bpspt_s[i] = (uint64_t*)memalign(64, 2 * sizeof(uint64_t));
// }*/
//}
int r = 0;
for (int i_bpspt = 0; i_bpspt < kNumBitParallelRoots; ++i_bpspt) {
while (r < numOfVertices && usd[r] ) ++r;
if (r == numOfVertices) {
for (NodeID v = 0; v < numOfVertices; ++v) {
index_[v].bpspt_d[i_bpspt] = INF_WEIGHT;
bindex_[v].bpspt_d[i_bpspt] = INF_WEIGHT;
}
continue;
}
r_usd[r] = true;
//r_bp_usd[r] = true;
//forward search
fill(r_tmp_d.begin(), r_tmp_d.end(), INF_WEIGHT);
fill(r_tmp_s.begin(), r_tmp_s.end(), std::make_pair(0, 0));
int que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
r_tmp_d[r] = 0;
que_t1 = que_h;
int ns = 0;
vector<int> vs;
vector<NodeID> adj_r(graph.vertices[r + 1] - graph.vertices[r]);
for (EdgeID eid = graph.vertices[r]; eid < graph.vertices[r + 1]; eid++) {
adj_r[eid - graph.vertices[r]] = graph.edges[eid];
}
sort(adj_r.begin(), adj_r.end());
vector<NodeID> r_adj_r(graph.r_vertices[r + 1] - graph.r_vertices[r]);
for (EdgeID eid = graph.r_vertices[r]; eid < graph.r_vertices[r + 1]; eid++) {
r_adj_r[eid - graph.r_vertices[r]] = graph.r_edges[eid];
}
sort(r_adj_r.begin(), r_adj_r.end());
vector<NodeID> common_adj;
set_intersection(adj_r.begin(), adj_r.end(), r_adj_r.begin(), r_adj_r.end(), back_inserter(common_adj));
sort(common_adj.begin(), common_adj.end());
for (size_t i = 0; i < common_adj.size(); ++i) {
NodeID v = common_adj[i];
if (!r_usd[v]) {
r_usd[v] = true;
que[que_h++] = v;
r_tmp_d[v] = 1;
r_tmp_s[v].first = 1ULL << ns;
vs.push_back(v);
if (++ns == 64) break;
}
}
for (EdgeWeight d = 0; que_t0 < que_h; ++d) {
int num_sibling_es = 0, num_child_es = 0;
for (int que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
for (EdgeID eid = graph.vertices[v]; eid < graph.vertices[v + 1]; eid++) {
NodeID tv = graph.edges[eid];
EdgeWeight td = d + 1;
if (d > r_tmp_d[tv]);
else if (d == r_tmp_d[tv]) {
// if (v < tv) {
r_sibling_es[num_sibling_es].first = v;
r_sibling_es[num_sibling_es].second = tv;
++num_sibling_es;
//}
}
else {
if (r_tmp_d[tv] == INF_WEIGHT) {
que[que_h++] = tv;
r_tmp_d[tv] = td;
}
r_child_es[num_child_es].first = v;
r_child_es[num_child_es].second = tv;
++num_child_es;
}
}
}
for (int i = 0; i < num_sibling_es; ++i) {
int v = r_sibling_es[i].first, w = r_sibling_es[i].second;
//r_tmp_s[v].second |= r_tmp_s[w].first;
r_tmp_s[w].second |= r_tmp_s[v].first;
}
for (int i = 0; i < num_child_es; ++i) {
int v = r_child_es[i].first, c = r_child_es[i].second;
r_tmp_s[c].first |= r_tmp_s[v].first;
r_tmp_s[c].second |= r_tmp_s[v].second;
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (NodeID v = 0; v < numOfVertices; ++v) {
bindex_[inv[v]].bpspt_d[i_bpspt] = r_tmp_d[v];
bindex_[inv[v]].bpspt_s[i_bpspt][0] = r_tmp_s[v].first;
bindex_[inv[v]].bpspt_s[i_bpspt][1] = r_tmp_s[v].second & ~r_tmp_s[v].first;
}
//forward search end
//backward
usd[r] = true;
fill(tmp_d.begin(), tmp_d.end(), INF_WEIGHT);
fill(tmp_s.begin(), tmp_s.end(), std::make_pair(0, 0));
que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
tmp_d[r] = 0;
que_t1 = que_h;
ns = 0;
vs.clear();
for (size_t i = 0; i < common_adj.size(); ++i) {
NodeID v = common_adj[i];
if (!usd[v]) {
usd[v] = true;
que[que_h++] = v;
tmp_d[v] = 1;
tmp_s[v].first = 1ULL << ns;
vs.push_back(v);
if (++ns == 64) break;
}
}
for (EdgeWeight d = 0; que_t0 < que_h; ++d) {
int num_sibling_es = 0, num_child_es = 0;
for (int que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
for (EdgeID eid = graph.r_vertices[v]; eid < graph.r_vertices[v + 1]; eid++) {
NodeID tv = graph.r_edges[eid];
EdgeWeight td = d + 1;
if (d > tmp_d[tv]);
else if (d == tmp_d[tv]) {
//if (v < tv) {
sibling_es[num_sibling_es].first = v;
sibling_es[num_sibling_es].second = tv;
++num_sibling_es;
//}
}
else {
if (tmp_d[tv] == INF_WEIGHT) {
que[que_h++] = tv;
tmp_d[tv] = td;
}
child_es[num_child_es].first = v;
child_es[num_child_es].second = tv;
++num_child_es;
}
}
}
for (int i = 0; i < num_sibling_es; ++i) {
int v = sibling_es[i].first, w = sibling_es[i].second;
//tmp_s[v].second |= tmp_s[w].first;
tmp_s[w].second |= tmp_s[v].first;
}
for (int i = 0; i < num_child_es; ++i) {
int v = child_es[i].first, c = child_es[i].second;
tmp_s[c].first |= tmp_s[v].first;
tmp_s[c].second |= tmp_s[v].second;
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (NodeID v = 0; v < numOfVertices; ++v) {
index_[inv[v]].bpspt_d[i_bpspt] = tmp_d[v];
index_[inv[v]].bpspt_s[i_bpspt][0] = tmp_s[v].first;
index_[inv[v]].bpspt_s[i_bpspt][1] = tmp_s[v].second & ~tmp_s[v].first;
}
}
}
cout << "Building normal labels" << endl;
//for (size_t r = 0; r < numOfVertices; ++r) {
// if (usd[r]) continue;
// const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
// index_t_bp<kNumBitParallelRoots> &idx_r = index_[inv[r]];
// for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
// dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
// }
// NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
// que[que_h++] = r;
// vis[r] = true;
// que_t1 = que_h;
// for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
// for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
// NodeID v = que[que_i];
// pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
// index_t_bp<kNumBitParallelRoots> &idx_v = index_[inv[v]];
// // Prefetch
// _mm_prefetch(&idx_v.bpspt_d[0], _MM_HINT_T0);
// _mm_prefetch(&idx_v.bpspt_s[0][0], _MM_HINT_T0);
// _mm_prefetch(&tmp_idx_v.first[0], _MM_HINT_T0);
// _mm_prefetch(&tmp_idx_v.second[0], _MM_HINT_T0);
// if (usd[v]) continue;
// for (int i = 0; i < kNumBitParallelRoots; ++i) {
// EdgeWeight td = idx_r.bpspt_d[i] + idx_v.bpspt_d[i];
// if (td - 2 <= d) {
// td +=
// (idx_r.bpspt_s[i][0] & idx_v.bpspt_s[i][0]) ? -2 :
// ((idx_r.bpspt_s[i][0] & idx_v.bpspt_s[i][1]) |
// (idx_r.bpspt_s[i][1] & idx_v.bpspt_s[i][0]))
// ? -1 : 0;
// if (td <= d) goto pruned;
// }
// }
// for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
// NodeID w = tmp_idx_v.first[i];
// EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
// if (td <= d) {
// //pruning_power[w]++;
// goto pruned;
// }
// }
// // Traverse
// tmp_idx_v.first.back() = r;
// tmp_idx_v.second.back() = d;
// tmp_idx_v.first.push_back(numOfVertices);
// tmp_idx_v.second.push_back(INF_WEIGHT);
// //iteration_generated[r]++;
// /*for (size_t i = 0; i < adj[v].size(); ++i) {
// NodeID w = adj[v][i];*/
// for (EdgeID eid = graph.vertices[v]; eid < graph.vertices[v + 1]; ++eid) {
// NodeID w = graph.edges[eid];
// if (!vis[w]) {
// que[que_h++] = w;
// vis[w] = true;
// }
// }
// pruned:
// {}
// }
// que_t0 = que_t1;
// que_t1 = que_h;
// }
// for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
// for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
// dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
// usd[r] = true;
//}
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
// Forward search.
// Initialize forward labels of r.
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
index_t_bp<kNumBitParallelRoots> &idx_r = index_[inv[r]];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_v = r_tmp_idx[v];
index_t_bp<kNumBitParallelRoots> &r_idx_v = bindex_[inv[v]];
//index_t &idx_v = index_[inv[v]];
// Prefetch
_mm_prefetch(&r_idx_v.bpspt_d[0], _MM_HINT_T0);
_mm_prefetch(&r_idx_v.bpspt_s[0][0], _MM_HINT_T0);
_mm_prefetch(&r_tmp_idx_v.first[0], _MM_HINT_T0);
_mm_prefetch(&r_tmp_idx_v.second[0], _MM_HINT_T0);
if (usd[v]) continue;
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight td = idx_r.bpspt_d[i] + r_idx_v.bpspt_d[i];
if (td - 2 <= d) {
td +=
(idx_r.bpspt_s[i][0] & r_idx_v.bpspt_s[i][0]) ? -2 :
((idx_r.bpspt_s[i][0] & r_idx_v.bpspt_s[i][1]) |
(idx_r.bpspt_s[i][1] & r_idx_v.bpspt_s[i][0]))
? -1 : 0;
if (td <= d) goto pruned_forward;
}
}
// Pruned by the forward labels of r and backward labels of v in the forward search from r when reaching v.
for (size_t i = 0; i < r_tmp_idx_v.first.size(); ++i) {
NodeID w = r_tmp_idx_v.first[i];
EdgeWeight td = r_tmp_idx_v.second[i] + dst_r[w];
if (td <= d) {
goto pruned_forward;
}
}
// Traverse
r_tmp_idx_v.first.back() = r;
r_tmp_idx_v.second.back() = d;
r_tmp_idx_v.first.push_back(numOfVertices);
r_tmp_idx_v.second.push_back(INF_WEIGHT);
/*for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];*/
// Array Representation
for (EdgeID eid = graph.vertices[v]; eid < graph.vertices[v + 1]; ++eid) {
NodeID w = graph.edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned_forward:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
// Backward search.
// Initialize backward labels of r.
const pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_r = r_tmp_idx[r];
index_t_bp<kNumBitParallelRoots> &r_idx_r = bindex_[inv[r]];
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i) {
r_dst_r[r_tmp_idx_r.first[i]] = r_tmp_idx_r.second[i];
}
que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
index_t_bp<kNumBitParallelRoots> &idx_v = index_[inv[v]];
//index_t &idx_v = index_[inv[v]];
_mm_prefetch(&idx_v.bpspt_d[0], _MM_HINT_T0);
_mm_prefetch(&idx_v.bpspt_s[0][0], _MM_HINT_T0);
_mm_prefetch(&tmp_idx_v.first[0], _MM_HINT_T0);
_mm_prefetch(&tmp_idx_v.second[0], _MM_HINT_T0);
if (usd[v]) continue;
for (int i = 0; i < kNumBitParallelRoots; ++i) {
EdgeWeight td = r_idx_r.bpspt_d[i] + idx_v.bpspt_d[i];
if (td - 2 <= d) {
/*td +=
(r_idx_r.bpspt_s[i][0] & idx_v.bpspt_s[i][0]) ? -2 :
((r_idx_r.bpspt_s[i][0] & idx_v.bpspt_s[i][1]) |
(r_idx_r.bpspt_s[i][1] & idx_v.bpspt_s[i][0]))
? -1 : 0;*/
td +=
( idx_v.bpspt_s[i][0]) & r_idx_r.bpspt_s[i][0] ? -2 :
((idx_v.bpspt_s[i][1] & r_idx_r.bpspt_s[i][0]) |
(idx_v.bpspt_s[i][0] & r_idx_r.bpspt_s[i][1]))
? -1 : 0;
if (td <= d) goto pruned_backward;
}
}
// Pruned by the backward labels of r and forward labels of v in the backward search from r when reaching v (v->r path).
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + r_dst_r[w];
if (td <= d) {
goto pruned_backward;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
/*for (size_t i = 0; i < r_adj[v].size(); ++i) {
NodeID w = r_adj[v][i];*/
// Array Representation
for (EdgeID eid = graph.r_vertices[v]; eid < graph.r_vertices[v + 1]; ++eid) {
NodeID w = graph.r_edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned_backward:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i)
r_dst_r[r_tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
// Added by Johnpzh 02/13/2019
uint64_t amount = 0;
// Ended by Johnpzh
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k;
// Ended by Johnpzh
//index_[inv[v]].spt_v.resize(k);
//index_[inv[v]].spt_d.resize(k);
index_[inv[v]].spt_v = (NodeID*)memalign(64, k * sizeof(NodeID));
index_[inv[v]].spt_d = (EdgeWeight*)memalign(64, k * sizeof(EdgeWeight));
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
k = r_tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k;
// Ended by Johnpzh
//index_[inv[v]].spt_v.resize(k);
//index_[inv[v]].spt_d.resize(k);
bindex_[inv[v]].spt_v = (NodeID*)memalign(64, k * sizeof(NodeID));
bindex_[inv[v]].spt_d = (EdgeWeight*)memalign(64, k * sizeof(EdgeWeight));
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_v[i] = r_tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_d[i] = r_tmp_idx[v].second[i];
r_tmp_idx[v].first.clear();
r_tmp_idx[v].second.clear();
r_tmp_idx[v].first.shrink_to_fit();
r_tmp_idx[v].second.shrink_to_fit();
}
// Added by Johnpzh 02/13/2019
amount = (double)(amount) / 2;
cout << "avg_label_size: " << (double)(amount)/(double)numOfVertices - 1 << endl;
// Ended by Johnpzh
}
};
class PL_W : public construction {
public:
vector<double> iteration_generated;
vector<double> pruning_power;
PL_W(WGraph &wgraph, Ordering &orders) {
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t>& index_ = labels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
// vector<vector<NodeID> > &adj = wgraph.adj;
// vector<vector<EdgeWeight> > &adj_weight = wgraph.adj_weight;
vector<EdgeID>& vertices = wgraph.vertices;
vector<NodeEdgeWeightPair>& edges = wgraph.edges;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<bool> vis(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
queue<NodeID> visited_que;
vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
long pop = 0;
double hsize = 0;
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
pqueue.update(r, 0);
//vis[r] = true;
long max_heap_size = 0;
long heap_size = 1;
while (!pqueue.empty()) {
pop++;
heap_size--;
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
vis[v] = true;
visited_que.push(v);
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
if (td <= v_d) {
pruning_power[w]++;
goto pruned;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = v_d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
// for (size_t i = 0; i < adj[v].size(); ++i) {
// NodeID w = adj[v][i];
// EdgeWeight w_d = adj_weight[v][i] + v_d;
for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid) {
NodeID w = edges[eid].first;
EdgeWeight w_d = edges[eid].second + v_d;
if (!vis[w]) {
if (distances[w] == INF_WEIGHT) {
heap_size++;
if (max_heap_size < heap_size)
max_heap_size = heap_size;
}
if( distances[w] > w_d ){
pqueue.update(w, w_d);
distances[w] = w_d;
}
}
}
pruned:
{}
}
hsize = hsize + max_heap_size;
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
pqueue.clear(vis_v);
}
pqueue.clear_n();
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
//cout << "total pop:" << pop << endl;
//cout << "heap size:" << (double)hsize / (double)numOfVertices << endl;
double count = 0;
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
count = count + k - 1;
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
}
cout << "Average_label_size: " << count / numOfVertices << endl;
}
PL_W(WGraph &wgraph, Ordering &orders, bool DIRECTED, bool PATH_QUERY) {
// Generating Path Labels
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t_path>& index_ = plabels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
// vector<vector<NodeID> > &adj = wgraph.adj;
// vector<vector<EdgeWeight> > &adj_weight = wgraph.adj_weight;
vector<EdgeID>& vertices = wgraph.vertices;
vector<NodeEdgeWeightPair>& edges = wgraph.edges;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<NodeID> > > tmp_idx_parent(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices), vector<NodeID>(1, numOfVertices)));
vector<bool> vis(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
queue<NodeID> visited_que;
vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
vector<NodeID> parents(numOfVertices, numOfVertices);
benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
parents[r] = inv[r];
pqueue.update(r, 0);
//vis[r] = true;
while (!pqueue.empty()) {
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
pair<vector<NodeID>, vector<NodeID> > &tmp_idx_parent_v = tmp_idx_parent[v];
vis[v] = true;
visited_que.push(v);
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
if (td <= v_d) {
pruning_power[w]++;
goto pruned;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = v_d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
tmp_idx_parent_v.first.back() = r;
tmp_idx_parent_v.second.back() = parents[v];
tmp_idx_parent_v.first.push_back(numOfVertices);
tmp_idx_parent_v.second.push_back(numOfVertices);
iteration_generated[r]++;
// for (size_t i = 0; i < adj[v].size(); ++i) {
// NodeID w = adj[v][i];
// EdgeWeight w_d = adj_weight[v][i] + v_d;
for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid) {
NodeID w = edges[eid].first;
EdgeWeight w_d = edges[eid].second + v_d;
if (!vis[w]) {
if (distances[w] > w_d) {
pqueue.update(w, w_d);
distances[w] = w_d;
parents[w] = inv[v];
}
}
}
pruned:
{}
}
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
parents[vis_v] = numOfVertices;
pqueue.clear(vis_v);
}
pqueue.clear_n();
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
// Added by Johnpzh 02/13/2019
uint64_t amount = 0;
// Ended by Johnpzh
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k - 1;
// Ended by Johnpzh
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
index_[inv[v]].spt_p.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_p[i] = tmp_idx_parent[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx_parent[v].first.clear();
tmp_idx_parent[v].second.clear();
}
// Added by Johnpzh 02/13/2019
amount = (double)(amount) / 2;
cout << "avg_label_size: " << (double)(amount)/(double)numOfVertices << endl;
// Ended by Johnpzh
}
PL_W(WGraph &wgraph, Ordering &orders, bool D_FLAGS) {
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t>& index_ = dlabels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
/*vector<vector<NodeID> > &adj = wgraph.adj;
vector<vector<EdgeWeight> > &adj_weight = wgraph.adj_weight;*/
vector<index_t>& bindex_ = dlabels.bindex_;/*
vector<vector<NodeID> > &r_adj = wgraph.r_adj;
vector<vector<EdgeWeight> > &r_adj_weight = wgraph.r_adj_weight;*/
//Array Representation
vector<EdgeID>& vertices = wgraph.vertices;
vector<EdgeID>& r_vertices = wgraph.r_vertices;
vector<NodeEdgeWeightPair>& edges = wgraph.edges;
vector<NodeEdgeWeightPair>& r_edges = wgraph.r_edges;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<bool> vis(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT);
queue<NodeID> visited_que;
vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
// Forward search from r.
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
pqueue.update(r, 0);
//vis[r] = true;
while (!pqueue.empty()) {
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_v = r_tmp_idx[v];
vis[v] = true;
visited_que.push(v);
if (usd[v]) continue;
for (size_t i = 0; i < r_tmp_idx_v.first.size(); ++i) {
NodeID w = r_tmp_idx_v.first[i];
EdgeWeight td = r_tmp_idx_v.second[i] + dst_r[w];
if (td <= v_d) {
pruning_power[w]++;
goto pruned_forward;
}
}
// Traverse
r_tmp_idx_v.first.back() = r;
r_tmp_idx_v.second.back() = v_d;
r_tmp_idx_v.first.push_back(numOfVertices);
r_tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/* for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];
EdgeWeight w_d = adj_weight[v][i] + v_d;*/
//Array Representation
for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid) {
NodeID w = edges[eid].first;
EdgeWeight w_d = edges[eid].second + v_d;
if (!vis[w]) {
if (distances[w] > w_d) {
pqueue.update(w, w_d);
distances[w] = w_d;
}
}
}
pruned_forward:
{}
}
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
//pqueue.clear(vis_v);
}
//pqueue.clear_n();
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
// Backward search from r.
const pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_r = r_tmp_idx[r];
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i) {
r_dst_r[r_tmp_idx_r.first[i]] = r_tmp_idx_r.second[i];
}
pqueue.update(r, 0);
while (!pqueue.empty()) {
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
vis[v] = true;
visited_que.push(v);
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + r_dst_r[w];
if (td <= v_d) {
pruning_power[w]++;
goto pruned_backward;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = v_d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < r_adj[v].size(); ++i) {
NodeID w = r_adj[v][i];
EdgeWeight w_d = r_adj_weight[v][i] + v_d;*/
//Array Representation
for (EdgeID eid = r_vertices[v]; eid < r_vertices[v + 1]; ++eid) {
NodeID w = r_edges[eid].first;
EdgeWeight w_d = r_edges[eid].second + v_d;
if (!vis[w]) {
if (distances[w] > w_d) {
pqueue.update(w, w_d);
distances[w] = w_d;
}
}
}
pruned_backward:
{}
}
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
//pqueue.clear(vis_v);
}
// pqueue.clear_n();
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i)
r_dst_r[r_tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
// Added by Johnpzh 02/13/2019
uint64_t amount = 0;
// Ended by Johnpzh
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k;
// Ended by Johnpzh
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
k = r_tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k;
// Ended by Johnpzh
bindex_[inv[v]].spt_v.resize(k);
bindex_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_v[i] = r_tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_d[i] = r_tmp_idx[v].second[i];
r_tmp_idx[v].first.clear();
r_tmp_idx[v].second.clear();
r_tmp_idx[v].first.shrink_to_fit();
r_tmp_idx[v].second.shrink_to_fit();
}
// Added by Johnpzh 02/13/2019
amount = (double)(amount) / 2;
cout << "avg_label_size: " << (double)(amount)/(double)numOfVertices - 1 << endl;
// Ended by Johnpzh
}
PL_W(WGraph &wgraph, Ordering &orders, bool D_FLAGS, bool PATH_QUERY, bool dwpath) {
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t_path>& index_ = dplabels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
/*vector<vector<NodeID> > &adj = wgraph.adj;
vector<vector<EdgeWeight> > &adj_weight = wgraph.adj_weight;*/
vector<index_t_path>& bindex_ = dplabels.bindex_;/*
vector<vector<NodeID> > &r_adj = wgraph.r_adj;
vector<vector<EdgeWeight> > &r_adj_weight = wgraph.r_adj_weight;*/
//Array Representation
vector<EdgeID>& vertices = wgraph.vertices;
vector<EdgeID>& r_vertices = wgraph.r_vertices;
vector<NodeEdgeWeightPair>& edges = wgraph.edges;
vector<NodeEdgeWeightPair>& r_edges = wgraph.r_edges;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<NodeID> parents(numOfVertices, numOfVertices);
vector<pair<vector<NodeID>, vector<NodeID> > > tmp_idx_parent(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices), vector<NodeID>(1, numOfVertices)));
vector<NodeID> r_parents(numOfVertices, numOfVertices);
vector<pair<vector<NodeID>, vector<NodeID> > > r_tmp_idx_parent(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices), vector<NodeID>(1, numOfVertices)));
vector<bool> vis(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT);
queue<NodeID> visited_que;
vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
// Forward search from r.
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
pqueue.update(r, 0);
distances[r] = 0;
parents[r] = inv[r];
//vis[r] = true;
while (!pqueue.empty()) {
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_v = r_tmp_idx[v];
pair<vector<NodeID>, vector<NodeID> > &r_tmp_idx_parent_v = r_tmp_idx_parent[v];
vis[v] = true;
visited_que.push(v);
if (usd[v]) continue;
for (size_t i = 0; i < r_tmp_idx_v.first.size(); ++i) {
NodeID w = r_tmp_idx_v.first[i];
EdgeWeight td = r_tmp_idx_v.second[i] + dst_r[w];
if (td <= v_d) {
pruning_power[w]++;
goto pruned_forward;
}
}
// Traverse
r_tmp_idx_v.first.back() = r;
r_tmp_idx_v.second.back() = v_d;
r_tmp_idx_v.first.push_back(numOfVertices);
r_tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
r_tmp_idx_parent_v.first.back() = r;
r_tmp_idx_parent_v.second.back() = parents[v];
r_tmp_idx_parent_v.first.push_back(numOfVertices);
r_tmp_idx_parent_v.second.push_back(numOfVertices);
/* for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];
EdgeWeight w_d = adj_weight[v][i] + v_d;*/
//Array Representation
for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid) {
NodeID w = edges[eid].first;
EdgeWeight w_d = edges[eid].second + v_d;
if (!vis[w]) {
if (distances[w] > w_d) {
parents[w] = inv[v];
pqueue.update(w, w_d);
distances[w] = w_d;
}
}
}
pruned_forward:
{}
}
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
parents[vis_v] = numOfVertices;
//pqueue.clear(vis_v);
}
//pqueue.clear_n();
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
// Backward search from r.
const pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_r = r_tmp_idx[r];
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i) {
r_dst_r[r_tmp_idx_r.first[i]] = r_tmp_idx_r.second[i];
}
pqueue.update(r, 0);
r_parents[r] = inv[r];
while (!pqueue.empty()) {
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
pair<vector<NodeID>, vector<NodeID> > &tmp_idx_parent_v = tmp_idx_parent[v];
vis[v] = true;
visited_que.push(v);
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + r_dst_r[w];
if (td <= v_d) {
pruning_power[w]++;
goto pruned_backward;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = v_d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
tmp_idx_parent_v.first.back() = r;
tmp_idx_parent_v.second.back() = r_parents[v];
tmp_idx_parent_v.first.push_back(numOfVertices);
tmp_idx_parent_v.second.push_back(numOfVertices);
iteration_generated[r]++;
/*for (size_t i = 0; i < r_adj[v].size(); ++i) {
NodeID w = r_adj[v][i];
EdgeWeight w_d = r_adj_weight[v][i] + v_d;*/
//Array Representation
for (EdgeID eid = r_vertices[v]; eid < r_vertices[v + 1]; ++eid) {
NodeID w = r_edges[eid].first;
EdgeWeight w_d = r_edges[eid].second + v_d;
if (!vis[w]) {
if (distances[w] > w_d) {
pqueue.update(w, w_d);
distances[w] = w_d;
r_parents[w] = inv[v];
}
}
}
pruned_backward:
{}
}
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
r_parents[vis_v] = numOfVertices;
//pqueue.clear(vis_v);
}
// pqueue.clear_n();
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i)
r_dst_r[r_tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
// Added by Johnpzh 02/13/2019
uint64_t amount = 0;
// Ended by Johnpzh
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k;
// Ended by Johnpzh
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
index_[inv[v]].spt_p.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_p[i] = tmp_idx_parent[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
tmp_idx_parent[v].first.clear();
tmp_idx_parent[v].second.clear();
tmp_idx_parent[v].first.shrink_to_fit();
tmp_idx_parent[v].second.shrink_to_fit();
k = r_tmp_idx[v].first.size();
// Added by Johnpzh 02/13/2019
amount += k;
// Ended by Johnpzh
bindex_[inv[v]].spt_v.resize(k);
bindex_[inv[v]].spt_d.resize(k);
bindex_[inv[v]].spt_p.resize(k);
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_v[i] = r_tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_d[i] = r_tmp_idx[v].second[i];
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_p[i] = r_tmp_idx_parent[v].second[i];
r_tmp_idx[v].first.clear();
r_tmp_idx[v].second.clear();
r_tmp_idx[v].first.shrink_to_fit();
r_tmp_idx[v].second.shrink_to_fit();
r_tmp_idx_parent[v].first.clear();
r_tmp_idx_parent[v].second.clear();
r_tmp_idx_parent[v].first.shrink_to_fit();
r_tmp_idx_parent[v].second.shrink_to_fit();
}
// Added by Johnpzh 02/13/2019
amount = (double)(amount) / 2;
cout << "avg_label_size: " << (double)(amount)/(double)numOfVertices - 1 << endl;
// Ended by Johnpzh
}
};
class CPL : public construction {
public:
vector<double> iteration_generated;
vector<double> pruning_power;
bool SECOND_LEVEL = false;
long children_size;
long r_children_size;
class nodeid_vector_hasher {
public:
std::size_t operator()(std::pair<NodeID, std::vector<NodeID> > const& pairvec) const {
std::size_t seed = pairvec.second.size();
seed ^= pairvec.first + 0x9e3779b9 + (seed << 6) + (seed >> 2);
for(auto& i : pairvec.second) {
seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
//using boost::hash_combine
template <class T>
inline void hash_combine(std::size_t& seed, T const& v)
{
seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
NodeID convertlist(NodeID& token_id, vector<token_t>& tokens_list, vector<vector<NodeID> >& tmp_tokens, vector<vector<EdgeWeight> >& tmp_tokens_distances, unordered_map<pair<NodeID, vector<NodeID> >, NodeID, nodeid_vector_hasher>& token_map, pair<vector<NodeID>, vector<EdgeWeight> > & tmp_idx_v, pair<vector<NodeID>, vector<NodeID> >& tmp_idx_token_parents_v, bool REVERSE){
NodeID lsize = tmp_idx_v.first.size();
NodeID anchorid = tmp_idx_v.first[lsize-2];
for(NodeID i = 0; i < lsize - 1; ++i){
//Add to parent_tree
NodeID h = tmp_idx_v.first[i];
NodeID hparent = tmp_idx_token_parents_v.first[i];
EdgeWeight hparent_dis = tmp_idx_token_parents_v.second[i];
NodeID tid = h;
// non-trival tokens
if(tmp_tokens[h].size() != 0){
vector<NodeID>& tmp_token_h = tmp_tokens[h];
//string tstring = token_string(h, tmp_token_h);
vector<EdgeWeight>& tmp_tokens_distances_h = tmp_tokens_distances[h];
pair<NodeID, vector<NodeID> > token_key = make_pair(h, tmp_token_h);
// New token
if(token_map.find(token_key) == token_map.end()){
token_map[token_key] = token_id;
token_t new_token;
NodeID csize = tmp_token_h.size();
new_token.sptc_v = (NodeID*)memalign(64, (csize + 1)* sizeof(NodeID));
new_token.sptc_d = (EdgeWeight*)memalign(64, (csize + 1) * sizeof(EdgeWeight));
new_token.sptc_v[0] = h;
new_token.sptc_d[0] = csize;
if(REVERSE)
r_children_size += (csize + 1);
else
children_size += (csize + 1);
for(NodeID j = 0; j < csize; ++j){
new_token.sptc_v[j+1] = tmp_token_h[j];
new_token.sptc_d[j+1] = tmp_tokens_distances_h[j];
}
tokens_list.push_back(new_token);
tid = token_id;
token_id++;
}else // Already exist
tid = token_map[token_key];
}
//trival tokens
if(i == lsize - 2)
anchorid = tid;
if(hparent!=numOfVertices){
tmp_tokens[hparent].push_back(tid);
tmp_tokens_distances[hparent].push_back(hparent_dis);
}
}
return anchorid;
}
void converttokens(vector<pair<vector<NodeID>, vector<EdgeWeight> > > & tmp_idx, vector<pair<vector<NodeID>, vector<NodeID> > >& tmp_idx_token_parents, bool REVERSE){
vector<token_t> tokens_list;
vector<token_t> r_tokens_list;
vector<vector<NodeID> > tmp_tokens(numOfVertices);
vector<vector<EdgeWeight> > tmp_tokens_distances(numOfVertices);
vector<vector<NodeID> > r_tmp_tokens(numOfVertices);
vector<vector<EdgeWeight> > r_tmp_tokens_distances(numOfVertices);
unordered_map<pair<NodeID, vector<NodeID> >, NodeID, nodeid_vector_hasher> token_map;
unordered_map<pair<NodeID, vector<NodeID> >, NodeID, nodeid_vector_hasher> r_token_map;
if(REVERSE == false)
children_size = 0;
else
r_children_size = 0;
NodeID token_id = numOfVertices;
NodeID r_token_id = numOfVertices;
if(REVERSE == false)
clabels.anchor_p = (NodeID*)memalign(64, (numOfVertices)* sizeof(NodeID));
else
clabels.r_anchor_p = (NodeID*)memalign(64, (numOfVertices)* sizeof(NodeID));
//vector<NodeID> que(numOfVertices, numOfVertices);
for(NodeID v = 0; v < numOfVertices; ++v){
if(REVERSE == false)
clabels.anchor_p[v] = convertlist(token_id, tokens_list, tmp_tokens, tmp_tokens_distances, token_map, tmp_idx[v], tmp_idx_token_parents[v], REVERSE);
else
clabels.r_anchor_p[v] = convertlist(r_token_id, r_tokens_list, r_tmp_tokens, r_tmp_tokens_distances, r_token_map, tmp_idx[v], tmp_idx_token_parents[v], REVERSE);
//if(REVERSE == true)
// validation(tmp_idx[v], tmp_idx_token_parents[v], tokens_list, clabels.r_anchor_p[v], que);
if(REVERSE == false){
NodeID lsize = tmp_idx[v].first.size();
for(NodeID i = 0; i < lsize - 1; ++i){
NodeID h = tmp_idx[v].first[i];
NodeID hparent = tmp_idx_token_parents[v].first[i];
if( hparent != numOfVertices ){
if(tmp_tokens[hparent].empty() == false){
tmp_tokens[hparent].clear();
tmp_tokens_distances[hparent].clear();
}
}
}
}else{
NodeID lsize = tmp_idx[v].first.size();
for(NodeID i = 0; i < lsize - 1; ++i){
NodeID h = tmp_idx[v].first[i];
NodeID hparent = tmp_idx_token_parents[v].first[i];
if( hparent != numOfVertices ){
if(r_tmp_tokens[hparent].empty() == false){
r_tmp_tokens[hparent].clear();
r_tmp_tokens_distances[hparent].clear();
}
}
}
}
}
//vector<vector<bool> > one_level(tokens_list.size());
if(REVERSE == false){
clabels.numOfTokens = tokens_list.size();
clabels.tokenindex_p = (token_t*)memalign(64, clabels.numOfTokens * sizeof(token_t));
for(NodeID i = 0; i < clabels.numOfTokens; ++i){
clabels.tokenindex_p[i] = tokens_list[i];
}
}else{
clabels.r_numOfTokens = r_tokens_list.size();
clabels.r_tokenindex_p = (token_t*)memalign(64, clabels.r_numOfTokens * sizeof(token_t));
for(NodeID i = 0; i < clabels.r_numOfTokens; ++i){
clabels.r_tokenindex_p[i] = r_tokens_list[i];
}
}
if(REVERSE == false){
if(SECOND_LEVEL){
vector<token_t> supertokens(numOfVertices);
convertsupertokens(tokens_list, supertokens);
clabels.supertokenindex_p = (token_t*)memalign(64, numOfVertices * sizeof(token_t));
for(NodeID i = 0; i < supertokens.size(); ++i){
clabels.supertokenindex_p[i] = supertokens[i];
}
for(NodeID i = 0; i < clabels.numOfTokens; ++i){
clabels.tokenindex_p[i] = tokens_list[i];
}
//convertsupertokens(clabels.tokenindex_p, clabels.supertokenindex_p, clabels.numOfTokens);
//vector<NodeID> que(numOfVertices, numOfVertices);
//for(NodeID v = 0; v < numOfVertices; ++v){
//if(REVERSE) {
//cout << v << endl;
//validation(tmp_idx[v], tmp_idx_token_parents[v], tokens_list,supertokens, clabels.anchor_p[v], que);
//validation(tmp_idx[v], tmp_idx_token_parents[v], tokens_list, clabels.supertokenindex_p, clabels.anchor_p[v], que);
//}
//}
}
}else{
if(SECOND_LEVEL){
//convertsupertokens(clabels.r_tokenindex_p, clabels.r_supertokenindex_p, clabels.r_numOfTokens);
vector<token_t> r_supertokens(numOfVertices);
convertsupertokens(r_tokens_list, r_supertokens);
clabels.r_supertokenindex_p = (token_t*)memalign(64, numOfVertices * sizeof(token_t));
for(NodeID i = 0; i < r_supertokens.size(); ++i){
clabels.r_supertokenindex_p[i] = r_supertokens[i];
}
for(NodeID i = 0; i < clabels.r_numOfTokens; ++i){
clabels.r_tokenindex_p[i] = r_tokens_list[i];
}
/*
//vector<NodeID> que(numOfVertices, numOfVertices);
for(NodeID v = 0; v < numOfVertices; ++v){
//if(REVERSE) {
cout << v << endl;
//validation(tmp_idx[v], tmp_idx_token_parents[v], r_tokens_list, r_supertokens, clabels.r_anchor_p[v], que);
validation(tmp_idx[v], tmp_idx_token_parents[v], r_tokens_list, clabels.r_supertokenindex_p, clabels.r_anchor_p[v], que);
//}
}*/
}
}
clabels.total_children = children_size;
}
void convertsupertokens(vector<token_t>& tokens_list, vector<token_t>& supertokens){
vector<unordered_map<NodeID, NodeID> > sorted_sp(numOfVertices);
vector<unordered_map<NodeID, EdgeWeight> > dis_sp(numOfVertices);
NodeID total_supertoken_children = 0;
for(NodeID t = 0 ; t < tokens_list.size(); ++t){
token_t& token = tokens_list[t];
NodeID r = token.sptc_v[0];
EdgeWeight csize = token.sptc_d[0];
unordered_map<NodeID, NodeID>& rc_map = sorted_sp[r];
unordered_map<NodeID, EdgeWeight>& rd_map = dis_sp[r];
for(EdgeWeight i = 0; i < csize; ++i){
NodeID cid = token.sptc_v[i + 1];
rc_map[cid]++;
rd_map[cid] = token.sptc_d[i + 1];
}
}
//supertokens.resize(numOfVertices);
// Creating super tokens, sorting the children based on frequency
for(NodeID v = 0; v < numOfVertices; ++v){
vector<pair<NodeID, NodeID> > sorted_tmp;
unordered_map<NodeID, NodeID>& vc_map = sorted_sp[v];
unordered_map<NodeID, EdgeWeight>& vd_map = dis_sp[v];
for(unordered_map<NodeID, NodeID>::iterator it = vc_map.begin(); it != vc_map.end(); ++it){
sorted_tmp.push_back(make_pair((*it).second, (*it).first));
}
sort(sorted_tmp.rbegin(), sorted_tmp.rend());
token_t new_token;
EdgeWeight csize = sorted_tmp.size();
new_token.sptc_v = (NodeID*)memalign(64, (csize + 1)* sizeof(NodeID));
new_token.sptc_d = (EdgeWeight*)memalign(64, (csize + 1) * sizeof(EdgeWeight));
new_token.sptc_v[0] = csize;
new_token.sptc_d[0] = ceil((double)ceil((double)csize / (double)8) / (double)8);
for(NodeID i = 0; i < csize; ++i){
NodeID cid = sorted_tmp[i].second;
new_token.sptc_v[i + 1] = cid;
new_token.sptc_d[i + 1] = vd_map[cid];
}
supertokens[v] = new_token;
total_supertoken_children += csize;
}
// Converting each tokens to supertokens
vector<bool> isChild(numOfVertices + tokens_list.size(), false);
for(NodeID t = 0 ; t < tokens_list.size(); ++t){
token_t& token = tokens_list[t];
NodeID r = token.sptc_v[0];
EdgeWeight csize = token.sptc_d[0];
if(csize == 0) continue;
/* vector<pair<NodeID, NodeID> > sorted_tmp;
unordered_map<NodeID, NodeID>& rc_map = sorted_sp[r]; */
for(EdgeWeight i = 0; i < csize; ++i){
NodeID cid = token.sptc_v[i + 1];
isChild[cid] = true;
}
//sort(sorted_tmp.rbegin(), sorted_tmp.rend());
const token_t& supertoken_r = supertokens[r];
//vector<bool>& one_level_t = one_level[t];
//NodeID second_level_length = ceil((double)supertoken_r.sptc_d[0] / (double)8);
NodeID first_level_length = ceil((double)supertoken_r.sptc_v[0] / (double)8);
//cout << first_level_length << "," << second_level_length << endl;
vector<bool> first_level_bv(first_level_length);
vector<bool> second_level_bv;
// NodeID t1 = 0;
NodeID t2 = 1;
// NodeID tt = sorted_tmp[t1].second;
NodeID st = supertoken_r.sptc_v[t2];
// NodeID ctsize = sorted_tmp.size();
NodeID stsize = supertoken_r.sptc_v[0];
//one_level_t.resize(stsize, false);
vector<bool> tmp_set(8, false);
for(NodeID i = 0; i < first_level_length; ++i){
NodeID in_batch = false;
//if(t1 != ctsize && t2 != stsize)
fill(tmp_set.begin(), tmp_set.end(), false);
for(NodeID j = 0; j < 8; ++j){
// if(t1 == ctsize) break;
if(t2 == (stsize + 1)) break;
// tt = sorted_tmp[t1].second;
st = supertoken_r.sptc_v[t2];
if(isChild[st]){
tmp_set[j] = true;
in_batch = true;
}
t2++;
}
if(in_batch == false)
first_level_bv[i] = false;
else{
first_level_bv[i] = true;
for(NodeID j = 0; j < 8; ++j)
second_level_bv.push_back(tmp_set[j]);
}
}
for(EdgeWeight i = 0; i < csize; ++i){
NodeID cid = token.sptc_v[i + 1];
isChild[cid] = false;
}
NodeID first_level_int_length = ceil((double)first_level_length/(double)8); // bytes
NodeID second_level_int_length = ceil((double)second_level_bv.size() / (double)8); // bytes
// if(t < 10) cout << "sl:" << r << "," << second_level_int_length << " vs " << second_level_bv.size() << " vs " << token.sptc_d[0] << ";" << stsize << " vs " << first_level_length << endl;
//supertoken_r.sptc_v[0] = stsize; //how many children for this supertoken
//supertoken_r.sptc_d[0] = first_level_int_length; //how many uchar to store for this token referring to this supertoken = stsize / 8 / 8
token.sptc_d[0] = second_level_int_length; //how many uchar to store for this token in second level
// convert first_level_bv -> uint8_t* sptc_fbv
// convert second_level_bv -> uint8_t* sptc_sbv
// first_level_bv % 8 == 0;
// second_level_bv % 8 == 0;
token.sptc_fbv = (unsigned char*)memalign(64, first_level_int_length * sizeof(unsigned char));
token.sptc_sbv = (unsigned char*)memalign(64, second_level_int_length * sizeof(unsigned char));
// cout << "first:" << endl;
for(NodeID i = 0; i < first_level_int_length; ++i){
token.sptc_fbv[i] = 0;
for(NodeID j = 0; j < 8; ++j){
token.sptc_fbv[i] = token.sptc_fbv[i] << 1;
if(first_level_bv[i * 8 + j]) ++token.sptc_fbv[i];
}
/*
bitset<8> x(token.sptc_fbv[i]);
cout << x << endl;
for(NodeID j = 0; j < 8; ++j){
if(first_level_bv[i * 8 + j])
cout << "1";
else
cout << "0";
}
cout << endl; */
}
//cout << endl;
//cout << "second:" << endl;
for(NodeID i = 0; i < second_level_int_length; ++i){
token.sptc_sbv[i] = 0;
for(NodeID j = 0; j < 8; ++j){
token.sptc_sbv[i] = token.sptc_sbv[i] << 1;
if(second_level_bv[i * 8 + j]) ++token.sptc_sbv[i];
}
// bitset<8> x(token.sptc_sbv[i]);
// cout << x ;
/* for(NodeID j = 0; j < 8; ++j){
if(second_level_bv[i * 8 + j])
cout << "1";
else
cout << "0";
} */
// cout << ",";
}
//cout << endl;
}
cout << " Number of Supertokens: " << supertokens.size() << endl;
cout << " Average Children of Supertokens: " << (double)total_supertoken_children / (double) supertokens.size() << endl;
}
CPL(Graph &graph, Ordering &orders, bool slevel) {
SECOND_LEVEL = slevel;
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t>& index_ = labels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
//vector<vector<NodeID> > &adj = graph.adj;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx_token_parents(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, numOfVertices)));
vector<bool> vis(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_token_parents_v = tmp_idx_token_parents[v];
index_t &idx_v = index_[inv[v]];
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
if(tmp_idx_v.second[i] == d + dst_r[w] && tmp_idx_token_parents_v.first[i] == numOfVertices){
tmp_idx_token_parents_v.first[i] = r;//tmp_idx_token_parents_v.first.size();
tmp_idx_token_parents_v.second[i] = dst_r[w];
}
if (td <= d) {
pruning_power[w]++;
goto pruned;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
tmp_idx_token_parents_v.first.back() = numOfVertices;
tmp_idx_token_parents_v.second.back() = INF_WEIGHT;
tmp_idx_token_parents_v.first.push_back(numOfVertices);
tmp_idx_token_parents_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];*/
for (EdgeID eid = graph.vertices[v]; eid < graph.vertices[v + 1]; ++eid){
NodeID w = graph.edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
converttokens(tmp_idx, tmp_idx_token_parents, false);
vector<NodeID> change_anchor(numOfVertices);
for (size_t v = 0; v < numOfVertices; ++v) {
change_anchor[inv[v]] = clabels.anchor_p[v];
}
for (size_t v = 0; v < numOfVertices; ++v) {
clabels.anchor_p[v] = change_anchor[v];
}
/*
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
}
*/
}
CPL(Graph &graph, Ordering &orders, bool slevel, bool D_FLAGS) {
SECOND_LEVEL = slevel;
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t>& index_ = dlabels.index_;
vector<index_t>& bindex_ = dlabels.bindex_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
/* vector<vector<NodeID> > &adj = graph.adj;
vector<vector<NodeID> > &r_adj = graph.r_adj;*/
// Array Representation
vector<EdgeID>& vertices = graph.vertices;
vector<EdgeID>& r_vertices = graph.r_vertices;
vector<NodeID>& edges = graph.edges;
vector<NodeID>& r_edges = graph.r_edges;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT))); // Backward labels.
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx_token_parents(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, numOfVertices)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx_token_parents(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, numOfVertices)));
vector<bool> vis(numOfVertices);
vector<NodeID> que(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT); // Forward labels of root.
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT); // Backward labels of root.
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
// Forward search.
// Initialize forward labels of r.
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
const pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_r = r_tmp_idx[r];
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i) {
r_dst_r[r_tmp_idx_r.first[i]] = r_tmp_idx_r.second[i];
}
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_v = r_tmp_idx[v];
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_token_parents_v = r_tmp_idx_token_parents[v];
//index_t &idx_v = index_[inv[v]];
if (usd[v]) continue;
// Pruned by the forward labels of r and backward labels of v in the forward search from r when reaching v.
for (size_t i = 0; i < r_tmp_idx_v.first.size(); ++i) {
NodeID w = r_tmp_idx_v.first[i];
EdgeWeight td = r_tmp_idx_v.second[i] + dst_r[w];
if(r_tmp_idx_v.second[i] == d + r_dst_r[w] && r_tmp_idx_token_parents_v.first[i] == numOfVertices){
r_tmp_idx_token_parents_v.first[i] = r;//tmp_idx_token_parents_v.first.size();
r_tmp_idx_token_parents_v.second[i] = r_dst_r[w];
}
if (td <= d) {
pruning_power[w]++;
goto pruned_forward;
}
}
// Traverse
r_tmp_idx_v.first.back() = r;
r_tmp_idx_v.second.back() = d;
r_tmp_idx_v.first.push_back(numOfVertices);
r_tmp_idx_v.second.push_back(INF_WEIGHT);
r_tmp_idx_token_parents_v.first.back() = numOfVertices;
r_tmp_idx_token_parents_v.second.back() = INF_WEIGHT;
r_tmp_idx_token_parents_v.first.push_back(numOfVertices);
r_tmp_idx_token_parents_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];*/
// Array Representation
for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid){
NodeID w = edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned_forward:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
// Backward search.
// Initialize backward labels of r.
que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = r;
vis[r] = true;
que_t1 = que_h;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_token_parents_v = tmp_idx_token_parents[v];
//index_t &idx_v = index_[inv[v]];
if (usd[v]) continue;
// Pruned by the backward labels of r and forward labels of v in the backward search from r when reaching v (v->r path).
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + r_dst_r[w];
if(tmp_idx_v.second[i] == d + dst_r[w] && tmp_idx_token_parents_v.first[i] == numOfVertices){
tmp_idx_token_parents_v.first[i] = r;//tmp_idx_token_parents_v.first.size();
tmp_idx_token_parents_v.second[i] = dst_r[w];
}
if (td <= d) {
pruning_power[w]++;
goto pruned_backward;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
tmp_idx_token_parents_v.first.back() = numOfVertices;
tmp_idx_token_parents_v.second.back() = INF_WEIGHT;
tmp_idx_token_parents_v.first.push_back(numOfVertices);
tmp_idx_token_parents_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < r_adj[v].size(); ++i) {
NodeID w = r_adj[v][i];*/
// Array Representation
for (EdgeID eid = r_vertices[v]; eid < r_vertices[v + 1]; ++eid) {
NodeID w = r_edges[eid];
if (!vis[w]) {
que[que_h++] = w;
vis[w] = true;
}
}
pruned_backward:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
for (size_t i = 0; i < que_h; ++i) vis[que[i]] = false;
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i)
r_dst_r[r_tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
converttokens(tmp_idx, tmp_idx_token_parents, false);
//converttokens(tmp_idx, tmp_idx_token_parents, r_tmp_idx, r_tmp_idx_token_parents);
cout << clabels.numOfTokens << " Tokens in total" << endl;
cout << (double)children_size / (double) clabels.numOfTokens << " average children number" << endl;
converttokens(r_tmp_idx, r_tmp_idx_token_parents, true);
cout << clabels.r_numOfTokens << " Tokens in total" << endl;
cout << (double)r_children_size / (double) clabels.r_numOfTokens << " average children number" << endl;
vector<NodeID> change_anchor(numOfVertices);
for (size_t v = 0; v < numOfVertices; ++v) {
change_anchor[inv[v]] = clabels.anchor_p[v];
}
for (size_t v = 0; v < numOfVertices; ++v) {
clabels.anchor_p[v] = change_anchor[v];
}
for (size_t v = 0; v < numOfVertices; ++v) {
change_anchor[inv[v]] = clabels.r_anchor_p[v];
}
for (size_t v = 0; v < numOfVertices; ++v) {
clabels.r_anchor_p[v] = change_anchor[v];
}
}
};
class CPL_W : public construction {
public:
vector<double> iteration_generated;
vector<double> pruning_power;
bool SECOND_LEVEL = false;
long children_size;
long r_children_size;
class nodeid_vector_hasher {
public:
std::size_t operator()(std::pair<NodeID, std::vector<NodeID> > const& pairvec) const {
std::size_t seed = pairvec.second.size();
seed ^= pairvec.first + 0x9e3779b9 + (seed << 6) + (seed >> 2);
for(auto& i : pairvec.second) {
seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
//using boost::hash_combine
template <class T>
inline void hash_combine(std::size_t& seed, T const& v)
{
seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
NodeID convertlist(NodeID& token_id, vector<token_t>& tokens_list, vector<vector<NodeID> >& tmp_tokens, vector<vector<EdgeWeight> >& tmp_tokens_distances, unordered_map<pair<NodeID, vector<NodeID> >, NodeID, nodeid_vector_hasher>& token_map, pair<vector<NodeID>, vector<EdgeWeight> > & tmp_idx_v, pair<vector<NodeID>, vector<NodeID> >& tmp_idx_token_parents_v, bool REVERSE){
NodeID lsize = tmp_idx_v.first.size();
NodeID anchorid = tmp_idx_v.first[lsize-2];
for(NodeID i = 0; i < lsize - 1; ++i){
//Add to parent_tree
NodeID h = tmp_idx_v.first[i];
NodeID hparent = tmp_idx_token_parents_v.first[i];
EdgeWeight hparent_dis = tmp_idx_token_parents_v.second[i];
NodeID tid = h;
// non-trival tokens
if(tmp_tokens[h].size() != 0){
vector<NodeID>& tmp_token_h = tmp_tokens[h];
//string tstring = token_string(h, tmp_token_h);
vector<EdgeWeight>& tmp_tokens_distances_h = tmp_tokens_distances[h];
pair<NodeID, vector<NodeID> > token_key = make_pair(h, tmp_token_h);
// New token
if(token_map.find(token_key) == token_map.end()){
token_map[token_key] = token_id;
token_t new_token;
NodeID csize = tmp_token_h.size();
new_token.sptc_v = (NodeID*)memalign(64, (csize + 1)* sizeof(NodeID));
new_token.sptc_d = (EdgeWeight*)memalign(64, (csize + 1) * sizeof(EdgeWeight));
new_token.sptc_v[0] = h;
new_token.sptc_d[0] = csize;
if(REVERSE)
r_children_size += (csize + 1);
else
children_size += (csize + 1);
for(NodeID j = 0; j < csize; ++j){
new_token.sptc_v[j+1] = tmp_token_h[j];
new_token.sptc_d[j+1] = tmp_tokens_distances_h[j];
}
tokens_list.push_back(new_token);
tid = token_id;
token_id++;
}else // Already exist
tid = token_map[token_key];
}
//trival tokens
if(i == lsize - 2)
anchorid = tid;
if(hparent!=numOfVertices){
tmp_tokens[hparent].push_back(tid);
tmp_tokens_distances[hparent].push_back(hparent_dis);
}
}
return anchorid;
}
void converttokens(vector<pair<vector<NodeID>, vector<EdgeWeight> > > & tmp_idx, vector<pair<vector<NodeID>, vector<NodeID> > >& tmp_idx_token_parents, bool REVERSE){
vector<token_t> tokens_list;
vector<token_t> r_tokens_list;
vector<vector<NodeID> > tmp_tokens(numOfVertices);
vector<vector<EdgeWeight> > tmp_tokens_distances(numOfVertices);
vector<vector<NodeID> > r_tmp_tokens(numOfVertices);
vector<vector<EdgeWeight> > r_tmp_tokens_distances(numOfVertices);
unordered_map<pair<NodeID, vector<NodeID> >, NodeID, nodeid_vector_hasher> token_map;
unordered_map<pair<NodeID, vector<NodeID> >, NodeID, nodeid_vector_hasher> r_token_map;
if(REVERSE == false)
children_size = 0;
else
r_children_size = 0;
NodeID token_id = numOfVertices;
NodeID r_token_id = numOfVertices;
if(REVERSE == false)
clabels.anchor_p = (NodeID*)memalign(64, (numOfVertices)* sizeof(NodeID));
else
clabels.r_anchor_p = (NodeID*)memalign(64, (numOfVertices)* sizeof(NodeID));
//vector<NodeID> que(numOfVertices, numOfVertices);
for(NodeID v = 0; v < numOfVertices; ++v){
if(REVERSE == false)
clabels.anchor_p[v] = convertlist(token_id, tokens_list, tmp_tokens, tmp_tokens_distances, token_map, tmp_idx[v], tmp_idx_token_parents[v], REVERSE);
else
clabels.r_anchor_p[v] = convertlist(r_token_id, r_tokens_list, r_tmp_tokens, r_tmp_tokens_distances, r_token_map, tmp_idx[v], tmp_idx_token_parents[v], REVERSE);
//if(REVERSE == true)
// validation(tmp_idx[v], tmp_idx_token_parents[v], tokens_list, clabels.r_anchor_p[v], que);
if(REVERSE == false){
NodeID lsize = tmp_idx[v].first.size();
for(NodeID i = 0; i < lsize - 1; ++i){
NodeID h = tmp_idx[v].first[i];
NodeID hparent = tmp_idx_token_parents[v].first[i];
if( hparent != numOfVertices ){
if(tmp_tokens[hparent].empty() == false){
tmp_tokens[hparent].clear();
tmp_tokens_distances[hparent].clear();
}
}
}
}else{
NodeID lsize = tmp_idx[v].first.size();
for(NodeID i = 0; i < lsize - 1; ++i){
NodeID h = tmp_idx[v].first[i];
NodeID hparent = tmp_idx_token_parents[v].first[i];
if( hparent != numOfVertices ){
if(r_tmp_tokens[hparent].empty() == false){
r_tmp_tokens[hparent].clear();
r_tmp_tokens_distances[hparent].clear();
}
}
}
}
}
//vector<vector<bool> > one_level(tokens_list.size());
if(REVERSE == false){
clabels.numOfTokens = tokens_list.size();
clabels.tokenindex_p = (token_t*)memalign(64, clabels.numOfTokens * sizeof(token_t));
for(NodeID i = 0; i < clabels.numOfTokens; ++i){
clabels.tokenindex_p[i] = tokens_list[i];
}
}else{
clabels.r_numOfTokens = r_tokens_list.size();
clabels.r_tokenindex_p = (token_t*)memalign(64, clabels.r_numOfTokens * sizeof(token_t));
for(NodeID i = 0; i < clabels.r_numOfTokens; ++i){
clabels.r_tokenindex_p[i] = r_tokens_list[i];
}
}
if(REVERSE == false){
if(SECOND_LEVEL){
vector<token_t> supertokens(numOfVertices);
convertsupertokens(tokens_list, supertokens);
clabels.supertokenindex_p = (token_t*)memalign(64, numOfVertices * sizeof(token_t));
for(NodeID i = 0; i < supertokens.size(); ++i){
clabels.supertokenindex_p[i] = supertokens[i];
}
for(NodeID i = 0; i < clabels.numOfTokens; ++i){
clabels.tokenindex_p[i] = tokens_list[i];
}
//convertsupertokens(clabels.tokenindex_p, clabels.supertokenindex_p, clabels.numOfTokens);
//vector<NodeID> que(numOfVertices, numOfVertices);
//for(NodeID v = 0; v < numOfVertices; ++v){
//if(REVERSE) {
//cout << v << endl;
//validation(tmp_idx[v], tmp_idx_token_parents[v], tokens_list,supertokens, clabels.anchor_p[v], que);
//validation(tmp_idx[v], tmp_idx_token_parents[v], tokens_list, clabels.supertokenindex_p, clabels.anchor_p[v], que);
//}
//}
}
}else{
if(SECOND_LEVEL){
//convertsupertokens(clabels.r_tokenindex_p, clabels.r_supertokenindex_p, clabels.r_numOfTokens);
vector<token_t> r_supertokens(numOfVertices);
convertsupertokens(r_tokens_list, r_supertokens);
clabels.r_supertokenindex_p = (token_t*)memalign(64, numOfVertices * sizeof(token_t));
for(NodeID i = 0; i < r_supertokens.size(); ++i){
clabels.r_supertokenindex_p[i] = r_supertokens[i];
}
for(NodeID i = 0; i < clabels.r_numOfTokens; ++i){
clabels.r_tokenindex_p[i] = r_tokens_list[i];
}
/*
//vector<NodeID> que(numOfVertices, numOfVertices);
for(NodeID v = 0; v < numOfVertices; ++v){
//if(REVERSE) {
cout << v << endl;
//validation(tmp_idx[v], tmp_idx_token_parents[v], r_tokens_list, r_supertokens, clabels.r_anchor_p[v], que);
validation(tmp_idx[v], tmp_idx_token_parents[v], r_tokens_list, clabels.r_supertokenindex_p, clabels.r_anchor_p[v], que);
//}
}*/
}
}
clabels.total_children = children_size;
}
void convertsupertokens(vector<token_t>& tokens_list, vector<token_t>& supertokens){
vector<unordered_map<NodeID, NodeID> > sorted_sp(numOfVertices);
vector<unordered_map<NodeID, EdgeWeight> > dis_sp(numOfVertices);
NodeID total_supertoken_children = 0;
for(NodeID t = 0 ; t < tokens_list.size(); ++t){
token_t& token = tokens_list[t];
NodeID r = token.sptc_v[0];
EdgeWeight csize = token.sptc_d[0];
unordered_map<NodeID, NodeID>& rc_map = sorted_sp[r];
unordered_map<NodeID, EdgeWeight>& rd_map = dis_sp[r];
for(EdgeWeight i = 0; i < csize; ++i){
NodeID cid = token.sptc_v[i + 1];
rc_map[cid]++;
rd_map[cid] = token.sptc_d[i + 1];
}
}
//supertokens.resize(numOfVertices);
// Creating super tokens, sorting the children based on frequency
for(NodeID v = 0; v < numOfVertices; ++v){
vector<pair<NodeID, NodeID> > sorted_tmp;
unordered_map<NodeID, NodeID>& vc_map = sorted_sp[v];
unordered_map<NodeID, EdgeWeight>& vd_map = dis_sp[v];
for(unordered_map<NodeID, NodeID>::iterator it = vc_map.begin(); it != vc_map.end(); ++it){
sorted_tmp.push_back(make_pair((*it).second, (*it).first));
}
sort(sorted_tmp.rbegin(), sorted_tmp.rend());
token_t new_token;
EdgeWeight csize = sorted_tmp.size();
new_token.sptc_v = (NodeID*)memalign(64, (csize + 1)* sizeof(NodeID));
new_token.sptc_d = (EdgeWeight*)memalign(64, (csize + 1) * sizeof(EdgeWeight));
new_token.sptc_v[0] = csize;
new_token.sptc_d[0] = ceil((double)ceil((double)csize / (double)8) / (double)8);
for(NodeID i = 0; i < csize; ++i){
NodeID cid = sorted_tmp[i].second;
new_token.sptc_v[i + 1] = cid;
new_token.sptc_d[i + 1] = vd_map[cid];
}
supertokens[v] = new_token;
total_supertoken_children += csize;
}
// Converting each tokens to supertokens
vector<bool> isChild(numOfVertices + tokens_list.size(), false);
for(NodeID t = 0 ; t < tokens_list.size(); ++t){
token_t& token = tokens_list[t];
NodeID r = token.sptc_v[0];
EdgeWeight csize = token.sptc_d[0];
if(csize == 0) continue;
/* vector<pair<NodeID, NodeID> > sorted_tmp;
unordered_map<NodeID, NodeID>& rc_map = sorted_sp[r]; */
for(EdgeWeight i = 0; i < csize; ++i){
NodeID cid = token.sptc_v[i + 1];
isChild[cid] = true;
}
//sort(sorted_tmp.rbegin(), sorted_tmp.rend());
const token_t& supertoken_r = supertokens[r];
//vector<bool>& one_level_t = one_level[t];
//NodeID second_level_length = ceil((double)supertoken_r.sptc_d[0] / (double)8);
NodeID first_level_length = ceil((double)supertoken_r.sptc_v[0] / (double)8);
//cout << first_level_length << "," << second_level_length << endl;
vector<bool> first_level_bv(first_level_length);
vector<bool> second_level_bv;
// NodeID t1 = 0;
NodeID t2 = 1;
// NodeID tt = sorted_tmp[t1].second;
NodeID st = supertoken_r.sptc_v[t2];
// NodeID ctsize = sorted_tmp.size();
NodeID stsize = supertoken_r.sptc_v[0];
//one_level_t.resize(stsize, false);
vector<bool> tmp_set(8, false);
for(NodeID i = 0; i < first_level_length; ++i){
NodeID in_batch = false;
//if(t1 != ctsize && t2 != stsize)
fill(tmp_set.begin(), tmp_set.end(), false);
for(NodeID j = 0; j < 8; ++j){
// if(t1 == ctsize) break;
if(t2 == (stsize + 1)) break;
// tt = sorted_tmp[t1].second;
st = supertoken_r.sptc_v[t2];
if(isChild[st]){
tmp_set[j] = true;
in_batch = true;
}
t2++;
}
if(in_batch == false)
first_level_bv[i] = false;
else{
first_level_bv[i] = true;
for(NodeID j = 0; j < 8; ++j)
second_level_bv.push_back(tmp_set[j]);
}
}
for(EdgeWeight i = 0; i < csize; ++i){
NodeID cid = token.sptc_v[i + 1];
isChild[cid] = false;
}
NodeID first_level_int_length = ceil((double)first_level_length/(double)8); // bytes
NodeID second_level_int_length = ceil((double)second_level_bv.size() / (double)8); // bytes
// if(t < 10) cout << "sl:" << r << "," << second_level_int_length << " vs " << second_level_bv.size() << " vs " << token.sptc_d[0] << ";" << stsize << " vs " << first_level_length << endl;
//supertoken_r.sptc_v[0] = stsize; //how many children for this supertoken
//supertoken_r.sptc_d[0] = first_level_int_length; //how many uchar to store for this token referring to this supertoken = stsize / 8 / 8
token.sptc_d[0] = second_level_int_length; //how many uchar to store for this token in second level
// convert first_level_bv -> uint8_t* sptc_fbv
// convert second_level_bv -> uint8_t* sptc_sbv
// first_level_bv % 8 == 0;
// second_level_bv % 8 == 0;
token.sptc_fbv = (unsigned char*)memalign(64, first_level_int_length * sizeof(unsigned char));
token.sptc_sbv = (unsigned char*)memalign(64, second_level_int_length * sizeof(unsigned char));
// cout << "first:" << endl;
for(NodeID i = 0; i < first_level_int_length; ++i){
token.sptc_fbv[i] = 0;
for(NodeID j = 0; j < 8; ++j){
token.sptc_fbv[i] = token.sptc_fbv[i] << 1;
if(first_level_bv[i * 8 + j]) ++token.sptc_fbv[i];
}
/*
bitset<8> x(token.sptc_fbv[i]);
cout << x << endl;
for(NodeID j = 0; j < 8; ++j){
if(first_level_bv[i * 8 + j])
cout << "1";
else
cout << "0";
}
cout << endl; */
}
//cout << endl;
//cout << "second:" << endl;
for(NodeID i = 0; i < second_level_int_length; ++i){
token.sptc_sbv[i] = 0;
for(NodeID j = 0; j < 8; ++j){
token.sptc_sbv[i] = token.sptc_sbv[i] << 1;
if(second_level_bv[i * 8 + j]) ++token.sptc_sbv[i];
}
// bitset<8> x(token.sptc_sbv[i]);
// cout << x ;
/* for(NodeID j = 0; j < 8; ++j){
if(second_level_bv[i * 8 + j])
cout << "1";
else
cout << "0";
} */
// cout << ",";
}
//cout << endl;
}
cout << " Number of Supertokens: " << supertokens.size() << endl;
cout << " Average Children of Supertokens: " << (double)total_supertoken_children / (double) supertokens.size() << endl;
}
CPL_W(WGraph &wgraph, Ordering &orders, bool slevel) {
SECOND_LEVEL = slevel;
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t>& index_ = labels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
// vector<vector<NodeID> > &adj = wgraph.adj;
// vector<vector<EdgeWeight> > &adj_weight = wgraph.adj_weight;
vector<EdgeID>& vertices = wgraph.vertices;
vector<NodeEdgeWeightPair>& edges = wgraph.edges;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx_token_parents(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, numOfVertices)));
vector<bool> vis(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
queue<NodeID> visited_que;
vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
long pop = 0;
double hsize = 0;
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
pqueue.update(r, 0);
//vis[r] = true;
long max_heap_size = 0;
long heap_size = 1;
while (!pqueue.empty()) {
pop++;
heap_size--;
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_token_parents_v = tmp_idx_token_parents[v];
vis[v] = true;
visited_que.push(v);
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
if(tmp_idx_v.second[i] == v_d + dst_r[w] && tmp_idx_token_parents_v.first[i] == numOfVertices){
tmp_idx_token_parents_v.first[i] = r;//tmp_idx_token_parents_v.first.size();
tmp_idx_token_parents_v.second[i] = dst_r[w];
}
if (td <= v_d) {
pruning_power[w]++;
goto pruned;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = v_d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
tmp_idx_token_parents_v.first.back() = numOfVertices;
tmp_idx_token_parents_v.second.back() = INF_WEIGHT;
tmp_idx_token_parents_v.first.push_back(numOfVertices);
tmp_idx_token_parents_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
// for (size_t i = 0; i < adj[v].size(); ++i) {
// NodeID w = adj[v][i];
// EdgeWeight w_d = adj_weight[v][i] + v_d;
for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid) {
NodeID w = edges[eid].first;
EdgeWeight w_d = edges[eid].second + v_d;
if (!vis[w]) {
if (distances[w] == INF_WEIGHT) {
heap_size++;
if (max_heap_size < heap_size)
max_heap_size = heap_size;
}
if( distances[w] > w_d ){
pqueue.update(w, w_d);
distances[w] = w_d;
}
}
}
pruned:
{}
}
hsize = hsize + max_heap_size;
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
pqueue.clear(vis_v);
}
pqueue.clear_n();
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
//cout << "total pop:" << pop << endl;
//cout << "heap size:" << (double)hsize / (double)numOfVertices << endl;
converttokens(tmp_idx, tmp_idx_token_parents, false);
vector<NodeID> change_anchor(numOfVertices);
for (size_t v = 0; v < numOfVertices; ++v) {
change_anchor[inv[v]] = clabels.anchor_p[v];
}
for (size_t v = 0; v < numOfVertices; ++v) {
clabels.anchor_p[v] = change_anchor[v];
}
/*
double count = 0;
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
count = count + k - 1;
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
}
cout << "Average_label_size: " << count / numOfVertices << endl;
*/
}
CPL_W(WGraph &wgraph, Ordering &orders, bool slevel, bool D_FLAGS) {
SECOND_LEVEL = slevel;
iteration_generated.resize(numOfVertices);
pruning_power.resize(numOfVertices);
vector<index_t>& index_ = dlabels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
/*vector<vector<NodeID> > &adj = wgraph.adj;
vector<vector<EdgeWeight> > &adj_weight = wgraph.adj_weight;*/
vector<index_t>& bindex_ = dlabels.bindex_;/*
vector<vector<NodeID> > &r_adj = wgraph.r_adj;
vector<vector<EdgeWeight> > &r_adj_weight = wgraph.r_adj_weight;*/
//Array Representation
vector<EdgeID>& vertices = wgraph.vertices;
vector<EdgeID>& r_vertices = wgraph.r_vertices;
vector<NodeEdgeWeightPair>& edges = wgraph.edges;
vector<NodeEdgeWeightPair>& r_edges = wgraph.r_edges;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx_token_parents(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, numOfVertices)));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx_token_parents(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, numOfVertices)));
vector<bool> vis(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT);
queue<NodeID> visited_que;
vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
// Forward search from r.
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
const pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_r = r_tmp_idx[r];
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i) {
r_dst_r[r_tmp_idx_r.first[i]] = r_tmp_idx_r.second[i];
}
pqueue.update(r, 0);
//vis[r] = true;
while (!pqueue.empty()) {
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_v = r_tmp_idx[v];
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_token_parents_v = r_tmp_idx_token_parents[v];
vis[v] = true;
visited_que.push(v);
if (usd[v]) continue;
for (size_t i = 0; i < r_tmp_idx_v.first.size(); ++i) {
NodeID w = r_tmp_idx_v.first[i];
EdgeWeight td = r_tmp_idx_v.second[i] + dst_r[w];
if(r_tmp_idx_v.second[i] == v_d + r_dst_r[w] && r_tmp_idx_token_parents_v.first[i] == numOfVertices){
r_tmp_idx_token_parents_v.first[i] = r;//tmp_idx_token_parents_v.first.size();
r_tmp_idx_token_parents_v.second[i] = r_dst_r[w];
}
if (td <= v_d) {
pruning_power[w]++;
goto pruned_forward;
}
}
// Traverse
r_tmp_idx_v.first.back() = r;
r_tmp_idx_v.second.back() = v_d;
r_tmp_idx_v.first.push_back(numOfVertices);
r_tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
r_tmp_idx_token_parents_v.first.back() = numOfVertices;
r_tmp_idx_token_parents_v.second.back() = INF_WEIGHT;
r_tmp_idx_token_parents_v.first.push_back(numOfVertices);
r_tmp_idx_token_parents_v.second.push_back(INF_WEIGHT);
/* for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i];
EdgeWeight w_d = adj_weight[v][i] + v_d;*/
//Array Representation
for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid) {
NodeID w = edges[eid].first;
EdgeWeight w_d = edges[eid].second + v_d;
if (!vis[w]) {
if (distances[w] > w_d) {
pqueue.update(w, w_d);
distances[w] = w_d;
}
}
}
pruned_forward:
{}
}
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
//pqueue.clear(vis_v);
}
//pqueue.clear_n();
// Backward search from r.
pqueue.update(r, 0);
while (!pqueue.empty()) {
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_token_parents_v = tmp_idx_token_parents[v];
vis[v] = true;
visited_que.push(v);
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + r_dst_r[w];
if(tmp_idx_v.second[i] == v_d + dst_r[w] && tmp_idx_token_parents_v.first[i] == numOfVertices){
tmp_idx_token_parents_v.first[i] = r;//tmp_idx_token_parents_v.first.size();
tmp_idx_token_parents_v.second[i] = dst_r[w];
}
if (td <= v_d) {
pruning_power[w]++;
goto pruned_backward;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = v_d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
tmp_idx_token_parents_v.first.back() = numOfVertices;
tmp_idx_token_parents_v.second.back() = INF_WEIGHT;
tmp_idx_token_parents_v.first.push_back(numOfVertices);
tmp_idx_token_parents_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
/*for (size_t i = 0; i < r_adj[v].size(); ++i) {
NodeID w = r_adj[v][i];
EdgeWeight w_d = r_adj_weight[v][i] + v_d;*/
//Array Representation
for (EdgeID eid = r_vertices[v]; eid < r_vertices[v + 1]; ++eid) {
NodeID w = r_edges[eid].first;
EdgeWeight w_d = r_edges[eid].second + v_d;
if (!vis[w]) {
if (distances[w] > w_d) {
pqueue.update(w, w_d);
distances[w] = w_d;
}
}
}
pruned_backward:
{}
}
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
//pqueue.clear(vis_v);
}
// pqueue.clear_n();
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
for (size_t i = 0; i < r_tmp_idx_r.first.size(); ++i)
r_dst_r[r_tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
converttokens(tmp_idx, tmp_idx_token_parents, false);
//converttokens(tmp_idx, tmp_idx_token_parents, r_tmp_idx, r_tmp_idx_token_parents);
cout << clabels.numOfTokens << " Tokens in total" << endl;
cout << (double)children_size / (double) clabels.numOfTokens << " average children number" << endl;
converttokens(r_tmp_idx, r_tmp_idx_token_parents, true);
cout << clabels.r_numOfTokens << " Tokens in total" << endl;
cout << (double)r_children_size / (double) clabels.r_numOfTokens << " average children number" << endl;
vector<NodeID> change_anchor(numOfVertices);
for (size_t v = 0; v < numOfVertices; ++v) {
change_anchor[inv[v]] = clabels.anchor_p[v];
}
for (size_t v = 0; v < numOfVertices; ++v) {
clabels.anchor_p[v] = change_anchor[v];
}
for (size_t v = 0; v < numOfVertices; ++v) {
change_anchor[inv[v]] = clabels.r_anchor_p[v];
}
for (size_t v = 0; v < numOfVertices; ++v) {
clabels.r_anchor_p[v] = change_anchor[v];
}
/*
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
tmp_idx[v].first.shrink_to_fit();
tmp_idx[v].second.shrink_to_fit();
k = r_tmp_idx[v].first.size();
bindex_[inv[v]].spt_v.resize(k);
bindex_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_v[i] = r_tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_d[i] = r_tmp_idx[v].second[i];
r_tmp_idx[v].first.clear();
r_tmp_idx[v].second.clear();
r_tmp_idx[v].first.shrink_to_fit();
r_tmp_idx[v].second.shrink_to_fit();
}*/
}
};
class Bottomup : public construction {
public:
vector<double> iteration_generated;
vector<double> pruning_power;
typedef vector<pair<NodeID, EdgeWeight> > Bucket;
vector<bool> contracted;
vector<Bucket> mtmBucket;
vector<EdgeWeight> possibleWitness;
int relabelByOrder(CHGraph &chgraph, Ordering &orders) {
int totalEdge = 0;
vector<NodeID>& inv = orders.inv;
vector<NodeID>& rank = orders.rank;
for (NodeID v = 0; v < numOfVertices; ++v) rank[inv[v]] = v;
vector<vector<CHGraph::CH_Edge> > new_adj(numOfVertices);
vector<vector<CHGraph::CH_Edge> > new_r_adj(numOfVertices);
//for (int i = 0; i < numOfVertices; ++i) {
// for (int j = 0; j < chgraph.adj[i].size(); ++j) {
// if (j != chgraph.adj[i].size() - 1)
// if (chgraph.adj[i][j].target == chgraph.adj[i][j + 1].target) {
// cout << i << " hahaah:" << chgraph.adj[i][j].weight << "," << chgraph.adj[i][j + 1].weight << endl;
// }
// }
//}
for (NodeID v = 0; v < numOfVertices; ++v) {
for (NodeID i = 0; i < chgraph.adj[v].size(); ++i)
new_adj[rank[v]].push_back(CHGraph::CH_Edge(rank[chgraph.adj[v][i].target], 0, chgraph.adj[v][i].weight));
totalEdge += chgraph.adj[v].size();
if (DIRECTED_FLAG == true) {
totalEdge += chgraph.r_adj[v].size();
for (NodeID i = 0; i < chgraph.r_adj[v].size(); ++i)
new_r_adj[rank[v]].push_back(CHGraph::CH_Edge(rank[chgraph.r_adj[v][i].target], 0, chgraph.r_adj[v][i].weight));
}
}
chgraph.adj.swap(new_adj);
if (DIRECTED_FLAG == true) {
chgraph.r_adj.swap(new_r_adj);
}
for (int i = 0; i < numOfVertices; ++i) {
if (DIRECTED_FLAG == true) {
sort(chgraph.r_adj[i].begin(), chgraph.r_adj[i].end());
}
}
new_adj.clear();
if (DIRECTED_FLAG == true) {
new_r_adj.clear();
}
return totalEdge;
}
int witness_search(NodeID v, CHGraph& chgraph, const int hopLimitsParameter, Ordering& orders, vector<bool>& vis, benchmark::heap<2, EdgeWeight, NodeID>& pqueue, unordered_set<NodeID>& visited_set, vector<EdgeWeight>& distances, vector<bool>& hitTarget) {
int addShortcuts = 0;
vector<CHGraph::CH_Edge>& inEdges = chgraph.adj[v];
vector<CHGraph::CH_Edge>& outEdges = chgraph.adj[v];
vector<pair<NodeID, CHGraph::CH_Edge> > possibleShortcuts;
// 1-hop witness search
if (hopLimitsParameter == 1) {
for (int i = 0; i < inEdges.size(); ++i) {
//if (inEdges[i].level == V) continue;
NodeID inNode = inEdges[i].target;
if (inNode >= v) continue; // Skip the nodes that have been already contracted.
EdgeWeight inWeight = inEdges[i].weight;
vector<CHGraph::CH_Edge>& outEdgesOfInNode = chgraph.adj[inNode];
for (int j = 0; j < outEdges.size(); ++j) {
//if (outEdges[j].level == V) continue;
NodeID outNode = outEdges[j].target;
if (outNode > v ) continue; // Skip the nodes that have been already contracted.
if (outNode >= inNode) continue; // For undirected case, only test each pair once and we also skip the case inNode == outNode
EdgeWeight outWeight = outEdges[j].weight;
EdgeWeight walkThroughWeight = inWeight + outWeight; // Distance for the path (inNode - v - outNode).
bool foundWitness = false;
for (int k = 0; k < outEdgesOfInNode.size(); ++k) {
NodeID outNeighborOfInNode = outEdgesOfInNode[k].target;
// if (outNeighborLevelOfInNode == V) continue;
if (outNeighborOfInNode >= v) continue; // Skip the ondes that have been already contracted.
if (outNeighborOfInNode == outNode) {
EdgeWeight outNeighborWeightOfInNode = outEdgesOfInNode[k].weight; // Distance for the direct path (inNode - outNode).
if (outNeighborWeightOfInNode <= walkThroughWeight) {
foundWitness = true;
//walkThroughWeight = outNeighborWeightOfInNode;
}
break;
}
}
if (foundWitness == false) {
possibleShortcuts.push_back(make_pair(inNode, CHGraph::CH_Edge(outNode, v, walkThroughWeight)));
}
}
}
}
// 2-hop witness search.
if (hopLimitsParameter == 2) {
// Init the many-to-many bucket.
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode >= v) continue; // Skip the nodes that have been already contracted.
EdgeWeight outWeight = outEdges[j].weight;
vector<CHGraph::CH_Edge>& inEdgesOfOutNode = chgraph.adj[outNode];
for (int k = 0; k < inEdgesOfOutNode.size(); ++k) {
NodeID inNeighborOfOutNode = inEdgesOfOutNode[k].target;
NodeID inNeighborLevelOfOutNode = inEdgesOfOutNode[k].level;
EdgeWeight inNeighborWeightOfOutNode = inEdgesOfOutNode[k].weight;
if (inNeighborOfOutNode >= v) continue; // Skip the nodes that have been already contracted. And skip the current contracted node (this is important).
mtmBucket[inNeighborOfOutNode].push_back(make_pair(outNode, inNeighborWeightOfOutNode));
}
}
// Finish the init.
for (int i = 0; i < inEdges.size(); ++i) {
NodeID inNode = inEdges[i].target;
if (inNode >= v) continue; // Skip the nodes that have bee n already contracted.
EdgeWeight inWeight = inEdges[i].weight;
vector<CHGraph::CH_Edge>& outEdgesOfInNode = chgraph.adj[inNode];
// One-hop witness search from the bucket of inNode.
Bucket& bucketInNode = mtmBucket[inNode];
for (int k = 0; k < bucketInNode.size(); ++k) {
NodeID target = bucketInNode[k].first;
EdgeWeight targetWeight = bucketInNode[k].second;
if (target >= inNode) continue;
if (possibleWitness[target] > targetWeight)
possibleWitness[target] = targetWeight;
}
// Two-hop witness search from inNode.
// 1-hop forward search from inNode and scan the buckets of the reached nodes to find the length of 2-hop witness.
for (int k = 0; k < outEdgesOfInNode.size(); ++k) {
NodeID reachNode = outEdgesOfInNode[k].target;
if (reachNode >= v) continue;// Skip the nodes that have been already contracted.
NodeID reachNodeLevel = outEdgesOfInNode[k].level;
EdgeWeight reachNodeWeight = outEdgesOfInNode[k].weight;
Bucket& bucketReachNode = mtmBucket[reachNode];
for (int q = 0; q < bucketReachNode.size(); ++q) {
NodeID target = bucketReachNode[q].first;
if (target >= inNode) continue;
EdgeWeight newTargetWeight = bucketReachNode[q].second + reachNodeWeight;
if (possibleWitness[target] > newTargetWeight)
possibleWitness[target] = newTargetWeight;
}
}
// Scan the outNode of v, to check whether shortcuts are needed for (inNode - v - outNode).
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode > v) {
possibleWitness[outNode] = INF_WEIGHT;
continue;
}
if (outNode >= inNode) {
possibleWitness[outNode] = INF_WEIGHT;
continue;
}// undirected, scan each pair only once.
EdgeWeight outWeight = outEdges[j].weight;
EdgeWeight witnessWeight = possibleWitness[outNode];
possibleWitness[outNode] = INF_WEIGHT;
EdgeWeight walkThroughWeight = inWeight + outWeight;
if(witnessWeight > walkThroughWeight)
possibleShortcuts.push_back(make_pair(inNode, CHGraph::CH_Edge(outNode, v, walkThroughWeight)));
}
}
// Cleanup the many-to-many bucket.
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode > v) continue;
EdgeWeight outWeight = outEdges[j].weight;
vector<CHGraph::CH_Edge>& inEdgesOfOutNode = chgraph.adj[outNode];
for (int k = 0; k < inEdgesOfOutNode.size(); ++k) {
NodeID inNeighborOfOutNode = inEdgesOfOutNode[k].target;
NodeID inNeighborLevelOfOutNode = inEdgesOfOutNode[k].level;
EdgeWeight inNeighborWeightOfOutNode = inEdgesOfOutNode[k].weight;
if (inNeighborOfOutNode >= v) continue;
if(!mtmBucket[inNeighborOfOutNode].empty())
mtmBucket[inNeighborOfOutNode].clear();
}
}
}
// Dijkstra Local Search.
if (hopLimitsParameter > 2) {
// Init the target table.
int noOfTarget = 0;
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode >= v) continue; // Skip the nodes that have been already contracted.
hitTarget[outNode] = true;
noOfTarget++;
}
// Loop the incoming node for witness search.
for (int i = 0; i < inEdges.size(); ++i) {
//if (inEdges[i].level == V) continue;
NodeID inNode = inEdges[i].target;
int visitedTarget = 0;
if (inNode >= v) continue; // Skip the nodes that have been already contracted.
EdgeWeight inWeight = inEdges[i].weight;
vector<CHGraph::CH_Edge>& outEdgesOfInNode = chgraph.adj[inNode];
pqueue.update(inNode, 0);
visited_set.insert(inNode);
distances[inNode] = 0;
while (!pqueue.empty()) {
NodeID u;
EdgeWeight u_d;
pqueue.extract_min(u, u_d);
vis[u] = true;
if (hitTarget[u] == true)
visitedTarget++;
if (visitedTarget == noOfTarget)
break;
for (int j = 0; j < chgraph.adj[u].size(); ++j) {
NodeID w = chgraph.adj[u][j].target;
EdgeWeight w_d = chgraph.adj[u][j].weight + u_d;
if (w >= v) continue; // Can not visit contracted nodes.
if (!vis[w]) {
if (distances[w] > w_d) {
pqueue.update(w, w_d);
distances[w] = w_d;
visited_set.insert(w);
}
}
}
}
// Test witness for all outNode.
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode >= v) continue;
if (outNode >= inNode) continue; // undirected, scan each pair only once.
EdgeWeight outWeight = outEdges[j].weight;
EdgeWeight walkThroughWeight = inWeight + outWeight;
if (distances[outNode] > walkThroughWeight) {
possibleShortcuts.push_back(make_pair(inNode, CHGraph::CH_Edge(outNode, v, walkThroughWeight)));
}
}
// Clean up the dijkstra structures otherwise the trash will manipulate the next inNode's dijkstra search.
for (unordered_set<NodeID>::iterator it = visited_set.begin(); it != visited_set.end(); ++it) {
NodeID cv = *it;
vis[cv] = false;
distances[cv] = INF_WEIGHT;
}
while (!pqueue.empty()) {
NodeID tmpv;
EdgeWeight tmpweight;
pqueue.extract_min(tmpv, tmpweight);
}
visited_set.clear();
}
// Clean the target table for the next contracted node.
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode >= v) continue; // Skip the nodes that have been already contracted.
hitTarget[outNode] = false;
}
}
// Append the shortcuts.
for (int i = 0; i < possibleShortcuts.size(); ++i) {
NodeID fromNode = possibleShortcuts[i].first;
NodeID toNode = possibleShortcuts[i].second.target;
NodeID level = possibleShortcuts[i].second.level;
EdgeWeight weight = possibleShortcuts[i].second.weight;
addShortcuts++;
addShortcuts++;
int fromAdjSize = chgraph.adj[fromNode].size();
bool skipfrom = false;
for (int j = fromAdjSize - 1; j + 1 > 0; --j) {
if (chgraph.adj[fromNode][j].target == toNode) {
if (weight > chgraph.adj[fromNode][j].weight) break;
chgraph.adj[fromNode][j].weight = weight;
chgraph.adj[fromNode][j].level = level;
skipfrom = true;
addShortcuts--;
break;
}
}
if (!skipfrom) {
chgraph.adj[fromNode].push_back(CHGraph::CH_Edge(toNode, level, weight));
}
int toAdjSize = chgraph.adj[toNode].size();
bool skipto = false;
for (int j = toAdjSize - 1; j + 1 > 0; --j) {
if (chgraph.adj[toNode][j].target == fromNode) {
if (weight > chgraph.adj[toNode][j].weight) break;
chgraph.adj[toNode][j].weight = weight;
chgraph.adj[toNode][j].level = level;
skipto = true;
addShortcuts--;
break;
}
}
if (!skipto)
chgraph.adj[toNode].push_back(CHGraph::CH_Edge(fromNode, level, weight));
}
addShortcuts -= chgraph.adj[v].size(); // Two times because it will appear in others' adj.
possibleShortcuts.clear();
return addShortcuts;
}
int witness_search_directed(NodeID v, CHGraph& chgraph, const int hopLimitsParameter, Ordering& orders, vector<bool>& vis, benchmark::heap<2, EdgeWeight, NodeID>& pqueue, unordered_set<NodeID>& visited_set, vector<EdgeWeight>& distances, vector<bool>& hitTarget) {
int addShortcuts = 0;
vector<CHGraph::CH_Edge>& inEdges = chgraph.r_adj[v];
vector<CHGraph::CH_Edge>& outEdges = chgraph.adj[v];
vector<pair<NodeID, CHGraph::CH_Edge> > possibleShortcuts;
// 1-hop witness search
if (hopLimitsParameter == 1) {
for (int i = 0; i < inEdges.size(); ++i) {
//if (inEdges[i].level == V) continue;
NodeID inNode = inEdges[i].target;
if (inNode >= v) continue; // Skip the nodes that have been already contracted.
EdgeWeight inWeight = inEdges[i].weight;
vector<CHGraph::CH_Edge>& outEdgesOfInNode = chgraph.adj[inNode];
for (int j = 0; j < outEdges.size(); ++j) {
//if (outEdges[j].level == V) continue;
NodeID outNode = outEdges[j].target;
if (outNode >= v) continue; // Skip the nodes that have been already contracted.
if (outNode == inNode) continue;
EdgeWeight outWeight = outEdges[j].weight;
EdgeWeight walkThroughWeight = inWeight + outWeight; // Distance for the path (inNode - v - outNode).
bool foundWitness = false;
for (int k = 0; k < outEdgesOfInNode.size(); ++k) {
NodeID outNeighborOfInNode = outEdgesOfInNode[k].target;
// if (outNeighborLevelOfInNode == V) continue;
if (outNeighborOfInNode >= v) continue; // Skip the ondes that have been already contracted.
if (outNeighborOfInNode == outNode) {
EdgeWeight outNeighborWeightOfInNode = outEdgesOfInNode[k].weight; // Distance for the direct path (inNode - outNode).
if (outNeighborWeightOfInNode <= walkThroughWeight) {
foundWitness = true;
//walkThroughWeight = outNeighborWeightOfInNode;
}
break;
}
}
if (foundWitness == false) {
possibleShortcuts.push_back(make_pair(inNode, CHGraph::CH_Edge(outNode, v, walkThroughWeight)));
}
}
}
}
// 2-hop witness search.
if (hopLimitsParameter == 2) {
// Init the many-to-many bucket.
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode >= v) continue; // Skip the nodes that have been already contracted.
EdgeWeight outWeight = outEdges[j].weight;
vector<CHGraph::CH_Edge>& inEdgesOfOutNode = chgraph.r_adj[outNode];
for (int k = 0; k < inEdgesOfOutNode.size(); ++k) {
NodeID inNeighborOfOutNode = inEdgesOfOutNode[k].target;
NodeID inNeighborLevelOfOutNode = inEdgesOfOutNode[k].level;
EdgeWeight inNeighborWeightOfOutNode = inEdgesOfOutNode[k].weight;
if (inNeighborOfOutNode >= v) continue; // Skip the nodes that have been already contracted. And skip the current contracted node (this is important).
mtmBucket[inNeighborOfOutNode].push_back(make_pair(outNode, inNeighborWeightOfOutNode));
}
}
// Finish the init.
for (int i = 0; i < inEdges.size(); ++i) {
NodeID inNode = inEdges[i].target;
if (inNode >= v) continue; // Skip the nodes that have bee n already contracted.
EdgeWeight inWeight = inEdges[i].weight;
vector<CHGraph::CH_Edge>& outEdgesOfInNode = chgraph.adj[inNode];
// One-hop witness search from the bucket of inNode.
Bucket& bucketInNode = mtmBucket[inNode];
for (int k = 0; k < bucketInNode.size(); ++k) {
NodeID target = bucketInNode[k].first;
EdgeWeight targetWeight = bucketInNode[k].second;
//if (target >= inNode) continue;
if (possibleWitness[target] > targetWeight)
possibleWitness[target] = targetWeight;
}
// Two-hop witness search from inNode.
// 1-hop forward search from inNode and scan the buckets of the reached nodes to find the length of 2-hop witness.
for (int k = 0; k < outEdgesOfInNode.size(); ++k) {
NodeID reachNode = outEdgesOfInNode[k].target;
if (reachNode >= v) continue;// Skip the nodes that have been already contracted.
NodeID reachNodeLevel = outEdgesOfInNode[k].level;
EdgeWeight reachNodeWeight = outEdgesOfInNode[k].weight;
Bucket& bucketReachNode = mtmBucket[reachNode];
for (int q = 0; q < bucketReachNode.size(); ++q) {
NodeID target = bucketReachNode[q].first;
// if (target >= inNode) continue;
EdgeWeight newTargetWeight = bucketReachNode[q].second + reachNodeWeight;
if (possibleWitness[target] > newTargetWeight)
possibleWitness[target] = newTargetWeight;
}
}
// Scan the outNode of v, to check whether shortcuts are needed for (inNode - v - outNode).
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode > v) {
possibleWitness[outNode] = INF_WEIGHT;
continue;
}
if (outNode == inNode) {
possibleWitness[outNode] = INF_WEIGHT;
continue;
}
EdgeWeight outWeight = outEdges[j].weight;
EdgeWeight witnessWeight = possibleWitness[outNode];
possibleWitness[outNode] = INF_WEIGHT;
EdgeWeight walkThroughWeight = inWeight + outWeight;
if (witnessWeight > walkThroughWeight)
possibleShortcuts.push_back(make_pair(inNode, CHGraph::CH_Edge(outNode, v, walkThroughWeight)));
}
}
// Cleanup the many-to-many bucket.
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode > v) continue;
EdgeWeight outWeight = outEdges[j].weight;
vector<CHGraph::CH_Edge>& inEdgesOfOutNode = chgraph.r_adj[outNode];
for (int k = 0; k < inEdgesOfOutNode.size(); ++k) {
NodeID inNeighborOfOutNode = inEdgesOfOutNode[k].target;
NodeID inNeighborLevelOfOutNode = inEdgesOfOutNode[k].level;
EdgeWeight inNeighborWeightOfOutNode = inEdgesOfOutNode[k].weight;
if (inNeighborOfOutNode >= v) continue;
if (!mtmBucket[inNeighborOfOutNode].empty())
mtmBucket[inNeighborOfOutNode].clear();
}
}
}
// Dijkstra Local Search.
if (hopLimitsParameter > 2) {
// Init the target table.
int noOfTarget = 0;
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode >= v) continue; // Skip the nodes that have been already contracted.
hitTarget[outNode] = true;
noOfTarget++;
}
// Loop the incoming node for witness search.
for (int i = 0; i < inEdges.size(); ++i) {
//if (inEdges[i].level == V) continue;
NodeID inNode = inEdges[i].target;
int visitedTarget = 0;
if (inNode >= v) continue; // Skip the nodes that have been already contracted.
EdgeWeight inWeight = inEdges[i].weight;
vector<CHGraph::CH_Edge>& outEdgesOfInNode = chgraph.adj[inNode];
pqueue.update(inNode, 0);
visited_set.insert(inNode);
distances[inNode] = 0;
while (!pqueue.empty()) {
NodeID u;
EdgeWeight u_d;
pqueue.extract_min(u, u_d);
vis[u] = true;
if (hitTarget[u] == true)
visitedTarget++;
if (visitedTarget == noOfTarget)
break;
for (int j = 0; j < chgraph.adj[u].size(); ++j) {
NodeID w = chgraph.adj[u][j].target;
EdgeWeight w_d = chgraph.adj[u][j].weight + u_d;
if (w >= v) continue; // Can not visit contracted nodes.
if (!vis[w]) {
if (distances[w] > w_d) {
pqueue.update(w, w_d);
distances[w] = w_d;
visited_set.insert(w);
}
}
}
}
// Test witness for all outNode.
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode >= v) continue;
if (outNode == inNode) continue;
EdgeWeight outWeight = outEdges[j].weight;
EdgeWeight walkThroughWeight = inWeight + outWeight;
if (distances[outNode] > walkThroughWeight) {
possibleShortcuts.push_back(make_pair(inNode, CHGraph::CH_Edge(outNode, v, walkThroughWeight)));
}
}
// Clean up the dijkstra structures otherwise the trash will manipulate the next inNode's dijkstra search.
for (unordered_set<NodeID>::iterator it = visited_set.begin(); it != visited_set.end(); ++it) {
NodeID cv = *it;
vis[cv] = false;
distances[cv] = INF_WEIGHT;
}
while (!pqueue.empty()) {
NodeID tmpv;
EdgeWeight tmpweight;
pqueue.extract_min(tmpv, tmpweight);
}
visited_set.clear();
}
// Clean the target table for the next contracted node.
for (int j = 0; j < outEdges.size(); ++j) {
NodeID outNode = outEdges[j].target;
if (outNode >= v) continue; // Skip the nodes that have been already contracted.
hitTarget[outNode] = false;
}
}
// Append the shortcuts.
for (int i = 0; i < possibleShortcuts.size(); ++i) {
addShortcuts += 2;
NodeID fromNode = possibleShortcuts[i].first;
NodeID toNode = possibleShortcuts[i].second.target;
NodeID level = possibleShortcuts[i].second.level;
EdgeWeight weight = possibleShortcuts[i].second.weight;
int fromAdjSize = chgraph.adj[fromNode].size();
bool skipfrom = false;
for (int j = fromAdjSize - 1; j + 1 > 0; --j) {
if (chgraph.adj[fromNode][j].target == toNode) {
if (weight > chgraph.adj[fromNode][j].weight) break;
chgraph.adj[fromNode][j].weight = weight;
chgraph.adj[fromNode][j].level = level;
skipfrom = true;
addShortcuts--;
break;
}
}
if (!skipfrom) {
chgraph.adj[fromNode].push_back(CHGraph::CH_Edge(toNode, level, weight));
}
int toAdjSize = chgraph.r_adj[toNode].size();
bool skipto = false;
for (int j = toAdjSize - 1; j + 1 > 0; --j) {
if (chgraph.r_adj[toNode][j].target == fromNode) {
if (weight > chgraph.r_adj[toNode][j].weight) break;
chgraph.r_adj[toNode][j].weight = weight;
chgraph.r_adj[toNode][j].level = level;
skipto = true;
addShortcuts--;
break;
}
}
if (!skipto)
chgraph.r_adj[toNode].push_back(CHGraph::CH_Edge(fromNode, level, weight));
}
addShortcuts -= 2 * chgraph.adj[v].size(); // 2 times because these out (in) edges will appear in others' in (out) edges.
addShortcuts -= 2 * chgraph.r_adj[v].size();
possibleShortcuts.clear();
return addShortcuts;
}
int build_shortcuts_dij(NodeID source, vector<vector<CHGraph::CH_Edge> >& adj, vector<bool>& vis, benchmark::heap<2, EdgeWeight, NodeID>& pqueue, unordered_set<NodeID>& visited_set, vector<EdgeWeight>& distances, vector<NodeID>& max_parents, vector<bool>& isNeighbor, vector<bool>& waitForPop, vector<vector<CHGraph::CH_Edge> >& shortcuts) {
// All dsitances[] is INF_WEIGHT, all vis[] is false, all max_parents[] is numOfVertices
if (source == 0) return 0; // No shortcut for the most important vertex
int uncover_count = source;
pqueue.update(source, 0);
distances[source] = 0;
//isNeighbor[source] = true;
visited_set.insert(source);
int in_que_cover_wait_for_pop = -1;
int in_que_cover = 0;
int in_que = 1;
/*if (source == 3)
cout << "one search" << endl;*/
//int sspace = 0;
while (!pqueue.empty()) {
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
in_que--;
vis[v] = true;
// sspace++;
// cout << "source: " << source << " visiting:" << v << " inque:" << in_que << " inque_cover:" << in_que_cover << " inque_cover_wait_for_pop:" << in_que_cover_wait_for_pop << endl;
if (max_parents[v] != numOfVertices) {
// If v is the first vertex having higher rank than source along its shortest path, add a shortcut.
if (max_parents[v] == v && isNeighbor[v] == false) {
shortcuts[source].push_back(CHGraph::CH_Edge(v, source, v_d));
in_que_cover_wait_for_pop--;
}
else if (max_parents[v] == v && isNeighbor[v] == true) {
in_que_cover_wait_for_pop--;
}
if (v < source)
uncover_count--;
if (uncover_count == 0) { // All vertices higher rank than source have been visited.
// cout << "good 1" << endl;
break;
}
in_que_cover--;
}
// if (in_que == in_que_cover && v != source && in_que != 0)// All elments in queue have been covered.
// continue;
//if (source == 3)
// cout << "v: " << v << endl
//if (in_que == in_que_cover && v != source && in_que_cover_wait_for_pop != -1 && in_que_cover_wait_for_pop != 0) {
// cout << "source: " << v << " inque:" << in_que << " inque_cover:" << in_que_cover << " inque_cover_wait_for_pop:" << in_que_cover_wait_for_pop << endl;
// // cout << "good 2" << endl;
// continue;
//};
for (int i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i].target;
EdgeWeight w_d = adj[v][i].weight + v_d;
if (!vis[w]) {
// When it is first inserted into the queue.
if (distances[w] == INF_WEIGHT && w_d < distances[w]) {
in_que++;
visited_set.insert(w);
}
if (distances[w] > w_d) {
distances[w] = w_d;
pqueue.update(w, w_d);
//if (source == 3)
// cout << v << "," << max_parents[v] << "," << w << "," << max_parents[w] << endl;
if (v == source)
isNeighbor[w] = true;
int uncover_flag = false;
if (max_parents[w] == numOfVertices)
uncover_flag = true;
// // w is the first vertex has higher rank than source.
// if (w < source && max_parents[v] == numOfVertices) {
// // Newly covered vertex in queue.
// /*if (max_parents[w] == numOfVertices) {
// in_que_cover++; */
// if(waitForPop[w] == false){
// if (in_que_cover_wait_for_pop == -1)
// in_que_cover_wait_for_pop = 0;
// in_que_cover_wait_for_pop++;
// waitForPop[w] = true;
// }
// max_parents[w] = w;
// }
//
// // w-source has already been hit by previous max_parents[v].
// if (max_parents[v] != numOfVertices) {
// // Newly covered vertex in queue.
///* if(max_parents[w] == numOfVertices)
// in_que_cover++;*/
// if (waitForPop[w] == true) {
// if (in_que_cover_wait_for_pop == -1)
// in_que_cover_wait_for_pop = 0;
// else
// in_que_cover_wait_for_pop--;
// waitForPop[w] = false;
// }
// max_parents[w] = max_parents[v];
// }
// // w has already been covered previously but it is not the shortest path. it has not been covered yet.
// if (w > source && max_parents[v] == numOfVertices && max_parents[w] != numOfVertices) {
// max_parents[w] = numOfVertices;
// in_que_cover--;
// }
// // w has not yet been covered. it is the first time it has been ocvered.
// if (uncover_flag == true && max_parents[w] != numOfVertices)
// in_que_cover++;
//
// The shorter path comes from u-x-v-w rather than u(v)-w.
if (isNeighbor[w] == true && v != source) {
isNeighbor[w] = false;
}
// w has not been covered yet.
if (max_parents[w] == numOfVertices) {
// w is the first vertex has higher rank than source.
if (w < source && max_parents[v] == numOfVertices) {
// Newly covered vertex in queue.
/*if (max_parents[w] == numOfVertices) {
in_que_cover++; */
if(waitForPop[w] == false){
if (in_que_cover_wait_for_pop == -1)
in_que_cover_wait_for_pop = 0;
in_que_cover_wait_for_pop++;
waitForPop[w] = true;
}
max_parents[w] = w;
}
// w-source has already been hit by previous max_parents[v].
if (max_parents[v] != numOfVertices) {
// Newly covered vertex in queue.
/* if(max_parents[w] == numOfVertices)
in_que_cover++;*/
if (waitForPop[w] == true) {
if (in_que_cover_wait_for_pop == -1)
in_que_cover_wait_for_pop = 0;
else
in_que_cover_wait_for_pop--;
waitForPop[w] = false;
}
max_parents[w] = max_parents[v];
}
// w has not yet been covered. it is the first time it has been ocvered.
if (uncover_flag == true && max_parents[w] != numOfVertices)
in_que_cover++;
}
else { // max_parents[w] != numOfVertices // w has been covered previously
// v has not been covered
if (max_parents[v] == numOfVertices) {
if (w < source) {//w is the first higher rank vertex in this shortest path
if (waitForPop[w] == false) {
if (in_que_cover_wait_for_pop == -1)
in_que_cover_wait_for_pop = 0;
in_que_cover_wait_for_pop++;
waitForPop[w] = true;
}
max_parents[w] = w;
}
else {//w has not been covered yet, remove its covered information
max_parents[w] = numOfVertices;
in_que_cover--;
}
}
// w has already been covered by v. if w is the first higher rank vertex previously, remove this information
if (max_parents[v] != numOfVertices) {
if (max_parents[w] == w) {
if (waitForPop[w] == true) {
if (in_que_cover_wait_for_pop == -1)
in_que_cover_wait_for_pop = 0;
else
in_que_cover_wait_for_pop--;
waitForPop[w] = false;
}
max_parents[w] = max_parents[v];
}
}
}
}
}
}
if (in_que == in_que_cover && v != source && in_que_cover_wait_for_pop != -1 && in_que_cover_wait_for_pop == 0) {
// cout << "source: " << v << " inque:" << in_que << " inque_cover:" << in_que_cover << " inque_cover_wait_for_pop:" << in_que_cover_wait_for_pop << endl;
// cout << "good 2" << endl;
break;
}
}
// cout << "search space:" << sspace << endl;
// Clean up the dijkstra structures otherwise the trash will manipulate the next inNode's dijkstra search.
for (unordered_set<NodeID>::iterator it = visited_set.begin(); it != visited_set.end(); ++it) {
NodeID cv = *it;
vis[cv] = false;
distances[cv] = INF_WEIGHT;
max_parents[cv] = numOfVertices;
isNeighbor[cv] = false;
pqueue.clear(cv);
waitForPop[cv] = false;
}
/* while (!pqueue.empty()) {
NodeID tmpv;
EdgeWeight tmpweight;
pqueue.extract_min(tmpv, tmpweight);
}*/
pqueue.clear_n();
visited_set.clear();
return 0;
}
//int build_shortcuts_dij(NodeID source, vector<vector<CHGraph::CH_Edge> >& adj, vector<bool>& vis, benchmark::heap<2, EdgeWeight, NodeID>& pqueue, unordered_set<NodeID>& visited_set, vector<EdgeWeight>& distances, vector<NodeID>& max_parents, vector<bool>& isNeighbor, vector<vector<CHGraph::CH_Edge> >& shortcuts) {
// int uncover_count = source;
// pqueue.update(source, 0);
// distances[source] = 0;
// //isNeighbor[source] = true;
// visited_set.insert(source);
// while (!pqueue.empty()) {
// NodeID v;
// EdgeWeight v_d;
// pqueue.extract_min(v, v_d);
// vis[v] = true;
// if (max_parents[v] != numOfVertices) { // Either one of the ancestors of v or v has higher rank than source, we can stop the search from here.
// if (max_parents[v] == v && isNeighbor[v] == false)
// shortcuts[source].push_back(CHGraph::CH_Edge(v, source, v_d));
// if (v < source)
// uncover_count--;
// if (uncover_count == 0) // All vertices higher rank than source have been covered.
// break;
// continue;
// }
// for (int i = 0; i < adj[v].size(); ++i) {
// NodeID w = adj[v][i].target;
// EdgeWeight w_d = adj[v][i].weight + v_d;
// if (!vis[w]) {
// if (distances[w] > w_d) {
// distances[w] = w_d;
// pqueue.update(w, w_d);
// visited_set.insert(w);
// if (v == source)
// isNeighbor[w] = true;
// // w is the first vertex has higher rank than source.
// if (w < source && max_parents[v] == numOfVertices)
// max_parents[w] = w;
// // w-source has already been hit by previous max_parents[v].
// if (max_parents[v] != numOfVertices)
// max_parents[w] = max_parents[v];
// // The shorter path comes from u-x-v-w rather than u(v)-w.
// if (isNeighbor[w] == true && v != source) {
// isNeighbor[w] = false;
// }
// /* if (max_parents[w] > w)
// max_parents[w] = w;
// if(max_parents[w] > max_parents[v])
// max_parents[w] = max_parents[v];*/
// }
// }
// }
// }
// // Clean up the dijkstra structures otherwise the trash will manipulate the next inNode's dijkstra search.
// for (unordered_set<NodeID>::iterator it = visited_set.begin(); it != visited_set.end(); ++it) {
// NodeID cv = *it;
// vis[cv] = false;
// distances[cv] = INF_WEIGHT;
// max_parents[cv] = numOfVertices;
// isNeighbor[cv] = false;
// pqueue.clear(cv);
// }
// /* while (!pqueue.empty()) {
// NodeID tmpv;
// EdgeWeight tmpweight;
// pqueue.extract_min(tmpv, tmpweight);
// }*/
// pqueue.clear_n();
// visited_set.clear();
// return 0;
//}
//int build_shortcuts_bfs(NodeID source, vector<vector<CHGraph::CH_Edge> >& adj, vector<bool>& vis, vector<NodeID>& max_parents, vector<bool>& isNeighbor, vector<vector<CHGraph::CH_Edge> >& shortcuts, vector<NodeID>& que) {
// int uncover_count = source;
// //vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
//
// NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
// que[que_h++] = source;
// vis[source] = true;
// que_t1 = que_h;
// for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
// for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
// NodeID v = que[que_i];
// if (max_parents[v] != numOfVertices) { // Either one of the ancestors of v or v has higher rank than source, we can stop the search from here.
//
// if (max_parents[v] == v && isNeighbor[v] == false)
// shortcuts[source].push_back(CHGraph::CH_Edge(v, source, d));
//
// if (v < source)
// uncover_count--;
// if (uncover_count == 0) { // All vertices higher rank than source have been covered.
// break;
// }
// continue;
// }
// for (size_t i = 0; i < adj[v].size(); ++i) {
// NodeID w = adj[v][i].target;
// if (!vis[w]) {
// vis[w] = true;
// if (v == source)
// isNeighbor[w] = true;
// // w is the first vertex has higher rank than source.
// if (w < source )//&& max_parents[v] == numOfVertices)
// max_parents[w] = w;
// //// w-source has already been hit by previous max_parents[v].
// //if (max_parents[v] != numOfVertices) {
// // max_parents[w] = max_parents[v];
// // continue;
// //}
//
// //// The shorter path comes from u-x-v-w rather than u(v)-w. *We wont have this case in unweigted graphs.
// //if (isNeighbor[w] == true && v != source) {
// // isNeighbor[w] = false;
// //}
// que[que_h++] = w;
// }
// }
// pruned:
// {}
// }
// que_t0 = que_t1;
// que_t1 = que_h;
// }
// for (size_t i = 0; i < que_h; ++i) {
// vis[que[i]] = false;
// max_parents[que[i]] = numOfVertices;
// isNeighbor[que[i]] = false;
// }
//}
int build_shortcuts_bfs(NodeID source, vector<vector<CHGraph::CH_Edge> >& adj, vector<bool>& vis, vector<NodeID>& max_parents, vector<bool>& isNeighbor, vector<vector<CHGraph::CH_Edge> >& shortcuts, vector<NodeID>& que) {
int uncover_count = source;
//vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
NodeID que_t0 = 0, que_t1 = 0, que_h = 0;
que[que_h++] = source;
vis[source] = true;
que_t1 = que_h;
int in_que = 1;
int in_que_cover = 0;
int in_que_wait_for_pop = -1;
for (EdgeWeight d = 0; que_t0 < que_h; d = d + 1) {
for (NodeID que_i = que_t0; que_i < que_t1; ++que_i) {
NodeID v = que[que_i];
in_que--;
if (max_parents[v] != numOfVertices) { // Either one of the ancestors of v or v has higher rank than source, we can stop the search from here.
if (max_parents[v] == v && isNeighbor[v] == false) {
shortcuts[source].push_back(CHGraph::CH_Edge(v, source, d));
in_que_wait_for_pop--;
}
if(max_parents[v] == v && isNeighbor[v] == true)
in_que_wait_for_pop--;
if (v < source)
uncover_count--;
if (uncover_count == 0) { // All vertices higher rank than source have been covered.
goto jumpout;
}
in_que_cover--;
}
for (size_t i = 0; i < adj[v].size(); ++i) {
NodeID w = adj[v][i].target;
if (!vis[w]) {
vis[w] = true;
in_que++;
if (v == source)
isNeighbor[w] = true;
// w is the first vertex has higher rank than source.
if (w < source && max_parents[v] == numOfVertices) {//&& max_parents[v] == numOfVertices)
max_parents[w] = w;
if (in_que_wait_for_pop == -1)
in_que_wait_for_pop = 0;
in_que_wait_for_pop++;
in_que_cover++;
}
if (max_parents[v] != numOfVertices) {
in_que_cover++;
max_parents[w] = max_parents[v];
}
//// w-source has already been hit by previous max_parents[v].
//if (max_parents[v] != numOfVertices) {
// max_parents[w] = max_parents[v];
// continue;
//}
//// The shorter path comes from u-x-v-w rather than u(v)-w. *We wont have this case in unweigted graphs.
//if (isNeighbor[w] == true && v != source) {
// isNeighbor[w] = false;
//}
que[que_h++] = w;
}
}
if (in_que == in_que_cover && in_que_wait_for_pop == 0) {
goto jumpout;
}
pruned:
{}
}
que_t0 = que_t1;
que_t1 = que_h;
}
jumpout:
{}
for (size_t i = 0; i < que_h; ++i) {
vis[que[i]] = false;
max_parents[que[i]] = numOfVertices;
isNeighbor[que[i]] = false;
}
}
void labeling(CHGraph &chgraph, Ordering &orders) {
for (int i = 0; i < numOfVertices; ++i) {
if(chgraph.adj[i].size() != 0)
sort(chgraph.adj[i].begin(), chgraph.adj[i].end());
if (DIRECTED_FLAG == true) {
if (chgraph.r_adj[i].size() != 0)
sort(chgraph.r_adj[i].begin(), chgraph.r_adj[i].end());
}
}
vector<index_t>& index_ = labels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(),
vector<EdgeWeight>()));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(),
vector<EdgeWeight>()));
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT);
set<NodeID> appendCandidate;
// vector<CHGraph::CH_Edge>& inEdges = chgraph.r_adj[v];
//vector<CHGraph::CH_Edge>& outEdges = chgraph.adj[v];
// Start to process every nodes.
for (NodeID v = 0; v < numOfVertices; ++v) {
vector<CHGraph::CH_Edge>& adj_v = chgraph.adj[v];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
if (DIRECTED_FLAG == false) {
//for (int i = 0; i < tmp_idx_v.first.size() - 1; ++i)
// dst_r[tmp_idx_v.first[i]] = tmp_idx_v.second[i];
// Search all the neighrbor u of v.
for (int i = 0; i < adj_v.size(); ++i) {
NodeID u = adj_v[i].target;
NodeID level = adj_v[i].level;
if (u >= v ) continue;
EdgeWeight weight = adj_v[i].weight;
// Check all the existing labels w in the labels of u.
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_u = tmp_idx[u];
for (int j = 0; j < tmp_idx_u.first.size(); ++j) {
NodeID w = tmp_idx_u.first[j];
EdgeWeight vuw_distance = tmp_idx_u.second[j] + weight; // Distance from v to u to w.
// Check whether the path (v->u->w) should be added into the labels of v. We prune it if the existing labels of v and w can answer the distance directly.
//pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_w = tmp_idx[w];
//for (int k = 0; k < tmp_idx_w.first.size(); ++k) {
// NodeID labelOfW = tmp_idx_w.first[k];
// EdgeWeight distanceToIt = tmp_idx_w.second[k] + dst_r[labelOfW];
// // Prune this label, we do not add (w, vuw_distance) to the label set of v.
// if (distanceToIt <= vuw_distance) goto pruning;
//}
if (dst_r[w] > vuw_distance) {
if (dst_r[w] == INF_WEIGHT) appendCandidate.insert(w);
dst_r[w] = vuw_distance;
}
//pruning: {}
}
}
// Post prune the candidate by running query test, start from the max rank candidate. It takes O(|M|^2) time, |M| is the average label size.
for (set<NodeID>::iterator it = appendCandidate.begin(); it != appendCandidate.end(); ++it) {
NodeID w = *it;
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_w = tmp_idx[w];
for (int k = 0; k < tmp_idx_w.first.size(); ++k) {
NodeID labelOfW = tmp_idx_w.first[k];
EdgeWeight distanceToIt = tmp_idx_w.second[k] + dst_r[labelOfW];
if (dst_r[w] >= distanceToIt) {
if (labelOfW != w)
dst_r[w] = INF_WEIGHT; // We prune it because the this path has been hit by another higher rank vertex labelOfW.
break;
}
}
}
for (set<NodeID>::iterator it = appendCandidate.begin(); it != appendCandidate.end(); ++it) {
NodeID w = *it;
if (dst_r[w] == INF_WEIGHT) continue;
tmp_idx_v.first.push_back(w);
tmp_idx_v.second.push_back(dst_r[w]);
dst_r[w] = INF_WEIGHT;
}
appendCandidate.clear();
tmp_idx_v.first.push_back(v);
tmp_idx_v.second.push_back(0);
}
}
if (DIRECTED_FLAG == false) {
for (size_t v = 0; v < numOfVertices; ++v) {
tmp_idx[v].first.push_back(numOfVertices);
tmp_idx[v].second.push_back(INF_WEIGHT);
NodeID k = tmp_idx[v].first.size();
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
// tmp_idx[v].first.clear();
vector<NodeID>().swap(tmp_idx[v].first);
vector<EdgeWeight>().swap(tmp_idx[v].second);
// tmp_idx[v].second.clear();
}
}
}
void td_labeling(CHGraph &chgraph, Ordering &orders) {
for (int i = 0; i < numOfVertices; ++i) {
if (chgraph.adj[i].size() != 0)
sort(chgraph.adj[i].rbegin(), chgraph.adj[i].rend());
if (chgraph.r_adj[i].size() != 0)
sort(chgraph.r_adj[i].rbegin(), chgraph.r_adj[i].rend());
}
vector<index_t>& index_ = labels.index_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
/* vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(),
vector<EdgeWeight>()));*/
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(),
vector<EdgeWeight>()));
//vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT);
set<NodeID> appendCandidate;
// vector<CHGraph::CH_Edge>& inEdges = chgraph.r_adj[v];
//vector<CHGraph::CH_Edge>& outEdges = chgraph.adj[v];
//vector<index_t>& index_ = labels.index_;
//vector<NodeID> &inv = orders.inv;
//vector<NodeID> &rank = orders.rank;
// vector<vector<NodeID> > &adj = wgraph.adj;
// vector<vector<EdgeWeight> > &adj_weight = wgraph.adj_weight;
//vector<EdgeID>& vertices = wgraph.vertices;
//vector<NodeEdgeWeightPair>& edges = wgraph.edges;
vector<bool> usd(numOfVertices, false);
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(1, numOfVertices),
vector<EdgeWeight>(1, INF_WEIGHT)));
vector<bool> vis(numOfVertices);
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
queue<NodeID> visited_que;
vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
long pop = 0;
double hsize = 0;
for (size_t r = 0; r < numOfVertices; ++r) {
if (usd[r]) continue;
const pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_r = tmp_idx[r];
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i) {
dst_r[tmp_idx_r.first[i]] = tmp_idx_r.second[i];
}
pqueue.update(r, 0);
//vis[r] = true;
long max_heap_size = 0;
long heap_size = 1;
while (!pqueue.empty()) {
pop++;
heap_size--;
NodeID v;
EdgeWeight v_d;
pqueue.extract_min(v, v_d);
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
vis[v] = true;
visited_que.push(v);
vector<CHGraph::CH_Edge>& adj_v = chgraph.adj[v];
if (usd[v]) continue;
for (size_t i = 0; i < tmp_idx_v.first.size(); ++i) {
NodeID w = tmp_idx_v.first[i];
EdgeWeight td = tmp_idx_v.second[i] + dst_r[w];
if (td <= v_d) {
// pruning_power[w]++;
goto pruned;
}
}
// Traverse
tmp_idx_v.first.back() = r;
tmp_idx_v.second.back() = v_d;
tmp_idx_v.first.push_back(numOfVertices);
tmp_idx_v.second.push_back(INF_WEIGHT);
iteration_generated[r]++;
// for (size_t i = 0; i < adj[v].size(); ++i) {
// NodeID w = adj[v][i];
// EdgeWeight w_d = adj_weight[v][i] + v_d;
//for (EdgeID eid = vertices[v]; eid < vertices[v + 1]; ++eid) {
// NodeID w = edges[eid].first;
// EdgeWeight w_d = edges[eid].second + v_d;
for (int i = 0; i < adj_v.size(); ++i) {
NodeID w = adj_v[i].target;
EdgeWeight w_d = adj_v[i].weight + v_d;
if (w < v) break; //Only the neighbors with lower ranks will be visited.
if (!vis[w]) {
if (distances[w] == INF_WEIGHT) {
heap_size++;
if (max_heap_size < heap_size)
max_heap_size = heap_size;
}
if (distances[w] > w_d) {
pqueue.update(w, w_d);
distances[w] = w_d;
}
}
}
pruned:
{}
}
hsize = hsize + max_heap_size;
while (!visited_que.empty()) {
NodeID vis_v = visited_que.front();
visited_que.pop();
vis[vis_v] = false;
distances[vis_v] = INF_WEIGHT;
pqueue.clear(vis_v);
}
pqueue.clear_n();
for (size_t i = 0; i < tmp_idx_r.first.size(); ++i)
dst_r[tmp_idx_r.first[i]] = INF_WEIGHT;
usd[r] = true;
}
cout << "total pop:" << pop << endl;
cout << "average max heap size " << (double)hsize / (double)numOfVertices << endl;
for (size_t v = 0; v < numOfVertices; ++v) {
NodeID k = tmp_idx[v].first.size();
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
}
}
void labeling_directed(CHGraph &chgraph, Ordering &orders) {
for (int i = 0; i < numOfVertices; ++i) {
/* cout << i << endl;
if(i == 5073)
cout << chgraph.adj[i].size() << endl;
for (int j = 0; j < chgraph.adj[i].size(); ++j) {
if (i == 5073)
cout << "," << j;
NodeID hh = chgraph.adj[i][j].target;
}
cout << "test ok " << chgraph.adj[i].size();
for (int j = 0; j < chgraph.r_adj[i].size(); ++j) {
NodeID hh = chgraph.r_adj[i][j].target;
}*/
sort(chgraph.adj[i].begin(), chgraph.adj[i].end());
sort(chgraph.r_adj[i].begin(), chgraph.r_adj[i].end());
//cout << "," << chgraph.r_adj[i].size() << endl;
}
vector<index_t>& index_ = dlabels.index_;
vector<index_t>& bindex_ = dlabels.bindex_;
vector<NodeID> &inv = orders.inv;
vector<NodeID> &rank = orders.rank;
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
tmp_idx(numOfVertices, make_pair(vector<NodeID>(),
vector<EdgeWeight>()));
vector<pair<vector<NodeID>, vector<EdgeWeight> > >
r_tmp_idx(numOfVertices, make_pair(vector<NodeID>(),
vector<EdgeWeight>()));
vector<EdgeWeight> dst_r(numOfVertices + 1, INF_WEIGHT);
vector<EdgeWeight> r_dst_r(numOfVertices + 1, INF_WEIGHT);
set<NodeID> appendCandidate;
// The main process:
// Forward search: fetch necessary outLabel of the forward adj. (all outgoing labels must pass out neighbors)
// Backward search: fetch necessary inLabel of the backward adj.(all incoming labels must pass in neighbors)
// Start to process every nodes.
for (NodeID v = 0; v < numOfVertices; ++v) {
// Forward search.
{
vector<CHGraph::CH_Edge>& adj_v = chgraph.adj[v];
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_v = tmp_idx[v];
// Search all the neighrbor u of v.
for (int i = 0; i < adj_v.size(); ++i) {
NodeID u = adj_v[i].target;
NodeID level = adj_v[i].level;
if (u >= v) continue;
EdgeWeight weight = adj_v[i].weight;
// Check all the existing labels w in the labels of u.
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_u = tmp_idx[u];
for (int j = 0; j < tmp_idx_u.first.size(); ++j) {
NodeID w = tmp_idx_u.first[j];
EdgeWeight vuw_distance = tmp_idx_u.second[j] + weight; // Distance from v to u to w.
if (dst_r[w] > vuw_distance) {
if (dst_r[w] == INF_WEIGHT) appendCandidate.insert(w);
dst_r[w] = vuw_distance;
}
}
}
// Post prune the candidate by running query test, start from the max rank candidate. It takes O(|M|^2) time, |M| is the average label size.
for (set<NodeID>::iterator it = appendCandidate.begin(); it != appendCandidate.end(); ++it) {
NodeID w = *it;
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_w = r_tmp_idx[w];
for (int k = 0; k < r_tmp_idx_w.first.size(); ++k) {
NodeID labelOfW = r_tmp_idx_w.first[k];
EdgeWeight distanceToIt = r_tmp_idx_w.second[k] + dst_r[labelOfW];
if (dst_r[w] >= distanceToIt) {
if (labelOfW != w)
dst_r[w] = INF_WEIGHT; // We prune it because the this path has been hit by another higher rank vertex labelOfW.
break;
}
}
}
for (set<NodeID>::iterator it = appendCandidate.begin(); it != appendCandidate.end(); ++it) {
NodeID w = *it;
if (dst_r[w] == INF_WEIGHT) continue;
tmp_idx_v.first.push_back(w);
tmp_idx_v.second.push_back(dst_r[w]);
dst_r[w] = INF_WEIGHT;
}
appendCandidate.clear();
tmp_idx_v.first.push_back(v);
tmp_idx_v.second.push_back(0);
}
// Backward search.
{
vector<CHGraph::CH_Edge>& r_adj_v = chgraph.r_adj[v];
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_v = r_tmp_idx[v];
// Search all the neighrbor u of v.
for (int i = 0; i < r_adj_v.size(); ++i) {
NodeID u = r_adj_v[i].target;
NodeID level = r_adj_v[i].level;
if (u >= v) continue;
EdgeWeight weight = r_adj_v[i].weight;
// Check all the existing labels w in the labels of u.
pair<vector<NodeID>, vector<EdgeWeight> > &r_tmp_idx_u = r_tmp_idx[u];
for (int j = 0; j < r_tmp_idx_u.first.size(); ++j) {
NodeID w = r_tmp_idx_u.first[j];
EdgeWeight wuv_distance = r_tmp_idx_u.second[j] + weight; // Distance from w to u to v.
if (r_dst_r[w] > wuv_distance) {
if (r_dst_r[w] == INF_WEIGHT) appendCandidate.insert(w);
r_dst_r[w] = wuv_distance;
}
//pruning: {}
}
}
// Post prune the candidate by running query test, start from the max rank candidate. It takes O(|M|^2) time, |M| is the average label size.
for (set<NodeID>::iterator it = appendCandidate.begin(); it != appendCandidate.end(); ++it) {
NodeID w = *it;
pair<vector<NodeID>, vector<EdgeWeight> > &tmp_idx_w = tmp_idx[w];
for (int k = 0; k < tmp_idx_w.first.size(); ++k) {
NodeID labelOfW = tmp_idx_w.first[k];
EdgeWeight distanceToIt = tmp_idx_w.second[k] + r_dst_r[labelOfW];
if (r_dst_r[w] >= distanceToIt) {
if (labelOfW != w)
r_dst_r[w] = INF_WEIGHT; // We prune it because the this path has been hit by another higher rank vertex labelOfW.
break;
}
}
}
for (set<NodeID>::iterator it = appendCandidate.begin(); it != appendCandidate.end(); ++it) {
NodeID w = *it;
if (r_dst_r[w] == INF_WEIGHT) continue;
r_tmp_idx_v.first.push_back(w);
r_tmp_idx_v.second.push_back(r_dst_r[w]);
r_dst_r[w] = INF_WEIGHT;
}
appendCandidate.clear();
r_tmp_idx_v.first.push_back(v);
r_tmp_idx_v.second.push_back(0);
}
}
int added = 0;
for (size_t v = 0; v < numOfVertices; ++v ){
tmp_idx[v].first.push_back(numOfVertices);
tmp_idx[v].second.push_back(INF_WEIGHT);
NodeID k = tmp_idx[v].first.size();
index_[inv[v]].spt_v.resize(k);
index_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_v[i] = tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) index_[inv[v]].spt_d[i] = tmp_idx[v].second[i];
tmp_idx[v].first.clear();
tmp_idx[v].second.clear();
added += k;
r_tmp_idx[v].first.push_back(numOfVertices);
r_tmp_idx[v].second.push_back(INF_WEIGHT);
k = r_tmp_idx[v].first.size();
bindex_[inv[v]].spt_v.resize(k);
bindex_[inv[v]].spt_d.resize(k);
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_v[i] = r_tmp_idx[v].first[i];
for (NodeID i = 0; i < k; ++i) bindex_[inv[v]].spt_d[i] = r_tmp_idx[v].second[i];
r_tmp_idx[v].first.clear();
r_tmp_idx[v].second.clear();
added += k;
}
cout << added << endl;
}
Bottomup(CHGraph &chgraph, Ordering &orders, double& time_contracting, const double SWITCH_DEGREE_PARA, const int HOP_LIMIT_PARA) {
iteration_generated.resize(numOfVertices);
benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
unordered_set<NodeID> visited_set;
vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
vector<bool> hitTarget(numOfVertices);// false
vector<bool> vis(numOfVertices);
contracted.resize(numOfVertices, false);
possibleWitness.resize(numOfVertices, INF_WEIGHT);
mtmBucket.resize(numOfVertices);
// Temporary structures for Dijkstra searches.
NodeID remainNode = numOfVertices;
int currentEdges = relabelByOrder(chgraph, orders);
int hopLimitsParameter = 1;
double currentDegree = (double)currentEdges / (double)numOfVertices;
time_contracting = GetCurrentTimeSec();
// A main loop to pick all vertices from the least to the most important ones.
for (NodeID v = numOfVertices - 1; v > 0; --v) {
if(v % (numOfVertices /10) == 0)
cout << "Building shortcuts for " << v << "th vertices("<< orders.inv[v] <<"). Total shortcuts ratio so far " << currentEdges / numOfEdges << " time:" << GetCurrentTimeSec() - time_contracting << "s" << endl;
contracted[v] = true;
double time_thisround = GetCurrentTimeSec();
int addShortcuts = witness_search(v, chgraph, hopLimitsParameter, orders, vis, pqueue, visited_set, distances, hitTarget);
iteration_generated[v] = GetCurrentTimeSec() - time_thisround;
currentEdges += addShortcuts;
currentDegree = (double)currentEdges / (double)v;
if (HOP_LIMIT_PARA == 2 || HOP_LIMIT_PARA == 1 || HOP_LIMIT_PARA == 5) {
hopLimitsParameter = HOP_LIMIT_PARA;
continue;
}
if (currentDegree > 3.3 && currentDegree <= SWITCH_DEGREE_PARA && hopLimitsParameter != 2) {
hopLimitsParameter = 2;
cout << "At Vertex " << v << ". Switch to 2-hop limit with average degree:" << currentDegree << " #edge:" << currentEdges << endl;
}else if (currentDegree <= 3.3 && hopLimitsParameter !=1) {
hopLimitsParameter = 1;
cout << "At Vertex " << v << ". Switch to 1-hop limit with average degree:" << currentDegree << " #edge:" << currentEdges << endl;
}else if(hopLimitsParameter != 5 && currentDegree > SWITCH_DEGREE_PARA){
hopLimitsParameter = 5;
cout << "At Vertex " << v << ". Switch to multi-hop limit with average degree:" << currentDegree << " #edge:" << currentEdges << endl;
}
}
time_contracting = GetCurrentTimeSec() - time_contracting;
cout << "Spent " << time_contracting << " s on creating shortcuts..." << endl;
cout << "Start to label vertices..." << endl;
labeling(chgraph, orders);
}
Bottomup(CHGraph &chgraph, Ordering &orders, bool directed_flag, double& time_contracting, const double SWITCH_DEGREE_PARA, const int HOP_LIMIT_PARA) {
benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
unordered_set<NodeID> visited_set;
vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
vector<bool> hitTarget(numOfVertices);// false
vector<bool> vis(numOfVertices);
iteration_generated.resize(numOfVertices);
contracted.resize(numOfVertices, false);
possibleWitness.resize(numOfVertices, INF_WEIGHT);
mtmBucket.resize(numOfVertices);
// Temporary structures for Dijkstra searches.
NodeID remainNode = numOfVertices;
int currentEdges = relabelByOrder(chgraph, orders);
int hopLimitsParameter = 1;
double currentDegree = (double)currentEdges / (double)numOfVertices;
time_contracting = GetCurrentTimeSec();
// A main loop to pick all vertices from the least to the most important ones.
for (NodeID v = numOfVertices - 1; v > 0; --v) {
if (v % (numOfVertices / 10) == 0)
cout << "Building shortcuts for " << v << "th vertices(" << orders.inv[v] << "). Total shortcuts ratio so far " << currentEdges / numOfEdges << " time:" << GetCurrentTimeSec()- time_contracting << "s" << endl;
contracted[v] = true;
double time_thisround = GetCurrentTimeSec();
int addShortcuts = witness_search_directed(v, chgraph, hopLimitsParameter, orders, vis, pqueue, visited_set, distances, hitTarget);
iteration_generated[v] = GetCurrentTimeSec() - time_thisround;
currentEdges += addShortcuts;
currentDegree = (double)currentEdges / (double)v;
if (HOP_LIMIT_PARA == 2 || HOP_LIMIT_PARA == 1 || HOP_LIMIT_PARA == 5) {
hopLimitsParameter = HOP_LIMIT_PARA;
continue;
}
if (currentDegree > 3.3 && currentDegree <= SWITCH_DEGREE_PARA && hopLimitsParameter != 2) {
hopLimitsParameter = 2;
cout << "At Vertex " << v << ". Switch to 2-hop limit with average degree:" << currentDegree << " #edge:" << currentEdges << endl;
}
else if (currentDegree <= 3.3 && hopLimitsParameter != 1) {
hopLimitsParameter = 1;
cout << "At Vertex " << v << ". Switch to 1-hop limit with average degree:" << currentDegree << " #edge:" << currentEdges << endl;
}
else if (hopLimitsParameter != 5 && currentDegree > SWITCH_DEGREE_PARA) {
hopLimitsParameter = 5;
cout << "At Vertex " << v << ". Switch to multi-hop limit with average degree:" << currentDegree << " #edge:" << currentEdges << endl;
}
}
time_contracting = GetCurrentTimeSec() - time_contracting;
cout << "Spent " << time_contracting << " s on creating shortcuts..." << endl;
cout << "Start to label vertices..." << endl;
labeling_directed(chgraph, orders);
}
Bottomup(CHGraph &chgraph, Ordering &orders, double& time_contracting) {
vector<vector<CHGraph::CH_Edge> > shortcuts(numOfVertices);
vector<vector<CHGraph::CH_Edge> > r_shortcuts(numOfVertices);
//benchmark::heap<2, EdgeWeight, NodeID> pqueue(numOfVertices);
//unordered_set<NodeID> visited_set;
//vector<EdgeWeight> distances(numOfVertices, INF_WEIGHT);
//vector<bool> hitTarget(numOfVertices);// false
//vector<bool> vis(numOfVertices);
//iteration_generated.resize(numOfVertices);
//vector<NodeID> max_parents(numOfVertices, numOfVertices);
//vector<bool> isNeighbor(numOfVertices, false);
//vector<bool> waitForPop(numOfVertices, false);
//
//vector<NodeID> que(numOfVertices);
relabelByOrder(chgraph, orders);
long total_shortcut = 0;
time_contracting = GetCurrentTimeSec();
double time_shortcuting = GetCurrentTimeSec();
int num_threads = 10;
omp_set_num_threads(num_threads);
vector<vector<vector<CHGraph::CH_Edge> > > shortcuts_omp(num_threads, vector<vector<CHGraph::CH_Edge> >(numOfVertices));
vector<vector<vector<CHGraph::CH_Edge> > > r_shortcuts_omp(num_threads, vector<vector<CHGraph::CH_Edge> >(numOfVertices));
vector<benchmark::heap<2, EdgeWeight, NodeID> > pqueue(num_threads, benchmark::heap<2, EdgeWeight, NodeID>(numOfVertices) );
vector<unordered_set<NodeID> > visited_set(num_threads);
vector<vector<EdgeWeight> > distances(num_threads, vector<EdgeWeight>(numOfVertices, INF_WEIGHT));
vector<vector<bool> > hitTarget(num_threads, vector<bool>(numOfVertices) );// false
vector<vector<bool> > vis(num_threads, vector<bool>(numOfVertices));
iteration_generated.resize(numOfVertices);
vector<vector<NodeID> > max_parents(num_threads, vector<NodeID>(numOfVertices, numOfVertices));
vector<vector<bool> > isNeighbor(num_threads, vector<bool>(numOfVertices, false));
vector<vector<bool> > waitForPop(num_threads, vector<bool>(numOfVertices, false));
vector<vector<NodeID> > que(num_threads, vector<NodeID>(numOfVertices));
#pragma omp parallel for schedule(dynamic)
for (NodeID v = numOfVertices - 1; v > 0; --v) {
if (WEIGHTED_FLAG == true) {
//build_shortcuts_dij(v, chgraph.adj, vis, pqueue, visited_set, distances, max_parents, isNeighbor, shortcuts);
build_shortcuts_dij(v, chgraph.adj, vis[omp_get_thread_num()], pqueue[omp_get_thread_num()], visited_set[omp_get_thread_num()], distances[omp_get_thread_num()], max_parents[omp_get_thread_num()], isNeighbor[omp_get_thread_num()], waitForPop[omp_get_thread_num()], shortcuts_omp[omp_get_thread_num()]);
if (DIRECTED_FLAG == true)
// build_shortcuts_dij(v, chgraph.r_adj, vis, pqueue, visited_set, distances, max_parents, isNeighbor, r_shortcuts);
build_shortcuts_dij(v, chgraph.r_adj, vis[omp_get_thread_num()], pqueue[omp_get_thread_num()], visited_set[omp_get_thread_num()], distances[omp_get_thread_num()], max_parents[omp_get_thread_num()], isNeighbor[omp_get_thread_num()], waitForPop[omp_get_thread_num()], r_shortcuts_omp[omp_get_thread_num()]);
}
else {
build_shortcuts_bfs(v, chgraph.adj, vis[omp_get_thread_num()], max_parents[omp_get_thread_num()], isNeighbor[omp_get_thread_num()], shortcuts_omp[omp_get_thread_num()], que[omp_get_thread_num()]);
// build_shortcuts_bfs(v, chgraph.adj, vis[omp_get_thread_num()], max_parents[omp_get_thread_num()], isNeighbor[omp_get_thread_num()], shortcuts_omp[omp_get_thread_num()], que[omp_get_thread_num()]);
if (DIRECTED_FLAG == true)
build_shortcuts_bfs(v, chgraph.r_adj, vis[omp_get_thread_num()], max_parents[omp_get_thread_num()], isNeighbor[omp_get_thread_num()], r_shortcuts_omp[omp_get_thread_num()], que[omp_get_thread_num()]);
//build_shortcuts_bfs(v, chgraph.r_adj, vis[omp_get_thread_num()], max_parents[omp_get_thread_num()], isNeighbor[omp_get_thread_num()], r_shortcuts_omp[omp_get_thread_num()], que[omp_get_thread_num()]);
}
}
for (int t = 0; t < num_threads; ++t) {
for (int v = 0; v < numOfVertices; ++v) {
for (int i = 0; i < shortcuts_omp[t][v].size(); ++i) {
shortcuts[v].push_back(shortcuts_omp[t][v][i]);
}
for (int i = 0; i < r_shortcuts_omp[t][v].size(); ++i) {
r_shortcuts[v].push_back(r_shortcuts_omp[t][v][i]);
}
}
}
//for (NodeID v = numOfVertices - 1; v > 0; --v) {
// if (WEIGHTED_FLAG == true) {
// //build_shortcuts_dij(v, chgraph.adj, vis, pqueue, visited_set, distances, max_parents, isNeighbor, shortcuts);
// build_shortcuts_dij(v, chgraph.adj, vis, pqueue, visited_set, distances, max_parents, isNeighbor, waitForPop, shortcuts);
// if (DIRECTED_FLAG == true)
// // build_shortcuts_dij(v, chgraph.r_adj, vis, pqueue, visited_set, distances, max_parents, isNeighbor, r_shortcuts);
// build_shortcuts_dij(v, chgraph.r_adj, vis, pqueue, visited_set, distances, max_parents, isNeighbor, waitForPop, r_shortcuts);
// } else {
// build_shortcuts_bfs(v, chgraph.adj, vis, max_parents, isNeighbor, shortcuts, que);
// if (DIRECTED_FLAG == true)
// build_shortcuts_bfs(v, chgraph.r_adj, vis, max_parents, isNeighbor, r_shortcuts, que);
// }
//}
double time_searching = GetCurrentTimeSec() - time_contracting;
cout << "Spent " << time_searching << " s on searching shortcuts..." << endl;
if (DIRECTED_FLAG == false)
total_shortcut += process_shortcuts(chgraph, shortcuts);
else
total_shortcut += process_shortcuts_directed(chgraph, shortcuts, r_shortcuts);
time_contracting = GetCurrentTimeSec() - time_contracting - time_searching;
cout << "Spent " << time_contracting << " s on processing shortcuts..." << endl;
cout << "Start to label vertices..." << endl;
cout << total_shortcut << " shortcuts in total." << endl;
time_shortcuting = GetCurrentTimeSec() - time_shortcuting;
time_contracting = time_shortcuting;
if (DIRECTED_FLAG == false)
td_labeling(chgraph, orders);
//labeling(chgraph, orders);
else
labeling_directed(chgraph, orders);
}
Bottomup(CHGraph &chgraph, Ordering &orders, double& time_contracting, bool CH_ORDER_FLAGS) {
relabelByOrder(chgraph, orders);
labeling(chgraph, orders);
}
long process_shortcuts(CHGraph& chgraph, vector<vector<CHGraph::CH_Edge> > shortcuts) {
vector<vector<bool> > add_out(numOfVertices);
vector<vector<bool> > add_in(numOfVertices);
long added_shortcuts = 0;
// Test whether shortcut can replace the original edges.
for (NodeID v = 0; v < numOfVertices; ++v) {
vector<CHGraph::CH_Edge>& shortcuts_v = shortcuts[v];
vector<bool>& add_out_v = add_out[v];
vector<bool>& add_in_v = add_in[v];
add_out_v.resize(shortcuts_v.size(), true);
add_in_v.resize(shortcuts_v.size(), true);
for (int i = 0; i < shortcuts_v.size(); ++i) {
NodeID w = shortcuts_v[i].target;
vector<CHGraph::CH_Edge>::iterator pos = lower_bound(chgraph.adj[v].begin(), chgraph.adj[v].end(), shortcuts_v[i]);
if (pos != chgraph.adj[v].end() && (*pos).target == shortcuts_v[i].target) {
if ((*pos).weight > shortcuts_v[i].weight)
(*pos).weight = shortcuts_v[i].weight;
add_out_v[i] = false;
}
CHGraph::CH_Edge dummy(v, 0, 0);
pos = lower_bound(chgraph.adj[w].begin(), chgraph.adj[w].end(), dummy);
if (pos != chgraph.adj[w].end() && (*pos).target == v) {
if ((*pos).weight > shortcuts_v[i].weight)
(*pos).weight = shortcuts_v[i].weight;
add_in_v[i] = false;
}
}
}
// Append the actual shortcuts.
for (NodeID v = 0; v < numOfVertices; ++v) {
vector<CHGraph::CH_Edge>& shortcuts_v = shortcuts[v];
vector<bool>& add_out_v = add_out[v];
vector<bool>& add_in_v = add_in[v];
for (int i = 0; i < shortcuts_v.size(); ++i) {
NodeID w = shortcuts_v[i].target;
NodeID level = shortcuts_v[i].level;
EdgeWeight weight = shortcuts_v[i].weight;
if (add_out_v[i] == true)
chgraph.adj[v].push_back(CHGraph::CH_Edge(w, level, weight));
if (add_in_v[i] == true)
chgraph.adj[w].push_back(CHGraph::CH_Edge(v, level, weight));
if (add_out_v[i]==false && add_in_v[i]==false)
added_shortcuts--;
added_shortcuts++;
}
}
return added_shortcuts;
}
long process_shortcuts_directed(CHGraph& chgraph, vector<vector<CHGraph::CH_Edge> > shortcuts, vector<vector<CHGraph::CH_Edge> > r_shortcuts) {
vector<vector<bool> > add_out(numOfVertices);
vector<vector<bool> > add_in(numOfVertices);
vector<vector<bool> > r_add_out(numOfVertices);
vector<vector<bool> > r_add_in(numOfVertices);
long added_shortcuts = 0;
// Test whether shortcut can replace the original edges.
for (NodeID v = 0; v < numOfVertices; ++v) {
{// Forward shortcut from (v->w), so add this shortcut into adj[v] and r_adj[w].
vector<CHGraph::CH_Edge>& shortcuts_v = shortcuts[v];
vector<bool>& add_out_v = add_out[v];
vector<bool>& add_in_v = add_in[v];
add_out_v.resize(shortcuts_v.size(), true);
add_in_v.resize(shortcuts_v.size(), true);
for (int i = 0; i < shortcuts_v.size(); ++i) {
NodeID w = shortcuts_v[i].target;
vector<CHGraph::CH_Edge>::iterator pos = lower_bound(chgraph.adj[v].begin(), chgraph.adj[v].end(), shortcuts_v[i]);
if (pos != chgraph.adj[v].end() && (*pos).target == shortcuts_v[i].target) {
if ((*pos).weight > shortcuts_v[i].weight)
(*pos).weight = shortcuts_v[i].weight;
add_out_v[i] = false;
}
CHGraph::CH_Edge dummy(v, 0, 0);
pos = lower_bound(chgraph.r_adj[w].begin(), chgraph.r_adj[w].end(), dummy);
if (pos != chgraph.r_adj[w].end() && (*pos).target == v) {
if ((*pos).weight > shortcuts_v[i].weight)
(*pos).weight = shortcuts_v[i].weight;
add_in_v[i] = false;
}
}
}
{// Backward shortcuts, add (w->v) into adj[w] and r_adj[v].
vector<CHGraph::CH_Edge>& r_shortcuts_v = r_shortcuts[v];
vector<bool>& r_add_out_v = r_add_out[v];
vector<bool>& r_add_in_v = r_add_in[v];
r_add_out_v.resize(r_shortcuts_v.size(), true);
r_add_in_v.resize(r_shortcuts_v.size(), true);
for (int i = 0; i < r_shortcuts_v.size(); ++i) {
NodeID w = r_shortcuts_v[i].target;
vector<CHGraph::CH_Edge>::iterator pos = lower_bound(chgraph.r_adj[v].begin(), chgraph.r_adj[v].end(), r_shortcuts_v[i]);
if (pos != chgraph.r_adj[v].end() && (*pos).target == r_shortcuts_v[i].target) {
if ((*pos).weight > r_shortcuts_v[i].weight)
(*pos).weight = r_shortcuts_v[i].weight;
r_add_in_v[i] = false;
}
CHGraph::CH_Edge dummy(v, 0, 0);
pos = lower_bound(chgraph.adj[w].begin(), chgraph.adj[w].end(), dummy);
if (pos != chgraph.adj[w].end() && (*pos).target == v) {
if ((*pos).weight > r_shortcuts_v[i].weight)
(*pos).weight = r_shortcuts_v[i].weight;
r_add_out_v[i] = false;
}
}
}
}
// Append the actual shortcuts.
for (NodeID v = 0; v < numOfVertices; ++v) {
{//Forward shortcuts, add (v->w) to adj[v] and r_adj[w].
vector<CHGraph::CH_Edge>& shortcuts_v = shortcuts[v];
vector<bool>& add_out_v = add_out[v];
vector<bool>& add_in_v = add_in[v];
for (int i = 0; i < shortcuts_v.size(); ++i) {
NodeID w = shortcuts_v[i].target;
NodeID level = shortcuts_v[i].level;
EdgeWeight weight = shortcuts_v[i].weight;
if (add_out_v[i] == true) {
chgraph.adj[v].push_back(CHGraph::CH_Edge(w, level, weight));
// cout << v << "," << w << "," << weight << endl;
}
if (add_in_v[i] == true) {
chgraph.r_adj[w].push_back(CHGraph::CH_Edge(v, level, weight));
// cout << w << "," << v << "," << weight << endl;
}
if (add_out_v[i] == false && add_in_v[i] == false)
added_shortcuts--;
added_shortcuts++;
}
}
{// Backward shortcuts, add (w->v) to adj[w] and r_adj[v].
vector<CHGraph::CH_Edge>& r_shortcuts_v = r_shortcuts[v];
vector<bool>& r_add_out_v = r_add_out[v];
vector<bool>& r_add_in_v = r_add_in[v];
for (int i = 0; i < r_shortcuts_v.size(); ++i) {
NodeID w = r_shortcuts_v[i].target;
NodeID level = r_shortcuts_v[i].level;
EdgeWeight weight = r_shortcuts_v[i].weight;
if (r_add_out_v[i] == true) {
chgraph.adj[w].push_back(CHGraph::CH_Edge(v, level, weight));
// cout << w << "," << v << "," << weight << endl;
}
if (r_add_in_v[i] == true) {
chgraph.r_adj[v].push_back(CHGraph::CH_Edge(w, level, weight));
// cout << v << "," << w << "," << weight << endl;
}
if (r_add_out_v[i] == false && r_add_in_v[i] == false)
added_shortcuts--;
added_shortcuts++;
}
}
}
return added_shortcuts;
}
};
#endif
|
Parser.h | //===--- Parser.h - C Language Parser ---------------------------*- 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 Parser interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_PARSE_PARSER_H
#define LLVM_CLANG_PARSE_PARSER_H
#include "clang/AST/Availability.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/OperatorPrecedence.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Lex/CodeCompletionHandler.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/LoopHint.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SaveAndRestore.h"
#include <memory>
#include <stack>
namespace clang {
class PragmaHandler;
class Scope;
class BalancedDelimiterTracker;
class CorrectionCandidateCallback;
class DeclGroupRef;
class DiagnosticBuilder;
class Parser;
class ParsingDeclRAIIObject;
class ParsingDeclSpec;
class ParsingDeclarator;
class ParsingFieldDeclarator;
class ColonProtectionRAIIObject;
class InMessageExpressionRAIIObject;
class PoisonSEHIdentifiersRAIIObject;
class OMPClause;
class ObjCTypeParamList;
class ObjCTypeParameter;
/// Parser - This implements a parser for the C family of languages. After
/// parsing units of the grammar, productions are invoked to handle whatever has
/// been read.
///
class Parser : public CodeCompletionHandler {
friend class ColonProtectionRAIIObject;
friend class InMessageExpressionRAIIObject;
friend class PoisonSEHIdentifiersRAIIObject;
friend class ObjCDeclContextSwitch;
friend class ParenBraceBracketBalancer;
friend class BalancedDelimiterTracker;
Preprocessor &PP;
/// Tok - The current token we are peeking ahead. All parsing methods assume
/// that this is valid.
Token Tok;
// PrevTokLocation - The location of the token we previously
// consumed. This token is used for diagnostics where we expected to
// see a token following another token (e.g., the ';' at the end of
// a statement).
SourceLocation PrevTokLocation;
unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
unsigned short MisplacedModuleBeginCount = 0;
/// Actions - These are the callbacks we invoke as we parse various constructs
/// in the file.
Sema &Actions;
DiagnosticsEngine &Diags;
/// ScopeCache - Cache scopes to reduce malloc traffic.
enum { ScopeCacheSize = 16 };
unsigned NumCachedScopes;
Scope *ScopeCache[ScopeCacheSize];
/// Identifiers used for SEH handling in Borland. These are only
/// allowed in particular circumstances
// __except block
IdentifierInfo *Ident__exception_code,
*Ident___exception_code,
*Ident_GetExceptionCode;
// __except filter expression
IdentifierInfo *Ident__exception_info,
*Ident___exception_info,
*Ident_GetExceptionInfo;
// __finally
IdentifierInfo *Ident__abnormal_termination,
*Ident___abnormal_termination,
*Ident_AbnormalTermination;
/// Contextual keywords for Microsoft extensions.
IdentifierInfo *Ident__except;
mutable IdentifierInfo *Ident_sealed;
/// Ident_super - IdentifierInfo for "super", to support fast
/// comparison.
IdentifierInfo *Ident_super;
/// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
/// "bool" fast comparison. Only present if AltiVec or ZVector are enabled.
IdentifierInfo *Ident_vector;
IdentifierInfo *Ident_bool;
/// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
/// Only present if AltiVec enabled.
IdentifierInfo *Ident_pixel;
/// Objective-C contextual keywords.
mutable IdentifierInfo *Ident_instancetype;
/// Identifier for "introduced".
IdentifierInfo *Ident_introduced;
/// Identifier for "deprecated".
IdentifierInfo *Ident_deprecated;
/// Identifier for "obsoleted".
IdentifierInfo *Ident_obsoleted;
/// Identifier for "unavailable".
IdentifierInfo *Ident_unavailable;
/// Identifier for "message".
IdentifierInfo *Ident_message;
/// Identifier for "strict".
IdentifierInfo *Ident_strict;
/// Identifier for "replacement".
IdentifierInfo *Ident_replacement;
/// Identifiers used by the 'external_source_symbol' attribute.
IdentifierInfo *Ident_language, *Ident_defined_in,
*Ident_generated_declaration;
/// C++0x contextual keywords.
mutable IdentifierInfo *Ident_final;
mutable IdentifierInfo *Ident_GNU_final;
mutable IdentifierInfo *Ident_override;
// C++ type trait keywords that can be reverted to identifiers and still be
// used as type traits.
llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
std::unique_ptr<PragmaHandler> AlignHandler;
std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
std::unique_ptr<PragmaHandler> OptionsHandler;
std::unique_ptr<PragmaHandler> PackHandler;
std::unique_ptr<PragmaHandler> MSStructHandler;
std::unique_ptr<PragmaHandler> UnusedHandler;
std::unique_ptr<PragmaHandler> WeakHandler;
std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
std::unique_ptr<PragmaHandler> FPContractHandler;
std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
std::unique_ptr<PragmaHandler> OpenMPHandler;
std::unique_ptr<PragmaHandler> PCSectionHandler;
std::unique_ptr<PragmaHandler> MSCommentHandler;
std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
std::unique_ptr<PragmaHandler> MSPointersToMembers;
std::unique_ptr<PragmaHandler> MSVtorDisp;
std::unique_ptr<PragmaHandler> MSInitSeg;
std::unique_ptr<PragmaHandler> MSDataSeg;
std::unique_ptr<PragmaHandler> MSBSSSeg;
std::unique_ptr<PragmaHandler> MSConstSeg;
std::unique_ptr<PragmaHandler> MSCodeSeg;
std::unique_ptr<PragmaHandler> MSSection;
std::unique_ptr<PragmaHandler> MSRuntimeChecks;
std::unique_ptr<PragmaHandler> MSIntrinsic;
std::unique_ptr<PragmaHandler> MSOptimize;
std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
std::unique_ptr<PragmaHandler> OptimizeHandler;
std::unique_ptr<PragmaHandler> LoopHintHandler;
std::unique_ptr<PragmaHandler> UnrollHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
std::unique_ptr<PragmaHandler> FPHandler;
std::unique_ptr<PragmaHandler> STDCFENVHandler;
std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
std::unique_ptr<PragmaHandler> STDCUnknownHandler;
std::unique_ptr<PragmaHandler> AttributePragmaHandler;
std::unique_ptr<CommentHandler> CommentSemaHandler;
/// Whether the '>' token acts as an operator or not. This will be
/// true except when we are parsing an expression within a C++
/// template argument list, where the '>' closes the template
/// argument list.
bool GreaterThanIsOperator;
/// ColonIsSacred - When this is false, we aggressively try to recover from
/// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
/// safe in case statements and a few other things. This is managed by the
/// ColonProtectionRAIIObject RAII object.
bool ColonIsSacred;
/// When true, we are directly inside an Objective-C message
/// send expression.
///
/// This is managed by the \c InMessageExpressionRAIIObject class, and
/// should not be set directly.
bool InMessageExpression;
/// The "depth" of the template parameters currently being parsed.
unsigned TemplateParameterDepth;
/// RAII class that manages the template parameter depth.
class TemplateParameterDepthRAII {
unsigned &Depth;
unsigned AddedLevels;
public:
explicit TemplateParameterDepthRAII(unsigned &Depth)
: Depth(Depth), AddedLevels(0) {}
~TemplateParameterDepthRAII() {
Depth -= AddedLevels;
}
void operator++() {
++Depth;
++AddedLevels;
}
void addDepth(unsigned D) {
Depth += D;
AddedLevels += D;
}
unsigned getDepth() const { return Depth; }
};
/// Factory object for creating AttributeList objects.
AttributeFactory AttrFactory;
/// Gathers and cleans up TemplateIdAnnotations when parsing of a
/// top-level declaration is finished.
SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
/// Identifiers which have been declared within a tentative parse.
SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
IdentifierInfo *getSEHExceptKeyword();
/// True if we are within an Objective-C container while parsing C-like decls.
///
/// This is necessary because Sema thinks we have left the container
/// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
/// be NULL.
bool ParsingInObjCContainer;
/// Whether to skip parsing of function bodies.
///
/// This option can be used, for example, to speed up searches for
/// declarations/definitions when indexing.
bool SkipFunctionBodies;
/// The location of the expression statement that is being parsed right now.
/// Used to determine if an expression that is being parsed is a statement or
/// just a regular sub-expression.
SourceLocation ExprStatementTokLoc;
public:
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
~Parser() override;
const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
Preprocessor &getPreprocessor() const { return PP; }
Sema &getActions() const { return Actions; }
AttributeFactory &getAttrFactory() { return AttrFactory; }
const Token &getCurToken() const { return Tok; }
Scope *getCurScope() const { return Actions.getCurScope(); }
void incrementMSManglingNumber() const {
return Actions.incrementMSManglingNumber();
}
Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
// Type forwarding. All of these are statically 'void*', but they may all be
// different actual classes based on the actions in place.
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
typedef Sema::FullExprArg FullExprArg;
// Parsing methods.
/// Initialize - Warm up the parser.
///
void Initialize();
/// Parse the first top-level declaration in a translation unit.
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
/// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
/// the EOF was encountered.
bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
bool ParseTopLevelDecl() {
DeclGroupPtrTy Result;
return ParseTopLevelDecl(Result);
}
/// ConsumeToken - Consume the current 'peek token' and lex the next one.
/// This does not work with special tokens: string literals, code completion,
/// annotation tokens and balanced tokens must be handled using the specific
/// consume methods.
/// Returns the location of the consumed token.
SourceLocation ConsumeToken() {
assert(!isTokenSpecial() &&
"Should consume special tokens with Consume*Token");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
bool TryConsumeToken(tok::TokenKind Expected) {
if (Tok.isNot(Expected))
return false;
assert(!isTokenSpecial() &&
"Should consume special tokens with Consume*Token");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return true;
}
bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
if (!TryConsumeToken(Expected))
return false;
Loc = PrevTokLocation;
return true;
}
/// ConsumeAnyToken - Dispatch to the right Consume* method based on the
/// current token type. This should only be used in cases where the type of
/// the token really isn't known, e.g. in error recovery.
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
if (isTokenParen())
return ConsumeParen();
if (isTokenBracket())
return ConsumeBracket();
if (isTokenBrace())
return ConsumeBrace();
if (isTokenStringLiteral())
return ConsumeStringToken();
if (Tok.is(tok::code_completion))
return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
: handleUnexpectedCodeCompletionToken();
if (Tok.isAnnotation())
return ConsumeAnnotationToken();
return ConsumeToken();
}
SourceLocation getEndOfPreviousToken() {
return PP.getLocForEndOfToken(PrevTokLocation);
}
/// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
/// to the given nullability kind.
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
return Actions.getNullabilityKeyword(nullability);
}
private:
//===--------------------------------------------------------------------===//
// Low-Level token peeking and consumption methods.
//
/// isTokenParen - Return true if the cur token is '(' or ')'.
bool isTokenParen() const {
return Tok.isOneOf(tok::l_paren, tok::r_paren);
}
/// isTokenBracket - Return true if the cur token is '[' or ']'.
bool isTokenBracket() const {
return Tok.isOneOf(tok::l_square, tok::r_square);
}
/// isTokenBrace - Return true if the cur token is '{' or '}'.
bool isTokenBrace() const {
return Tok.isOneOf(tok::l_brace, tok::r_brace);
}
/// isTokenStringLiteral - True if this token is a string-literal.
bool isTokenStringLiteral() const {
return tok::isStringLiteral(Tok.getKind());
}
/// isTokenSpecial - True if this token requires special consumption methods.
bool isTokenSpecial() const {
return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
}
/// Returns true if the current token is '=' or is a type of '='.
/// For typos, give a fixit to '='
bool isTokenEqualOrEqualTypo();
/// Return the current token to the token stream and make the given
/// token the current token.
void UnconsumeToken(Token &Consumed) {
Token Next = Tok;
PP.EnterToken(Consumed);
PP.Lex(Tok);
PP.EnterToken(Next);
}
SourceLocation ConsumeAnnotationToken() {
assert(Tok.isAnnotation() && "wrong consume method");
SourceLocation Loc = Tok.getLocation();
PrevTokLocation = Tok.getAnnotationEndLoc();
PP.Lex(Tok);
return Loc;
}
/// ConsumeParen - This consume method keeps the paren count up-to-date.
///
SourceLocation ConsumeParen() {
assert(isTokenParen() && "wrong consume method");
if (Tok.getKind() == tok::l_paren)
++ParenCount;
else if (ParenCount)
--ParenCount; // Don't let unbalanced )'s drive the count negative.
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBracket - This consume method keeps the bracket count up-to-date.
///
SourceLocation ConsumeBracket() {
assert(isTokenBracket() && "wrong consume method");
if (Tok.getKind() == tok::l_square)
++BracketCount;
else if (BracketCount)
--BracketCount; // Don't let unbalanced ]'s drive the count negative.
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBrace - This consume method keeps the brace count up-to-date.
///
SourceLocation ConsumeBrace() {
assert(isTokenBrace() && "wrong consume method");
if (Tok.getKind() == tok::l_brace)
++BraceCount;
else if (BraceCount)
--BraceCount; // Don't let unbalanced }'s drive the count negative.
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeStringToken - Consume the current 'peek token', lexing a new one
/// and returning the token kind. This method is specific to strings, as it
/// handles string literal concatenation, as per C99 5.1.1.2, translation
/// phase #6.
SourceLocation ConsumeStringToken() {
assert(isTokenStringLiteral() &&
"Should only consume string literals with this method");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// Consume the current code-completion token.
///
/// This routine can be called to consume the code-completion token and
/// continue processing in special cases where \c cutOffParsing() isn't
/// desired, such as token caching or completion with lookahead.
SourceLocation ConsumeCodeCompletionToken() {
assert(Tok.is(tok::code_completion));
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
///\ brief When we are consuming a code-completion token without having
/// matched specific position in the grammar, provide code-completion results
/// based on context.
///
/// \returns the source location of the code-completion token.
SourceLocation handleUnexpectedCodeCompletionToken();
/// Abruptly cut off parsing; mainly used when we have reached the
/// code-completion point.
void cutOffParsing() {
if (PP.isCodeCompletionEnabled())
PP.setCodeCompletionReached();
// Cut off parsing by acting as if we reached the end-of-file.
Tok.setKind(tok::eof);
}
/// Determine if we're at the end of the file or at a transition
/// between modules.
bool isEofOrEom() {
tok::TokenKind Kind = Tok.getKind();
return Kind == tok::eof || Kind == tok::annot_module_begin ||
Kind == tok::annot_module_end || Kind == tok::annot_module_include;
}
/// Checks if the \p Level is valid for use in a fold expression.
bool isFoldOperator(prec::Level Level) const;
/// Checks if the \p Kind is a valid operator for fold expressions.
bool isFoldOperator(tok::TokenKind Kind) const;
/// Initialize all pragma handlers.
void initializePragmaHandlers();
/// Destroy and reset all pragma handlers.
void resetPragmaHandlers();
/// Handle the annotation token produced for #pragma unused(...)
void HandlePragmaUnused();
/// Handle the annotation token produced for
/// #pragma GCC visibility...
void HandlePragmaVisibility();
/// Handle the annotation token produced for
/// #pragma pack...
void HandlePragmaPack();
/// Handle the annotation token produced for
/// #pragma ms_struct...
void HandlePragmaMSStruct();
/// Handle the annotation token produced for
/// #pragma comment...
void HandlePragmaMSComment();
void HandlePragmaMSPointersToMembers();
void HandlePragmaMSVtorDisp();
void HandlePragmaMSPragma();
bool HandlePragmaMSSection(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSSegment(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSInitSeg(StringRef PragmaName,
SourceLocation PragmaLocation);
/// Handle the annotation token produced for
/// #pragma align...
void HandlePragmaAlign();
/// Handle the annotation token produced for
/// #pragma clang __debug dump...
void HandlePragmaDump();
/// Handle the annotation token produced for
/// #pragma weak id...
void HandlePragmaWeak();
/// Handle the annotation token produced for
/// #pragma weak id = id...
void HandlePragmaWeakAlias();
/// Handle the annotation token produced for
/// #pragma redefine_extname...
void HandlePragmaRedefineExtname();
/// Handle the annotation token produced for
/// #pragma STDC FP_CONTRACT...
void HandlePragmaFPContract();
/// Handle the annotation token produced for
/// #pragma clang fp ...
void HandlePragmaFP();
/// Handle the annotation token produced for
/// #pragma OPENCL EXTENSION...
void HandlePragmaOpenCLExtension();
/// Handle the annotation token produced for
/// #pragma clang __debug captured
StmtResult HandlePragmaCaptured();
/// Handle the annotation token produced for
/// #pragma clang loop and #pragma unroll.
bool HandlePragmaLoopHint(LoopHint &Hint);
bool ParsePragmaAttributeSubjectMatchRuleSet(
attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
void HandlePragmaAttribute();
/// GetLookAheadToken - This peeks ahead N tokens and returns that token
/// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
/// returns the token after Tok, etc.
///
/// Note that this differs from the Preprocessor's LookAhead method, because
/// the Parser always has one token lexed that the preprocessor doesn't.
///
const Token &GetLookAheadToken(unsigned N) {
if (N == 0 || Tok.is(tok::eof)) return Tok;
return PP.LookAhead(N-1);
}
public:
/// NextToken - This peeks ahead one token and returns it without
/// consuming it.
const Token &NextToken() {
return PP.LookAhead(0);
}
/// getTypeAnnotation - Read a parsed type out of an annotation token.
static ParsedType getTypeAnnotation(const Token &Tok) {
return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
}
private:
static void setTypeAnnotation(Token &Tok, ParsedType T) {
Tok.setAnnotationValue(T.getAsOpaquePtr());
}
/// Read an already-translated primary expression out of an annotation
/// token.
static ExprResult getExprAnnotation(const Token &Tok) {
return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
}
/// Set the primary expression corresponding to the given annotation
/// token.
static void setExprAnnotation(Token &Tok, ExprResult ER) {
Tok.setAnnotationValue(ER.getAsOpaquePointer());
}
public:
// If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
// find a type name by attempting typo correction.
bool TryAnnotateTypeOrScopeToken();
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
bool IsNewScope);
bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
private:
enum AnnotatedNameKind {
/// Annotation has failed and emitted an error.
ANK_Error,
/// The identifier is a tentatively-declared name.
ANK_TentativeDecl,
/// The identifier is a template name. FIXME: Add an annotation for that.
ANK_TemplateName,
/// The identifier can't be resolved.
ANK_Unresolved,
/// Annotation was successful.
ANK_Success
};
AnnotatedNameKind
TryAnnotateName(bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
/// Push a tok::annot_cxxscope token onto the token stream.
void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
/// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
/// replacing them with the non-context-sensitive keywords. This returns
/// true if the token was replaced.
bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid) {
if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
return false;
if (Tok.getIdentifierInfo() != Ident_vector &&
Tok.getIdentifierInfo() != Ident_bool &&
(!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
return false;
return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
}
/// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
/// identifier token, replacing it with the non-context-sensitive __vector.
/// This returns true if the token was replaced.
bool TryAltiVecVectorToken() {
if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
Tok.getIdentifierInfo() != Ident_vector) return false;
return TryAltiVecVectorTokenOutOfLine();
}
bool TryAltiVecVectorTokenOutOfLine();
bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid);
/// Returns true if the current token is the identifier 'instancetype'.
///
/// Should only be used in Objective-C language modes.
bool isObjCInstancetype() {
assert(getLangOpts().ObjC1);
if (Tok.isAnnotation())
return false;
if (!Ident_instancetype)
Ident_instancetype = PP.getIdentifierInfo("instancetype");
return Tok.getIdentifierInfo() == Ident_instancetype;
}
/// TryKeywordIdentFallback - For compatibility with system headers using
/// keywords as identifiers, attempt to convert the current token to an
/// identifier and optionally disable the keyword for the remainder of the
/// translation unit. This returns false if the token was not replaced,
/// otherwise emits a diagnostic and returns true.
bool TryKeywordIdentFallback(bool DisableKeyword);
/// Get the TemplateIdAnnotation from the token.
TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
/// TentativeParsingAction - An object that is used as a kind of "tentative
/// parsing transaction". It gets instantiated to mark the token position and
/// after the token consumption is done, Commit() or Revert() is called to
/// either "commit the consumed tokens" or revert to the previously marked
/// token position. Example:
///
/// TentativeParsingAction TPA(*this);
/// ConsumeToken();
/// ....
/// TPA.Revert();
///
class TentativeParsingAction {
Parser &P;
Token PrevTok;
size_t PrevTentativelyDeclaredIdentifierCount;
unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
bool isActive;
public:
explicit TentativeParsingAction(Parser& p) : P(p) {
PrevTok = P.Tok;
PrevTentativelyDeclaredIdentifierCount =
P.TentativelyDeclaredIdentifiers.size();
PrevParenCount = P.ParenCount;
PrevBracketCount = P.BracketCount;
PrevBraceCount = P.BraceCount;
P.PP.EnableBacktrackAtThisPos();
isActive = true;
}
void Commit() {
assert(isActive && "Parsing action was finished!");
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.PP.CommitBacktrackedTokens();
isActive = false;
}
void Revert() {
assert(isActive && "Parsing action was finished!");
P.PP.Backtrack();
P.Tok = PrevTok;
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.ParenCount = PrevParenCount;
P.BracketCount = PrevBracketCount;
P.BraceCount = PrevBraceCount;
isActive = false;
}
~TentativeParsingAction() {
assert(!isActive && "Forgot to call Commit or Revert!");
}
};
/// A TentativeParsingAction that automatically reverts in its destructor.
/// Useful for disambiguation parses that will always be reverted.
class RevertingTentativeParsingAction
: private Parser::TentativeParsingAction {
public:
RevertingTentativeParsingAction(Parser &P)
: Parser::TentativeParsingAction(P) {}
~RevertingTentativeParsingAction() { Revert(); }
};
class UnannotatedTentativeParsingAction;
/// ObjCDeclContextSwitch - An object used to switch context from
/// an objective-c decl context to its enclosing decl context and
/// back.
class ObjCDeclContextSwitch {
Parser &P;
Decl *DC;
SaveAndRestore<bool> WithinObjCContainer;
public:
explicit ObjCDeclContextSwitch(Parser &p)
: P(p), DC(p.getObjCDeclContext()),
WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
if (DC)
P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
}
~ObjCDeclContextSwitch() {
if (DC)
P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
}
};
/// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
/// input. If so, it is consumed and false is returned.
///
/// If a trivial punctuator misspelling is encountered, a FixIt error
/// diagnostic is issued and false is returned after recovery.
///
/// If the input is malformed, this emits the specified diagnostic and true is
/// returned.
bool ExpectAndConsume(tok::TokenKind ExpectedTok,
unsigned Diag = diag::err_expected,
StringRef DiagMsg = "");
/// The parser expects a semicolon and, if present, will consume it.
///
/// If the next token is not a semicolon, this emits the specified diagnostic,
/// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
/// to the semicolon, consumes that extra token.
bool ExpectAndConsumeSemi(unsigned DiagID);
/// The kind of extra semi diagnostic to emit.
enum ExtraSemiKind {
OutsideFunction = 0,
InsideStruct = 1,
InstanceVariableList = 2,
AfterMemberFunctionDefinition = 3
};
/// Consume any extra semi-colons until the end of the line.
void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
/// Return false if the next token is an identifier. An 'expected identifier'
/// error is emitted otherwise.
///
/// The parser tries to recover from the error by checking if the next token
/// is a C++ keyword when parsing Objective-C++. Return false if the recovery
/// was successful.
bool expectIdentifier();
public:
//===--------------------------------------------------------------------===//
// Scope manipulation
/// ParseScope - Introduces a new scope for parsing. The kind of
/// scope is determined by ScopeFlags. Objects of this type should
/// be created on the stack to coincide with the position where the
/// parser enters the new scope, and this object's constructor will
/// create that new scope. Similarly, once the object is destroyed
/// the parser will exit the scope.
class ParseScope {
Parser *Self;
ParseScope(const ParseScope &) = delete;
void operator=(const ParseScope &) = delete;
public:
// ParseScope - Construct a new object to manage a scope in the
// parser Self where the new Scope is created with the flags
// ScopeFlags, but only when we aren't about to enter a compound statement.
ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
bool BeforeCompoundStmt = false)
: Self(Self) {
if (EnteredScope && !BeforeCompoundStmt)
Self->EnterScope(ScopeFlags);
else {
if (BeforeCompoundStmt)
Self->incrementMSManglingNumber();
this->Self = nullptr;
}
}
// Exit - Exit the scope associated with this object now, rather
// than waiting until the object is destroyed.
void Exit() {
if (Self) {
Self->ExitScope();
Self = nullptr;
}
}
~ParseScope() {
Exit();
}
};
/// EnterScope - Start a new scope.
void EnterScope(unsigned ScopeFlags);
/// ExitScope - Pop a scope off the scope stack.
void ExitScope();
private:
/// RAII object used to modify the scope flags for the current scope.
class ParseScopeFlags {
Scope *CurScope;
unsigned OldFlags;
ParseScopeFlags(const ParseScopeFlags &) = delete;
void operator=(const ParseScopeFlags &) = delete;
public:
ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
~ParseScopeFlags();
};
//===--------------------------------------------------------------------===//
// Diagnostic Emission and Error recovery.
public:
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
DiagnosticBuilder Diag(unsigned DiagID) {
return Diag(Tok, DiagID);
}
private:
void SuggestParentheses(SourceLocation Loc, unsigned DK,
SourceRange ParenRange);
void CheckNestedObjCContexts(SourceLocation AtLoc);
public:
/// Control flags for SkipUntil functions.
enum SkipUntilFlags {
StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
/// Stop skipping at specified token, but don't skip the token itself
StopBeforeMatch = 1 << 1,
StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
};
friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
SkipUntilFlags R) {
return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
static_cast<unsigned>(R));
}
/// SkipUntil - Read tokens until we get to the specified token, then consume
/// it (unless StopBeforeMatch is specified). Because we cannot guarantee
/// that the token will ever occur, this skips to the next token, or to some
/// likely good stopping point. If Flags has StopAtSemi flag, skipping will
/// stop at a ';' character.
///
/// If SkipUntil finds the specified token, it returns true, otherwise it
/// returns false.
bool SkipUntil(tok::TokenKind T,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
return SkipUntil(llvm::makeArrayRef(T), Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2, T3};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
/// SkipMalformedDecl - Read tokens until we get to some likely good stopping
/// point for skipping past a simple-declaration.
void SkipMalformedDecl();
private:
//===--------------------------------------------------------------------===//
// Lexing and parsing of C++ inline methods.
struct ParsingClass;
/// [class.mem]p1: "... the class is regarded as complete within
/// - function bodies
/// - default arguments
/// - exception-specifications (TODO: C++0x)
/// - and brace-or-equal-initializers for non-static data members
/// (including such things in nested classes)."
/// LateParsedDeclarations build the tree of those elements so they can
/// be parsed after parsing the top-level class.
class LateParsedDeclaration {
public:
virtual ~LateParsedDeclaration();
virtual void ParseLexedMethodDeclarations();
virtual void ParseLexedMemberInitializers();
virtual void ParseLexedMethodDefs();
virtual void ParseLexedAttributes();
};
/// Inner node of the LateParsedDeclaration tree that parses
/// all its members recursively.
class LateParsedClass : public LateParsedDeclaration {
public:
LateParsedClass(Parser *P, ParsingClass *C);
~LateParsedClass() override;
void ParseLexedMethodDeclarations() override;
void ParseLexedMemberInitializers() override;
void ParseLexedMethodDefs() override;
void ParseLexedAttributes() override;
private:
Parser *Self;
ParsingClass *Class;
};
/// Contains the lexed tokens of an attribute with arguments that
/// may reference member variables and so need to be parsed at the
/// end of the class declaration after parsing all other member
/// member declarations.
/// FIXME: Perhaps we should change the name of LateParsedDeclaration to
/// LateParsedTokens.
struct LateParsedAttribute : public LateParsedDeclaration {
Parser *Self;
CachedTokens Toks;
IdentifierInfo &AttrName;
SourceLocation AttrNameLoc;
SmallVector<Decl*, 2> Decls;
explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
SourceLocation Loc)
: Self(P), AttrName(Name), AttrNameLoc(Loc) {}
void ParseLexedAttributes() override;
void addDecl(Decl *D) { Decls.push_back(D); }
};
// A list of late-parsed attributes. Used by ParseGNUAttributes.
class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
public:
LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
bool parseSoon() { return ParseSoon; }
private:
bool ParseSoon; // Are we planning to parse these shortly after creation?
};
/// Contains the lexed tokens of a member function definition
/// which needs to be parsed at the end of the class declaration
/// after parsing all other member declarations.
struct LexedMethod : public LateParsedDeclaration {
Parser *Self;
Decl *D;
CachedTokens Toks;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
explicit LexedMethod(Parser* P, Decl *MD)
: Self(P), D(MD), TemplateScope(false) {}
void ParseLexedMethodDefs() override;
};
/// LateParsedDefaultArgument - Keeps track of a parameter that may
/// have a default argument that cannot be parsed yet because it
/// occurs within a member function declaration inside the class
/// (C++ [class.mem]p2).
struct LateParsedDefaultArgument {
explicit LateParsedDefaultArgument(Decl *P,
std::unique_ptr<CachedTokens> Toks = nullptr)
: Param(P), Toks(std::move(Toks)) { }
/// Param - The parameter declaration for this parameter.
Decl *Param;
/// Toks - The sequence of tokens that comprises the default
/// argument expression, not including the '=' or the terminating
/// ')' or ','. This will be NULL for parameters that have no
/// default argument.
std::unique_ptr<CachedTokens> Toks;
};
/// LateParsedMethodDeclaration - A method declaration inside a class that
/// contains at least one entity whose parsing needs to be delayed
/// until the class itself is completely-defined, such as a default
/// argument (C++ [class.mem]p2).
struct LateParsedMethodDeclaration : public LateParsedDeclaration {
explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
: Self(P), Method(M), TemplateScope(false),
ExceptionSpecTokens(nullptr) {}
void ParseLexedMethodDeclarations() override;
Parser* Self;
/// Method - The method declaration.
Decl *Method;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
/// DefaultArgs - Contains the parameters of the function and
/// their default arguments. At least one of the parameters will
/// have a default argument, but all of the parameters of the
/// method will be stored so that they can be reintroduced into
/// scope at the appropriate times.
SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
/// The set of tokens that make up an exception-specification that
/// has not yet been parsed.
CachedTokens *ExceptionSpecTokens;
};
/// LateParsedMemberInitializer - An initializer for a non-static class data
/// member whose parsing must to be delayed until the class is completely
/// defined (C++11 [class.mem]p2).
struct LateParsedMemberInitializer : public LateParsedDeclaration {
LateParsedMemberInitializer(Parser *P, Decl *FD)
: Self(P), Field(FD) { }
void ParseLexedMemberInitializers() override;
Parser *Self;
/// Field - The field declaration.
Decl *Field;
/// CachedTokens - The sequence of tokens that comprises the initializer,
/// including any leading '='.
CachedTokens Toks;
};
/// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
/// C++ class, its method declarations that contain parts that won't be
/// parsed until after the definition is completed (C++ [class.mem]p2),
/// the method declarations and possibly attached inline definitions
/// will be stored here with the tokens that will be parsed to create those
/// entities.
typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
/// Representation of a class that has been parsed, including
/// any member function declarations or definitions that need to be
/// parsed after the corresponding top-level class is complete.
struct ParsingClass {
ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
: TopLevelClass(TopLevelClass), TemplateScope(false),
IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
/// Whether this is a "top-level" class, meaning that it is
/// not nested within another class.
bool TopLevelClass : 1;
/// Whether this class had an associated template
/// scope. When true, TagOrTemplate is a template declaration;
/// otherwise, it is a tag declaration.
bool TemplateScope : 1;
/// Whether this class is an __interface.
bool IsInterface : 1;
/// The class or class template whose definition we are parsing.
Decl *TagOrTemplate;
/// LateParsedDeclarations - Method declarations, inline definitions and
/// nested classes that contain pieces whose parsing will be delayed until
/// the top-level class is fully defined.
LateParsedDeclarationsContainer LateParsedDeclarations;
};
/// The stack of classes that is currently being
/// parsed. Nested and local classes will be pushed onto this stack
/// when they are parsed, and removed afterward.
std::stack<ParsingClass *> ClassStack;
ParsingClass &getCurrentClass() {
assert(!ClassStack.empty() && "No lexed method stacks!");
return *ClassStack.top();
}
/// RAII object used to manage the parsing of a class definition.
class ParsingClassDefinition {
Parser &P;
bool Popped;
Sema::ParsingClassState State;
public:
ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
bool IsInterface)
: P(P), Popped(false),
State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
}
/// Pop this class of the stack.
void Pop() {
assert(!Popped && "Nested class has already been popped");
Popped = true;
P.PopParsingClass(State);
}
~ParsingClassDefinition() {
if (!Popped)
P.PopParsingClass(State);
}
};
/// Contains information about any template-specific
/// information that has been parsed prior to parsing declaration
/// specifiers.
struct ParsedTemplateInfo {
ParsedTemplateInfo()
: Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
bool isSpecialization,
bool lastParameterListWasEmpty = false)
: Kind(isSpecialization? ExplicitSpecialization : Template),
TemplateParams(TemplateParams),
LastParameterListWasEmpty(lastParameterListWasEmpty) { }
explicit ParsedTemplateInfo(SourceLocation ExternLoc,
SourceLocation TemplateLoc)
: Kind(ExplicitInstantiation), TemplateParams(nullptr),
ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
LastParameterListWasEmpty(false){ }
/// The kind of template we are parsing.
enum {
/// We are not parsing a template at all.
NonTemplate = 0,
/// We are parsing a template declaration.
Template,
/// We are parsing an explicit specialization.
ExplicitSpecialization,
/// We are parsing an explicit instantiation.
ExplicitInstantiation
} Kind;
/// The template parameter lists, for template declarations
/// and explicit specializations.
TemplateParameterLists *TemplateParams;
/// The location of the 'extern' keyword, if any, for an explicit
/// instantiation
SourceLocation ExternLoc;
/// The location of the 'template' keyword, for an explicit
/// instantiation.
SourceLocation TemplateLoc;
/// Whether the last template parameter list was empty.
bool LastParameterListWasEmpty;
SourceRange getSourceRange() const LLVM_READONLY;
};
void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
static void LateTemplateParserCleanupCallback(void *P);
Sema::ParsingClassState
PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
void DeallocateParsedClasses(ParsingClass *Class);
void PopParsingClass(Sema::ParsingClassState);
enum CachedInitKind {
CIK_DefaultArgument,
CIK_DefaultInitializer
};
NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
AttributeList *AccessAttrs,
ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo,
const VirtSpecifiers& VS,
SourceLocation PureSpecLoc);
void ParseCXXNonStaticMemberInitializer(Decl *VarD);
void ParseLexedAttributes(ParsingClass &Class);
void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
bool EnterScope, bool OnDefinition);
void ParseLexedAttribute(LateParsedAttribute &LA,
bool EnterScope, bool OnDefinition);
void ParseLexedMethodDeclarations(ParsingClass &Class);
void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
void ParseLexedMethodDefs(ParsingClass &Class);
void ParseLexedMethodDef(LexedMethod &LM);
void ParseLexedMemberInitializers(ParsingClass &Class);
void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
bool ConsumeAndStoreConditional(CachedTokens &Toks);
bool ConsumeAndStoreUntil(tok::TokenKind T1,
CachedTokens &Toks,
bool StopAtSemi = true,
bool ConsumeFinalToken = true) {
return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
}
bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
CachedTokens &Toks,
bool StopAtSemi = true,
bool ConsumeFinalToken = true);
//===--------------------------------------------------------------------===//
// C99 6.9: External Definitions.
struct ParsedAttributesWithRange : ParsedAttributes {
ParsedAttributesWithRange(AttributeFactory &factory)
: ParsedAttributes(factory) {}
void clear() {
ParsedAttributes::clear();
Range = SourceRange();
}
SourceRange Range;
};
DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS = nullptr);
bool isDeclarationAfterDeclarator();
bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
ParsedAttributesWithRange &attrs,
ParsingDeclSpec *DS = nullptr,
AccessSpecifier AS = AS_none);
DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
ParsingDeclSpec &DS,
AccessSpecifier AS);
void SkipFunctionBody();
Decl *ParseFunctionDefinition(ParsingDeclarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
LateParsedAttrList *LateParsedAttrs = nullptr);
void ParseKNRParamDeclarations(Declarator &D);
// EndLoc, if non-NULL, is filled with the location of the last token of
// the simple-asm.
ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
ExprResult ParseAsmStringLiteral();
// Objective-C External Declarations
void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs);
DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
ParsedAttributes &prefixAttrs);
class ObjCTypeParamListScope;
ObjCTypeParamList *parseObjCTypeParamList();
ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
SmallVectorImpl<IdentifierLocPair> &protocolIdents,
SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
BalancedDelimiterTracker &T,
SmallVectorImpl<Decl *> &AllIvarDecls,
bool RBraceMissing);
void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
tok::ObjCKeywordKind visibility,
SourceLocation atLoc);
bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
SmallVectorImpl<SourceLocation> &PLocs,
bool WarnOnDeclarations,
bool ForObjCContainer,
SourceLocation &LAngleLoc,
SourceLocation &EndProtoLoc,
bool consumeLastToken);
/// Parse the first angle-bracket-delimited clause for an
/// Objective-C object or object pointer type, which may be either
/// type arguments or protocol qualifiers.
void parseObjCTypeArgsOrProtocolQualifiers(
ParsedType baseType,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SmallVectorImpl<SourceLocation> &protocolLocs,
SourceLocation &protocolRAngleLoc,
bool consumeLastToken,
bool warnOnIncompleteProtocols);
/// Parse either Objective-C type arguments or protocol qualifiers; if the
/// former, also parse protocol qualifiers afterward.
void parseObjCTypeArgsAndProtocolQualifiers(
ParsedType baseType,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SmallVectorImpl<SourceLocation> &protocolLocs,
SourceLocation &protocolRAngleLoc,
bool consumeLastToken);
/// Parse a protocol qualifier type such as '<NSCopying>', which is
/// an anachronistic way of writing 'id<NSCopying>'.
TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
/// Parse Objective-C type arguments and protocol qualifiers, extending the
/// current type with the parsed result.
TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
ParsedType type,
bool consumeLastToken,
SourceLocation &endLoc);
void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
Decl *CDecl);
DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
ParsedAttributes &prefixAttrs);
struct ObjCImplParsingDataRAII {
Parser &P;
Decl *Dcl;
bool HasCFunction;
typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
LateParsedObjCMethodContainer LateParsedObjCMethods;
ObjCImplParsingDataRAII(Parser &parser, Decl *D)
: P(parser), Dcl(D), HasCFunction(false) {
P.CurParsedObjCImpl = this;
Finished = false;
}
~ObjCImplParsingDataRAII();
void finish(SourceRange AtEnd);
bool isFinished() const { return Finished; }
private:
bool Finished;
};
ObjCImplParsingDataRAII *CurParsedObjCImpl;
void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
// Definitions for Objective-c context sensitive keywords recognition.
enum ObjCTypeQual {
objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
objc_nonnull, objc_nullable, objc_null_unspecified,
objc_NumQuals
};
IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
bool isTokIdentifier_in() const;
ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
ParsedAttributes *ParamAttrs);
void ParseObjCMethodRequirement();
Decl *ParseObjCMethodPrototype(
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition = true);
Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition=true);
void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
Decl *ParseObjCMethodDefinition();
public:
//===--------------------------------------------------------------------===//
// C99 6.5: Expressions.
/// TypeCastState - State whether an expression is or may be a type cast.
enum TypeCastState {
NotTypeCast = 0,
MaybeTypeCast,
IsTypeCast
};
ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpressionInExprEvalContext(
TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstraintExpression();
// Expr that doesn't include commas.
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
unsigned &NumLineToksConsumed,
bool IsUnevaluated);
private:
ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
prec::Level MinPrec);
ExprResult ParseCastExpression(bool isUnaryExpression,
bool isAddressOfOperand,
bool &NotCastExpr,
TypeCastState isTypeCast,
bool isVectorLiteral = false);
ExprResult ParseCastExpression(bool isUnaryExpression,
bool isAddressOfOperand = false,
TypeCastState isTypeCast = NotTypeCast,
bool isVectorLiteral = false);
/// Returns true if the next token cannot start an expression.
bool isNotExpressionStart();
/// Returns true if the next token would start a postfix-expression
/// suffix.
bool isPostfixExpressionSuffixStart() {
tok::TokenKind K = Tok.getKind();
return (K == tok::l_square || K == tok::l_paren ||
K == tok::period || K == tok::arrow ||
K == tok::plusplus || K == tok::minusminus);
}
bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
ExprResult ParseUnaryExprOrTypeTraitExpression();
ExprResult ParseBuiltinPrimaryExpression();
ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
bool &isCastExpr,
ParsedType &CastTy,
SourceRange &CastRange);
typedef SmallVector<Expr*, 20> ExprListTy;
typedef SmallVector<SourceLocation, 20> CommaLocsTy;
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
bool ParseExpressionList(
SmallVectorImpl<Expr *> &Exprs,
SmallVectorImpl<SourceLocation> &CommaLocs,
llvm::function_ref<void()> Completer = llvm::function_ref<void()>());
/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
/// used for misc language extensions.
bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
SmallVectorImpl<SourceLocation> &CommaLocs);
/// ParenParseOption - Control what ParseParenExpression will parse.
enum ParenParseOption {
SimpleExpr, // Only parse '(' expression ')'
CompoundStmt, // Also allow '(' compound-statement ')'
CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
CastExpr // Also allow '(' type-name ')' <anything>
};
ExprResult ParseParenExpression(ParenParseOption &ExprType,
bool stopIfCastExpr,
bool isTypeCast,
ParsedType &CastTy,
SourceLocation &RParenLoc);
ExprResult ParseCXXAmbiguousParenExpression(
ParenParseOption &ExprType, ParsedType &CastTy,
BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
SourceLocation LParenLoc,
SourceLocation RParenLoc);
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
ExprResult ParseGenericSelectionExpression();
ExprResult ParseObjCBoolLiteral();
ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
//===--------------------------------------------------------------------===//
// C++ Expressions
ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
Token &Replacement);
ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
bool areTokensAdjacent(const Token &A, const Token &B);
void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
bool EnteringContext, IdentifierInfo &II,
CXXScopeSpec &SS);
bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext,
bool *MayBePseudoDestructor = nullptr,
bool IsTypename = false,
IdentifierInfo **LastII = nullptr,
bool OnlyNamespace = false);
//===--------------------------------------------------------------------===//
// C++0x 5.1.2: Lambda expressions
// [...] () -> type {...}
ExprResult ParseLambdaExpression();
ExprResult TryParseLambdaExpression();
Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
bool *SkippedInits = nullptr);
bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
ExprResult ParseLambdaExpressionAfterIntroducer(
LambdaIntroducer &Intro);
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Casts
ExprResult ParseCXXCasts();
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Type Identification
ExprResult ParseCXXTypeid();
//===--------------------------------------------------------------------===//
// C++ : Microsoft __uuidof Expression
ExprResult ParseCXXUuidof();
//===--------------------------------------------------------------------===//
// C++ 5.2.4: C++ Pseudo-Destructor Expressions
ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
ParsedType ObjectType);
//===--------------------------------------------------------------------===//
// C++ 9.3.2: C++ 'this' pointer
ExprResult ParseCXXThis();
//===--------------------------------------------------------------------===//
// C++ 15: C++ Throw Expression
ExprResult ParseThrowExpression();
ExceptionSpecificationType tryParseExceptionSpecification(
bool Delayed,
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &DynamicExceptions,
SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
ExprResult &NoexceptExpr,
CachedTokens *&ExceptionSpecTokens);
// EndLoc is filled with the location of the last token of the specification.
ExceptionSpecificationType ParseDynamicExceptionSpecification(
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &Exceptions,
SmallVectorImpl<SourceRange> &Ranges);
//===--------------------------------------------------------------------===//
// C++0x 8: Function declaration trailing-return-type
TypeResult ParseTrailingReturnType(SourceRange &Range,
bool MayBeFollowedByDirectInit);
//===--------------------------------------------------------------------===//
// C++ 2.13.5: C++ Boolean Literals
ExprResult ParseCXXBoolLiteral();
//===--------------------------------------------------------------------===//
// C++ 5.2.3: Explicit type conversion (functional notation)
ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
/// This should only be called when the current token is known to be part of
/// simple-type-specifier.
void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
//===--------------------------------------------------------------------===//
// C++ 5.3.4 and 5.3.5: C++ new and delete
bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
Declarator &D);
void ParseDirectNewDeclarator(Declarator &D);
ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
ExprResult ParseCXXDeleteExpression(bool UseGlobal,
SourceLocation Start);
//===--------------------------------------------------------------------===//
// C++ if/switch/while condition expression.
Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
SourceLocation Loc,
Sema::ConditionKind CK);
//===--------------------------------------------------------------------===//
// C++ Coroutines
ExprResult ParseCoyieldExpression();
//===--------------------------------------------------------------------===//
// C99 6.7.8: Initialization.
/// ParseInitializer
/// initializer: [C99 6.7.8]
/// assignment-expression
/// '{' ...
ExprResult ParseInitializer() {
if (Tok.isNot(tok::l_brace))
return ParseAssignmentExpression();
return ParseBraceInitializer();
}
bool MayBeDesignationStart();
ExprResult ParseBraceInitializer();
ExprResult ParseInitializerWithPotentialDesignator();
//===--------------------------------------------------------------------===//
// clang Expressions
ExprResult ParseBlockLiteralExpression(); // ^{...}
//===--------------------------------------------------------------------===//
// Objective-C Expressions
ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
bool isSimpleObjCMessageExpression();
ExprResult ParseObjCMessageExpression();
ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
SourceLocation SuperLoc,
ParsedType ReceiverType,
Expr *ReceiverExpr);
ExprResult ParseAssignmentExprWithObjCMessageExprStart(
SourceLocation LBracloc, SourceLocation SuperLoc,
ParsedType ReceiverType, Expr *ReceiverExpr);
bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
//===--------------------------------------------------------------------===//
// C99 6.8: Statements and Blocks.
/// A SmallVector of statements, with stack size 32 (as that is the only one
/// used.)
typedef SmallVector<Stmt*, 32> StmtVector;
/// A SmallVector of expressions, with stack size 12 (the maximum used.)
typedef SmallVector<Expr*, 12> ExprVector;
/// A SmallVector of types.
typedef SmallVector<ParsedType, 12> TypeVector;
StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
bool AllowOpenMPStandalone = false);
enum AllowedConstructsKind {
/// Allow any declarations, statements, OpenMP directives.
ACK_Any,
/// Allow only statements and non-standalone OpenMP directives.
ACK_StatementsOpenMPNonStandalone,
/// Allow statements and all executable OpenMP directives
ACK_StatementsOpenMPAnyExecutable
};
StmtResult
ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
SourceLocation *TrailingElseLoc = nullptr);
StmtResult ParseStatementOrDeclarationAfterAttributes(
StmtVector &Stmts,
AllowedConstructsKind Allowed,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs);
StmtResult ParseExprStatement();
StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
StmtResult ParseCaseStatement(bool MissingCase = false,
ExprResult Expr = ExprResult());
StmtResult ParseDefaultStatement();
StmtResult ParseCompoundStatement(bool isStmtExpr = false);
StmtResult ParseCompoundStatement(bool isStmtExpr,
unsigned ScopeFlags);
void ParseCompoundStatementLeadingPragmas();
StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
bool ParseParenExprOrCondition(StmtResult *InitStmt,
Sema::ConditionResult &CondResult,
SourceLocation Loc,
Sema::ConditionKind CK);
StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseDoStatement();
StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseGotoStatement();
StmtResult ParseContinueStatement();
StmtResult ParseBreakStatement();
StmtResult ParseReturnStatement();
StmtResult ParseAsmStatement(bool &msAsm);
StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
AllowedConstructsKind Allowed,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs);
/// Describes the behavior that should be taken for an __if_exists
/// block.
enum IfExistsBehavior {
/// Parse the block; this code is always used.
IEB_Parse,
/// Skip the block entirely; this code is never used.
IEB_Skip,
/// Parse the block as a dependent block, which may be used in
/// some template instantiations but not others.
IEB_Dependent
};
/// Describes the condition of a Microsoft __if_exists or
/// __if_not_exists block.
struct IfExistsCondition {
/// The location of the initial keyword.
SourceLocation KeywordLoc;
/// Whether this is an __if_exists block (rather than an
/// __if_not_exists block).
bool IsIfExists;
/// Nested-name-specifier preceding the name.
CXXScopeSpec SS;
/// The name we're looking for.
UnqualifiedId Name;
/// The behavior of this __if_exists or __if_not_exists block
/// should.
IfExistsBehavior Behavior;
};
bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
void ParseMicrosoftIfExistsExternalDeclaration();
void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
AccessSpecifier& CurAS);
bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
bool &InitExprsOk);
bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
SmallVectorImpl<Expr *> &Constraints,
SmallVectorImpl<Expr *> &Exprs);
//===--------------------------------------------------------------------===//
// C++ 6: Statements and Blocks
StmtResult ParseCXXTryBlock();
StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
StmtResult ParseCXXCatchBlock(bool FnCatch = false);
//===--------------------------------------------------------------------===//
// MS: SEH Statements and Blocks
StmtResult ParseSEHTryBlock();
StmtResult ParseSEHExceptBlock(SourceLocation Loc);
StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
StmtResult ParseSEHLeaveStatement();
//===--------------------------------------------------------------------===//
// Objective-C Statements
StmtResult ParseObjCAtStatement(SourceLocation atLoc);
StmtResult ParseObjCTryStmt(SourceLocation atLoc);
StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
//===--------------------------------------------------------------------===//
// C99 6.7: Declarations.
/// A context for parsing declaration specifiers. TODO: flesh this
/// out, there are other significant restrictions on specifiers than
/// would be best implemented in the parser.
enum class DeclSpecContext {
DSC_normal, // normal context
DSC_class, // class context, enables 'friend'
DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
DSC_top_level, // top-level/namespace declaration context
DSC_template_param, // template parameter context
DSC_template_type_arg, // template type argument context
DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
DSC_condition // condition declaration context
};
/// Is this a context in which we are parsing just a type-specifier (or
/// trailing-type-specifier)?
static bool isTypeSpecifier(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_template_param:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
case DeclSpecContext::DSC_objc_method_result:
case DeclSpecContext::DSC_condition:
return false;
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_type_specifier:
case DeclSpecContext::DSC_trailing:
case DeclSpecContext::DSC_alias_declaration:
return true;
}
llvm_unreachable("Missing DeclSpecContext case");
}
/// Is this a context in which we can perform class template argument
/// deduction?
static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_template_param:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
case DeclSpecContext::DSC_condition:
case DeclSpecContext::DSC_type_specifier:
return true;
case DeclSpecContext::DSC_objc_method_result:
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_trailing:
case DeclSpecContext::DSC_alias_declaration:
return false;
}
llvm_unreachable("Missing DeclSpecContext case");
}
/// Information on a C++0x for-range-initializer found while parsing a
/// declaration which turns out to be a for-range-declaration.
struct ForRangeInit {
SourceLocation ColonLoc;
ExprResult RangeExpr;
bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
};
DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributesWithRange &attrs);
DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributesWithRange &attrs,
bool RequireSemi,
ForRangeInit *FRI = nullptr);
bool MightBeDeclarator(DeclaratorContext Context);
DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
SourceLocation *DeclEnd = nullptr,
ForRangeInit *FRI = nullptr);
Decl *ParseDeclarationAfterDeclarator(Declarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
bool ParseAsmAttributesAfterDeclarator(Declarator &D);
Decl *ParseDeclarationAfterDeclaratorAndAttributes(
Declarator &D,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
ForRangeInit *FRI = nullptr);
Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
/// When in code-completion, skip parsing of the function/method body
/// unless the body contains the code-completion point.
///
/// \returns true if the function body was skipped.
bool trySkippingFunctionBody();
bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC,
ParsedAttributesWithRange &Attrs);
DeclSpecContext
getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
void ParseDeclarationSpecifiers(
DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
AccessSpecifier AS = AS_none,
DeclSpecContext DSC = DeclSpecContext::DSC_normal,
LateParsedAttrList *LateAttrs = nullptr);
bool DiagnoseMissingSemiAfterTagDefinition(
DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
LateParsedAttrList *LateAttrs = nullptr);
void ParseSpecifierQualifierList(
DeclSpec &DS, AccessSpecifier AS = AS_none,
DeclSpecContext DSC = DeclSpecContext::DSC_normal);
void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
DeclaratorContext Context);
void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, DeclSpecContext DSC);
void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
Decl *TagDecl);
void ParseStructDeclaration(
ParsingDeclSpec &DS,
llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
bool isTypeSpecifierQualifier();
/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
/// is definitely a type-specifier. Return false if it isn't part of a type
/// specifier or if we're not sure.
bool isKnownToBeTypeSpecifier(const Token &Tok) const;
/// Return true if we know that we are definitely looking at a
/// decl-specifier, and isn't part of an expression such as a function-style
/// cast. Return false if it's no a decl-specifier, or we're not sure.
bool isKnownToBeDeclarationSpecifier() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationSpecifier() == TPResult::True;
return isDeclarationSpecifier(true);
}
/// isDeclarationStatement - Disambiguates between a declaration or an
/// expression statement, when parsing function bodies.
/// Returns true for declaration, false for expression.
bool isDeclarationStatement() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationStatement();
return isDeclarationSpecifier(true);
}
/// isForInitDeclaration - Disambiguates between a declaration or an
/// expression in the context of the C 'clause-1' or the C++
// 'for-init-statement' part of a 'for' statement.
/// Returns true for declaration, false for expression.
bool isForInitDeclaration() {
if (getLangOpts().CPlusPlus)
return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
return isDeclarationSpecifier(true);
}
/// Determine whether this is a C++1z for-range-identifier.
bool isForRangeIdentifier();
/// Determine whether we are currently at the start of an Objective-C
/// class message that appears to be missing the open bracket '['.
bool isStartOfObjCClassMessageMissingOpenBracket();
/// Starting with a scope specifier, identifier, or
/// template-id that refers to the current class, determine whether
/// this is a constructor declarator.
bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
/// Specifies the context in which type-id/expression
/// disambiguation will occur.
enum TentativeCXXTypeIdContext {
TypeIdInParens,
TypeIdUnambiguous,
TypeIdAsTemplateArgument
};
/// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
/// whether the parens contain an expression or a type-id.
/// Returns true for a type-id and false for an expression.
bool isTypeIdInParens(bool &isAmbiguous) {
if (getLangOpts().CPlusPlus)
return isCXXTypeId(TypeIdInParens, isAmbiguous);
isAmbiguous = false;
return isTypeSpecifierQualifier();
}
bool isTypeIdInParens() {
bool isAmbiguous;
return isTypeIdInParens(isAmbiguous);
}
/// Checks if the current tokens form type-id or expression.
/// It is similar to isTypeIdInParens but does not suppose that type-id
/// is in parenthesis.
bool isTypeIdUnambiguously() {
bool IsAmbiguous;
if (getLangOpts().CPlusPlus)
return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
return isTypeSpecifierQualifier();
}
/// isCXXDeclarationStatement - C++-specialized function that disambiguates
/// between a declaration or an expression statement, when parsing function
/// bodies. Returns true for declaration, false for expression.
bool isCXXDeclarationStatement();
/// isCXXSimpleDeclaration - C++-specialized function that disambiguates
/// between a simple-declaration or an expression-statement.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
/// Returns false if the statement is disambiguated as expression.
bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
/// a constructor-style initializer, when parsing declaration statements.
/// Returns true for function declarator and false for constructor-style
/// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
/// might be a constructor-style initializer.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
struct ConditionDeclarationOrInitStatementState;
enum class ConditionOrInitStatement {
Expression, ///< Disambiguated as an expression (either kind).
ConditionDecl, ///< Disambiguated as the declaration form of condition.
InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
Error ///< Can't be any of the above!
};
/// Disambiguates between the different kinds of things that can happen
/// after 'if (' or 'switch ('. This could be one of two different kinds of
/// declaration (depending on whether there is a ';' later) or an expression.
ConditionOrInitStatement
isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
bool isAmbiguous;
return isCXXTypeId(Context, isAmbiguous);
}
/// TPResult - Used as the result value for functions whose purpose is to
/// disambiguate C++ constructs by "tentatively parsing" them.
enum class TPResult {
True, False, Ambiguous, Error
};
/// Based only on the given token kind, determine whether we know that
/// we're at the start of an expression or a type-specifier-seq (which may
/// be an expression, in C++).
///
/// This routine does not attempt to resolve any of the trick cases, e.g.,
/// those involving lookup of identifiers.
///
/// \returns \c TPR_true if this token starts an expression, \c TPR_false if
/// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
/// tell.
TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
/// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
/// declaration specifier, TPResult::False if it is not,
/// TPResult::Ambiguous if it could be either a decl-specifier or a
/// function-style cast, and TPResult::Error if a parsing error was
/// encountered. If it could be a braced C++11 function-style cast, returns
/// BracedCastResult.
/// Doesn't consume tokens.
TPResult
isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
bool *HasMissingTypename = nullptr);
/// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
/// \c TPResult::Ambiguous, determine whether the decl-specifier would be
/// a type-specifier other than a cv-qualifier.
bool isCXXDeclarationSpecifierAType();
/// Determine whether an identifier has been tentatively declared as a
/// non-type. Such tentative declarations should not be found to name a type
/// during a tentative parse, but also should not be annotated as a non-type.
bool isTentativelyDeclared(IdentifierInfo *II);
// "Tentative parsing" functions, used for disambiguation. If a parsing error
// is encountered they will return TPResult::Error.
// Returning TPResult::True/False indicates that the ambiguity was
// resolved and tentative parsing may stop. TPResult::Ambiguous indicates
// that more tentative parsing is necessary for disambiguation.
// They all consume tokens, so backtracking should be used after calling them.
TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
TPResult TryParseTypeofSpecifier();
TPResult TryParseProtocolQualifiers();
TPResult TryParsePtrOperatorSeq();
TPResult TryParseOperatorId();
TPResult TryParseInitDeclaratorList();
TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
bool mayHaveDirectInit = false);
TPResult
TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
bool VersusTemplateArg = false);
TPResult TryParseFunctionDeclarator();
TPResult TryParseBracketDeclarator();
TPResult TryConsumeDeclarationSpecifier();
public:
TypeResult ParseTypeName(SourceRange *Range = nullptr,
DeclaratorContext Context
= DeclaratorContext::TypeNameContext,
AccessSpecifier AS = AS_none,
Decl **OwnedType = nullptr,
ParsedAttributes *Attrs = nullptr);
private:
void ParseBlockId(SourceLocation CaretLoc);
/// Are [[]] attributes enabled?
bool standardAttributesAllowed() const {
const LangOptions &LO = getLangOpts();
return LO.DoubleSquareBracketAttributes;
}
// Check for the start of an attribute-specifier-seq in a context where an
// attribute is not allowed.
bool CheckProhibitedCXX11Attribute() {
assert(Tok.is(tok::l_square));
if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
return false;
return DiagnoseProhibitedCXX11Attribute();
}
bool DiagnoseProhibitedCXX11Attribute();
void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation) {
if (!standardAttributesAllowed())
return;
if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
Tok.isNot(tok::kw_alignas))
return;
DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
}
void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation);
void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
DeclSpec &DS, Sema::TagUseKind TUK);
// FixItLoc = possible correct location for the attributes
void ProhibitAttributes(ParsedAttributesWithRange &attrs,
SourceLocation FixItLoc = SourceLocation()) {
if (!attrs.Range.isValid()) return;
DiagnoseProhibitedAttributes(attrs, FixItLoc);
attrs.clear();
}
void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs,
SourceLocation FixItLoc);
// Forbid C++11 and C2x attributes that appear on certain syntactic locations
// which standard permits but we don't supported yet, for example, attributes
// appertain to decl specifiers.
void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
unsigned DiagID);
/// Skip C++11 and C2x attributes and return the end location of the
/// last one.
/// \returns SourceLocation() if there are no attributes.
SourceLocation SkipCXX11Attributes();
/// Diagnose and skip C++11 and C2x attributes that appear in syntactic
/// locations where attributes are not allowed.
void DiagnoseAndSkipCXX11Attributes();
/// Parses syntax-generic attribute arguments for attributes which are
/// known to the implementation, and adds them to the given ParsedAttributes
/// list with the given attribute syntax. Returns the number of arguments
/// parsed for the attribute.
unsigned
ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
AttributeList::Syntax Syntax);
void MaybeParseGNUAttributes(Declarator &D,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute)) {
ParsedAttributes attrs(AttrFactory);
SourceLocation endLoc;
ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute))
ParseGNUAttributes(attrs, endLoc, LateAttrs);
}
void ParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr,
Declarator *D = nullptr);
void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
AttributeList::Syntax Syntax,
Declarator *D);
IdentifierLoc *ParseIdentifierLoc();
unsigned
ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
AttributeList::Syntax Syntax);
void MaybeParseCXX11Attributes(Declarator &D) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrs(AttrFactory);
SourceLocation endLoc;
ParseCXX11Attributes(attrs, &endLoc);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrsWithRange(AttrFactory);
ParseCXX11Attributes(attrsWithRange, endLoc);
attrs.takeAllFrom(attrsWithRange);
}
}
void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *endLoc = nullptr,
bool OuterMightBeMessageSend = false) {
if (standardAttributesAllowed() &&
isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
ParseCXX11Attributes(attrs, endLoc);
}
void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
SourceLocation *EndLoc = nullptr);
void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *EndLoc = nullptr);
/// Parses a C++11 (or C2x)-style attribute argument list. Returns true
/// if this results in adding an attribute to the ParsedAttributes list.
bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc);
IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
ParseMicrosoftAttributes(attrs, endLoc);
}
void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
void ParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr);
void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr) {
const auto &LO = getLangOpts();
if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
ParseMicrosoftDeclSpecs(Attrs, End);
}
void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr);
bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs);
void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
SourceLocation SkipExtendedMicrosoftTypeAttributes();
void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
/// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
/// or higher.
/// \return false if error happens.
bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
if (getLangOpts().OpenCL)
return ParseOpenCLUnrollHintAttribute(Attrs);
return true;
}
/// Parses opencl_unroll_hint attribute.
/// \return false if error happens.
bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
VersionTuple ParseVersionTuple(SourceRange &Range);
void ParseAvailabilityAttribute(IdentifierInfo &Availability,
SourceLocation AvailabilityLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
AttributeList::Syntax Syntax);
Optional<AvailabilitySpec> ParseAvailabilitySpec();
ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
SourceLocation Loc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
AttributeList::Syntax Syntax);
void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
SourceLocation ObjCBridgeRelatedLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
AttributeList::Syntax Syntax);
void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
AttributeList::Syntax Syntax);
void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
AttributeList::Syntax Syntax);
void ParseTypeofSpecifier(DeclSpec &DS);
SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
void ParseAtomicSpecifier(DeclSpec &DS);
ExprResult ParseAlignArgument(SourceLocation Start,
SourceLocation &EllipsisLoc);
void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
SourceLocation *endLoc = nullptr);
VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
return isCXX11VirtSpecifier(Tok);
}
void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
SourceLocation FriendLoc);
bool isCXX11FinalKeyword() const;
/// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
/// enter a new C++ declarator scope and exit it when the function is
/// finished.
class DeclaratorScopeObj {
Parser &P;
CXXScopeSpec &SS;
bool EnteredScope;
bool CreatedScope;
public:
DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
: P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
void EnterDeclaratorScope() {
assert(!EnteredScope && "Already entered the scope!");
assert(SS.isSet() && "C++ scope was not set!");
CreatedScope = true;
P.EnterScope(0); // Not a decl scope.
if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
EnteredScope = true;
}
~DeclaratorScopeObj() {
if (EnteredScope) {
assert(SS.isSet() && "C++ scope was cleared ?");
P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
}
if (CreatedScope)
P.ExitScope();
}
};
/// ParseDeclarator - Parse and verify a newly-initialized declarator.
void ParseDeclarator(Declarator &D);
/// A function that parses a variant of direct-declarator.
typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
void ParseDeclaratorInternal(Declarator &D,
DirectDeclParseFunction DirectDeclParser);
enum AttrRequirements {
AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
AR_GNUAttributesParsed = 1 << 1,
AR_CXX11AttributesParsed = 1 << 2,
AR_DeclspecAttributesParsed = 1 << 3,
AR_AllAttributesParsed = AR_GNUAttributesParsed |
AR_CXX11AttributesParsed |
AR_DeclspecAttributesParsed,
AR_VendorAttributesParsed = AR_GNUAttributesParsed |
AR_DeclspecAttributesParsed
};
void ParseTypeQualifierListOpt(
DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
bool AtomicAllowed = true, bool IdentifierRequired = false,
Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
void ParseDirectDeclarator(Declarator &D);
void ParseDecompositionDeclarator(Declarator &D);
void ParseParenDeclarator(Declarator &D);
void ParseFunctionDeclarator(Declarator &D,
ParsedAttributes &attrs,
BalancedDelimiterTracker &Tracker,
bool IsAmbiguous,
bool RequiresArg = false);
bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
SourceLocation &RefQualifierLoc);
bool isFunctionDeclaratorIdentifierList();
void ParseFunctionDeclaratorIdentifierList(
Declarator &D,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
void ParseParameterDeclarationClause(
Declarator &D,
ParsedAttributes &attrs,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
SourceLocation &EllipsisLoc);
void ParseBracketDeclarator(Declarator &D);
void ParseMisplacedBracketDeclarator(Declarator &D);
//===--------------------------------------------------------------------===//
// C++ 7: Declarations [dcl.dcl]
/// The kind of attribute specifier we have found.
enum CXX11AttributeKind {
/// This is not an attribute specifier.
CAK_NotAttributeSpecifier,
/// This should be treated as an attribute-specifier.
CAK_AttributeSpecifier,
/// The next tokens are '[[', but this is not an attribute-specifier. This
/// is ill-formed by C++11 [dcl.attr.grammar]p6.
CAK_InvalidAttributeSpecifier
};
CXX11AttributeKind
isCXX11AttributeSpecifier(bool Disambiguate = false,
bool OuterMightBeMessageSend = false);
void DiagnoseUnexpectedNamespace(NamedDecl *Context);
DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
SourceLocation &DeclEnd,
SourceLocation InlineLoc = SourceLocation());
void ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
std::vector<IdentifierInfo *> &Ident,
std::vector<SourceLocation> &NamespaceLoc,
unsigned int index, SourceLocation &InlineLoc,
ParsedAttributes &attrs,
BalancedDelimiterTracker &Tracker);
Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
Decl *ParseExportDeclaration();
DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
Decl *ParseUsingDirective(DeclaratorContext Context,
SourceLocation UsingLoc,
SourceLocation &DeclEnd,
ParsedAttributes &attrs);
struct UsingDeclarator {
SourceLocation TypenameLoc;
CXXScopeSpec SS;
UnqualifiedId Name;
SourceLocation EllipsisLoc;
void clear() {
TypenameLoc = EllipsisLoc = SourceLocation();
SS.clear();
Name.clear();
}
};
bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
const ParsedTemplateInfo &TemplateInfo,
SourceLocation UsingLoc,
SourceLocation &DeclEnd,
AccessSpecifier AS = AS_none);
Decl *ParseAliasDeclarationAfterDeclarator(
const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
SourceLocation AliasLoc, IdentifierInfo *Alias,
SourceLocation &DeclEnd);
//===--------------------------------------------------------------------===//
// C++ 9: classes [class] and C structs/unions.
bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
AccessSpecifier AS, bool EnteringContext,
DeclSpecContext DSC,
ParsedAttributesWithRange &Attributes);
void SkipCXXMemberSpecification(SourceLocation StartLoc,
SourceLocation AttrFixitLoc,
unsigned TagType,
Decl *TagDecl);
void ParseCXXMemberSpecification(SourceLocation StartLoc,
SourceLocation AttrFixitLoc,
ParsedAttributesWithRange &Attrs,
unsigned TagType,
Decl *TagDecl);
ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
SourceLocation &EqualLoc);
bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
VirtSpecifiers &VS,
ExprResult &BitfieldSize,
LateParsedAttrList &LateAttrs);
void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
VirtSpecifiers &VS);
DeclGroupPtrTy ParseCXXClassMemberDeclaration(
AccessSpecifier AS, AttributeList *Attr,
const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
DeclSpec::TST TagType, Decl *Tag);
void ParseConstructorInitializer(Decl *ConstructorDecl);
MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
Decl *ThisDecl);
//===--------------------------------------------------------------------===//
// C++ 10: Derived classes [class.derived]
TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
SourceLocation &EndLocation);
void ParseBaseClause(Decl *ClassDecl);
BaseResult ParseBaseSpecifier(Decl *ClassDecl);
AccessSpecifier getAccessSpecifierIfPresent() const;
bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Id,
bool AssumeTemplateId);
bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Result);
//===--------------------------------------------------------------------===//
// OpenMP: Directives and clauses.
/// Parse clauses for '#pragma omp declare simd'.
DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
CachedTokens &Toks,
SourceLocation Loc);
/// Parses declarative OpenMP directives.
DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
DeclSpec::TST TagType = DeclSpec::TST_unspecified,
Decl *TagDecl = nullptr);
/// Parse 'omp declare reduction' construct.
DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
/// Parses initializer for provided omp_priv declaration inside the reduction
/// initializer.
void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
/// Parses simple list of variables.
///
/// \param Kind Kind of the directive.
/// \param Callback Callback function to be called for the list elements.
/// \param AllowScopeSpecifier true, if the variables can have fully
/// qualified names.
///
bool ParseOpenMPSimpleVarList(
OpenMPDirectiveKind Kind,
const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
Callback,
bool AllowScopeSpecifier);
/// Parses declarative or executable directive.
///
/// \param Allowed ACK_Any, if any directives are allowed,
/// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
/// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
/// executable directives are allowed.
///
StmtResult
ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
/// Parses clause of kind \a CKind for directive of a kind \a Kind.
///
/// \param DKind Kind of current directive.
/// \param CKind Kind of current clause.
/// \param FirstClause true, if this is the first clause of a kind \a CKind
/// in current directive.
///
OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
OpenMPClauseKind CKind, bool FirstClause);
/// Parses clause with a single expression of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
bool ParseOnly);
/// Parses simple clause of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
/// Parses clause with a single expression and an additional argument
/// of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
bool ParseOnly);
/// Parses clause without any additional arguments.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
/// Parses clause with the list of variables of a kind \a Kind.
///
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
OpenMPClauseKind Kind, bool ParseOnly);
public:
/// Parses simple expression in parens for single-expression clauses of OpenMP
/// constructs.
/// \param RLoc Returned location of right paren.
ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
/// Data used for parsing list of variables in OpenMP clauses.
struct OpenMPVarListDataTy {
Expr *TailExpr = nullptr;
SourceLocation ColonLoc;
CXXScopeSpec ReductionIdScopeSpec;
DeclarationNameInfo ReductionId;
OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
bool IsMapTypeImplicit = false;
SourceLocation DepLinMapLoc;
};
/// Parses clauses with list.
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
SmallVectorImpl<Expr *> &Vars,
OpenMPVarListDataTy &Data);
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
bool AllowDestructorName,
bool AllowConstructorName,
bool AllowDeductionGuide,
ParsedType ObjectType,
SourceLocation *TemplateKWLoc,
UnqualifiedId &Result);
private:
//===--------------------------------------------------------------------===//
// C++ 14: Templates [temp]
// C++ 14.1: Template Parameters [temp.param]
Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
SourceLocation &DeclEnd,
AccessSpecifier AS = AS_none,
AttributeList *AccessAttrs = nullptr);
Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
SourceLocation &DeclEnd,
AccessSpecifier AS,
AttributeList *AccessAttrs);
Decl *ParseSingleDeclarationAfterTemplate(
DeclaratorContext Context,
const ParsedTemplateInfo &TemplateInfo,
ParsingDeclRAIIObject &DiagsFromParams,
SourceLocation &DeclEnd,
AccessSpecifier AS=AS_none,
AttributeList *AccessAttrs = nullptr);
bool ParseTemplateParameters(unsigned Depth,
SmallVectorImpl<NamedDecl *> &TemplateParams,
SourceLocation &LAngleLoc,
SourceLocation &RAngleLoc);
bool ParseTemplateParameterList(unsigned Depth,
SmallVectorImpl<NamedDecl*> &TemplateParams);
bool isStartOfTemplateTypeParameter();
NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
SourceLocation CorrectLoc,
bool AlreadyHasEllipsis,
bool IdentifierHasName);
void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
Declarator &D);
// C++ 14.3: Template arguments [temp.arg]
typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
bool ConsumeLastToken,
bool ObjCGenericList);
bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
SourceLocation &LAngleLoc,
TemplateArgList &TemplateArgs,
SourceLocation &RAngleLoc);
bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &TemplateName,
bool AllowTypeAnnotation = true);
void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
bool IsTemplateArgumentList(unsigned Skip = 0);
bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
ParsedTemplateArgument ParseTemplateTemplateArgument();
ParsedTemplateArgument ParseTemplateArgument();
Decl *ParseExplicitInstantiation(DeclaratorContext Context,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
SourceLocation &DeclEnd,
AccessSpecifier AS = AS_none);
//===--------------------------------------------------------------------===//
// Modules
DeclGroupPtrTy ParseModuleDecl();
Decl *ParseModuleImport(SourceLocation AtLoc);
bool parseMisplacedModuleImport();
bool tryParseMisplacedModuleImport() {
tok::TokenKind Kind = Tok.getKind();
if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
Kind == tok::annot_module_include)
return parseMisplacedModuleImport();
return false;
}
bool ParseModuleName(
SourceLocation UseLoc,
SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
bool IsImport);
//===--------------------------------------------------------------------===//
// C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
ExprResult ParseTypeTrait();
//===--------------------------------------------------------------------===//
// Embarcadero: Arary and Expression Traits
ExprResult ParseArrayTypeTrait();
ExprResult ParseExpressionTrait();
//===--------------------------------------------------------------------===//
// Preprocessor code-completion pass-through
void CodeCompleteDirective(bool InConditional) override;
void CodeCompleteInConditionalExclusion() override;
void CodeCompleteMacroName(bool IsDefinition) override;
void CodeCompletePreprocessorExpression() override;
void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
unsigned ArgumentIndex) override;
void CodeCompleteNaturalLanguage() override;
};
} // end namespace clang
#endif
|
GrB_Vector_wait.c | //------------------------------------------------------------------------------
// GrB_Vector_wait: wait for a vector to complete
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Finishes all work on a vector, followed by an OpenMP flush.
#include "GB.h"
#define GB_FREE_ALL ;
GrB_Info GrB_Vector_wait // finish all work on a vector
(
#if (GxB_IMPLEMENTATION_MAJOR <= 5)
GrB_Vector *v
#else
GrB_Vector v,
GrB_WaitMode waitmode
#endif
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
#if (GxB_IMPLEMENTATION_MAJOR <= 5)
GB_WHERE ((*v), "GrB_Vector_wait (&v)") ;
GB_RETURN_IF_NULL (v) ;
GB_RETURN_IF_NULL_OR_FAULTY (*v) ;
#else
GB_WHERE (v, "GrB_Vector_wait (v, waitmode)") ;
GB_RETURN_IF_NULL_OR_FAULTY (v) ;
#endif
//--------------------------------------------------------------------------
// finish all pending work on the vector
//--------------------------------------------------------------------------
#if (GxB_IMPLEMENTATION_MAJOR <= 5)
if (GB_ANY_PENDING_WORK (*v))
{
GrB_Info info ;
GB_BURBLE_START ("GrB_Vector_wait") ;
GB_OK (GB_wait ((GrB_Matrix) (*v), "vector", Context)) ;
GB_BURBLE_END ;
}
#else
if (waitmode != GrB_COMPLETE && GB_ANY_PENDING_WORK (v))
{
GrB_Info info ;
GB_BURBLE_START ("GrB_Vector_wait") ;
GB_OK (GB_wait ((GrB_Matrix) v, "vector", Context)) ;
GB_BURBLE_END ;
}
#endif
//--------------------------------------------------------------------------
// return result
//--------------------------------------------------------------------------
#pragma omp flush
return (GrB_SUCCESS) ;
}
|
compare.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC OOO M M PPPP AAA RRRR EEEEE %
% C O O MM MM P P A A R R E %
% C O O M M M PPPP AAAAA RRRR EEE %
% C O O M M P A A R R E %
% CCCC OOO M M P A A R R EEEEE %
% %
% %
% MagickCore Image Comparison Methods %
% %
% Software Design %
% Cristy %
% December 2003 %
% %
% %
% Copyright @ 1999 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/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/compare.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/fourier.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/registry.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string_.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"
#include "MagickCore/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p a r e I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CompareImages() compares one or more pixel channels of an image to a
% reconstructed image and returns the difference image.
%
% The format of the CompareImages method is:
%
% Image *CompareImages(const Image *image,const Image *reconstruct_image,
% const MetricType metric,double *distortion,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o metric: the metric.
%
% o distortion: the computed distortion between the images.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CompareImages(Image *image,const Image *reconstruct_image,
const MetricType metric,double *distortion,ExceptionInfo *exception)
{
CacheView
*highlight_view,
*image_view,
*reconstruct_view;
const char
*artifact;
double
fuzz;
Image
*clone_image,
*difference_image,
*highlight_image;
MagickBooleanType
status;
PixelInfo
highlight,
lowlight,
masklight;
RectangleInfo
geometry;
size_t
columns,
rows;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
assert(distortion != (double *) NULL);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*distortion=0.0;
status=GetImageDistortion(image,reconstruct_image,metric,distortion,
exception);
if (status == MagickFalse)
return((Image *) NULL);
columns=MagickMax(image->columns,reconstruct_image->columns);
rows=MagickMax(image->rows,reconstruct_image->rows);
SetGeometry(image,&geometry);
geometry.width=columns;
geometry.height=rows;
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageMask(clone_image,ReadPixelMask,(Image *) NULL,exception);
difference_image=ExtentImage(clone_image,&geometry,exception);
clone_image=DestroyImage(clone_image);
if (difference_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageAlphaChannel(difference_image,OpaqueAlphaChannel,exception);
highlight_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (highlight_image == (Image *) NULL)
{
difference_image=DestroyImage(difference_image);
return((Image *) NULL);
}
status=SetImageStorageClass(highlight_image,DirectClass,exception);
if (status == MagickFalse)
{
difference_image=DestroyImage(difference_image);
highlight_image=DestroyImage(highlight_image);
return((Image *) NULL);
}
(void) SetImageMask(highlight_image,ReadPixelMask,(Image *) NULL,exception);
(void) SetImageAlphaChannel(highlight_image,OpaqueAlphaChannel,exception);
(void) QueryColorCompliance("#f1001ecc",AllCompliance,&highlight,exception);
artifact=GetImageArtifact(image,"compare:highlight-color");
if (artifact != (const char *) NULL)
(void) QueryColorCompliance(artifact,AllCompliance,&highlight,exception);
(void) QueryColorCompliance("#ffffffcc",AllCompliance,&lowlight,exception);
artifact=GetImageArtifact(image,"compare:lowlight-color");
if (artifact != (const char *) NULL)
(void) QueryColorCompliance(artifact,AllCompliance,&lowlight,exception);
(void) QueryColorCompliance("#888888cc",AllCompliance,&masklight,exception);
artifact=GetImageArtifact(image,"compare:masklight-color");
if (artifact != (const char *) NULL)
(void) QueryColorCompliance(artifact,AllCompliance,&masklight,exception);
/*
Generate difference image.
*/
status=MagickTrue;
fuzz=GetFuzzyColorDistance(image,reconstruct_image);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
highlight_view=AcquireAuthenticCacheView(highlight_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,highlight_image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
MagickBooleanType
sync;
const Quantum
*magick_restrict p,
*magick_restrict q;
Quantum
*magick_restrict r;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
r=QueueCacheViewAuthenticPixels(highlight_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) ||
(r == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
MagickStatusType
difference;
ssize_t
i;
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
SetPixelViaPixelInfo(highlight_image,&masklight,r);
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
r+=GetPixelChannels(highlight_image);
continue;
}
difference=MagickFalse;
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance,
pixel;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
pixel=(double) p[i]-GetPixelChannel(reconstruct_image,channel,q);
else
pixel=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q);
distance=pixel*pixel;
if (distance >= fuzz)
{
difference=MagickTrue;
break;
}
}
if (difference == MagickFalse)
SetPixelViaPixelInfo(highlight_image,&lowlight,r);
else
SetPixelViaPixelInfo(highlight_image,&highlight,r);
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
r+=GetPixelChannels(highlight_image);
}
sync=SyncCacheViewAuthenticPixels(highlight_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
highlight_view=DestroyCacheView(highlight_view);
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
(void) CompositeImage(difference_image,highlight_image,image->compose,
MagickTrue,0,0,exception);
highlight_image=DestroyImage(highlight_image);
if (status == MagickFalse)
difference_image=DestroyImage(difference_image);
return(difference_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e D i s t o r t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageDistortion() compares one or more pixel channels of an image to a
% reconstructed image and returns the specified distortion metric.
%
% The format of the GetImageDistortion method is:
%
% MagickBooleanType GetImageDistortion(const Image *image,
% const Image *reconstruct_image,const MetricType metric,
% double *distortion,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o metric: the metric.
%
% o distortion: the computed distortion between the images.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType GetAbsoluteDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
fuzz;
MagickBooleanType
status;
size_t
columns,
rows;
ssize_t
y;
/*
Compute the absolute difference in pixels between two images.
*/
status=MagickTrue;
fuzz=GetFuzzyColorDistance(image,reconstruct_image);
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
const Quantum
*magick_restrict p,
*magick_restrict q;
ssize_t
j,
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) memset(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
MagickBooleanType
difference;
ssize_t
i;
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
difference=MagickFalse;
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance,
pixel;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
pixel=(double) p[i]-GetPixelChannel(reconstruct_image,channel,q);
else
pixel=Sa*p[i]-Da*GetPixelChannel(reconstruct_image,channel,q);
distance=pixel*pixel;
if (distance >= fuzz)
{
channel_distortion[i]++;
difference=MagickTrue;
}
}
if (difference != MagickFalse)
channel_distortion[CompositePixelChannel]++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetAbsoluteDistortion)
#endif
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]+=channel_distortion[j];
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType GetFuzzDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
area;
MagickBooleanType
status;
ssize_t
j;
size_t
columns,
rows;
ssize_t
y;
status=MagickTrue;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
area=0.0;
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
const Quantum
*magick_restrict p,
*magick_restrict q;
size_t
local_area = 0;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) memset(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
ssize_t
i;
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
distance=QuantumScale*(p[i]-GetPixelChannel(reconstruct_image,
channel,q));
else
distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image,
channel,q));
channel_distortion[i]+=distance*distance;
channel_distortion[CompositePixelChannel]+=distance*distance;
}
local_area++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetFuzzDistortion)
#endif
{
area+=local_area;
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]+=channel_distortion[j];
}
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
area=PerceptibleReciprocal(area);
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]*=area;
distortion[CompositePixelChannel]/=(double) GetImageChannels(image);
distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]);
return(status);
}
static MagickBooleanType GetMeanAbsoluteDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
area;
MagickBooleanType
status;
ssize_t
j;
size_t
columns,
rows;
ssize_t
y;
status=MagickTrue;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
area=0.0;
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
const Quantum
*magick_restrict p,
*magick_restrict q;
size_t
local_area = 0;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) memset(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
ssize_t
i;
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
distance=QuantumScale*fabs((double) (p[i]-(double)
GetPixelChannel(reconstruct_image,channel,q)));
else
distance=QuantumScale*fabs((double) (Sa*p[i]-Da*
GetPixelChannel(reconstruct_image,channel,q)));
channel_distortion[i]+=distance;
channel_distortion[CompositePixelChannel]+=distance;
}
local_area++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetMeanAbsoluteError)
#endif
{
area+=local_area;
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]+=channel_distortion[j];
}
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
area=PerceptibleReciprocal(area);
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]*=area;
distortion[CompositePixelChannel]/=(double) GetImageChannels(image);
return(status);
}
static MagickBooleanType GetMeanErrorPerPixel(Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
MagickBooleanType
status;
double
area,
maximum_error,
mean_error;
size_t
columns,
rows;
ssize_t
y;
status=MagickTrue;
area=0.0;
maximum_error=0.0;
mean_error=0.0;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
for (y=0; y < (ssize_t) rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q;
ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
ssize_t
i;
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
distance=fabs((double) (p[i]-(double)
GetPixelChannel(reconstruct_image,channel,q)));
else
distance=fabs((double) (Sa*p[i]-Da*
GetPixelChannel(reconstruct_image,channel,q)));
distortion[i]+=distance;
distortion[CompositePixelChannel]+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
area++;
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
area=PerceptibleReciprocal(area);
image->error.mean_error_per_pixel=area*distortion[CompositePixelChannel];
image->error.normalized_mean_error=area*QuantumScale*QuantumScale*mean_error;
image->error.normalized_maximum_error=QuantumScale*maximum_error;
return(status);
}
static MagickBooleanType GetMeanSquaredDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
area;
MagickBooleanType
status;
size_t
columns,
rows;
ssize_t
j,
y;
status=MagickTrue;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
area=0.0;
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q;
double
channel_distortion[MaxPixelChannels+1];
size_t
local_area = 0;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) memset(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
ssize_t
i;
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
distance=QuantumScale*(p[i]-GetPixelChannel(reconstruct_image,
channel,q));
else
distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(reconstruct_image,
channel,q));
channel_distortion[i]+=distance*distance;
channel_distortion[CompositePixelChannel]+=distance*distance;
}
local_area++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetMeanSquaredError)
#endif
{
area+=local_area;
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]+=channel_distortion[j];
}
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
area=PerceptibleReciprocal(area);
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]*=area;
distortion[CompositePixelChannel]/=GetImageChannels(image);
return(status);
}
static MagickBooleanType GetNormalizedCrossCorrelationDistortion(
const Image *image,const Image *reconstruct_image,double *distortion,
ExceptionInfo *exception)
{
#define SimilarityImageTag "Similarity/Image"
CacheView
*image_view,
*reconstruct_view;
ChannelStatistics
*image_statistics,
*reconstruct_statistics;
double
area;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
channels,
i;
size_t
columns,
rows;
ssize_t
y;
/*
Normalize to account for variation due to lighting and exposure condition.
*/
image_statistics=GetImageStatistics(image,exception);
reconstruct_statistics=GetImageStatistics(reconstruct_image,exception);
if ((image_statistics == (ChannelStatistics *) NULL) ||
(reconstruct_statistics == (ChannelStatistics *) NULL))
{
if (image_statistics != (ChannelStatistics *) NULL)
image_statistics=(ChannelStatistics *) RelinquishMagickMemory(
image_statistics);
if (reconstruct_statistics != (ChannelStatistics *) NULL)
reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory(
reconstruct_statistics);
return(MagickFalse);
}
status=MagickTrue;
progress=0;
for (i=0; i <= MaxPixelChannels; i++)
distortion[i]=0.0;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
area=0.0;
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
for (y=0; y < (ssize_t) rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q;
ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) columns; x++)
{
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
area++;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
}
area=PerceptibleReciprocal(area);
for (y=0; y < (ssize_t) rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q;
ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
distortion[i]+=area*QuantumScale*((double) p[i]-
image_statistics[channel].mean)*(GetPixelChannel(reconstruct_image,
channel,q)-reconstruct_statistics[channel].mean);
else
distortion[i]+=area*QuantumScale*(Sa*p[i]-
image_statistics[channel].mean)*(Da*GetPixelChannel(
reconstruct_image,channel,q)-reconstruct_statistics[channel].mean);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SimilarityImageTag,progress,rows);
if (proceed == MagickFalse)
{
status=MagickFalse;
break;
}
}
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
/*
Divide by the standard deviation.
*/
channels=0;
distortion[CompositePixelChannel]=0.0;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
gamma;
PixelChannel channel = GetPixelChannelChannel(image,i);
gamma=image_statistics[channel].standard_deviation*
reconstruct_statistics[channel].standard_deviation;
if (fabs(gamma) >= MagickEpsilon)
{
gamma=PerceptibleReciprocal(gamma);
distortion[i]=QuantumRange*gamma*distortion[i];
distortion[CompositePixelChannel]+=distortion[i]*distortion[i];
channels++;
}
}
if (channels != 0)
distortion[CompositePixelChannel]=sqrt(distortion[CompositePixelChannel]/
channels);
/*
Free resources.
*/
reconstruct_statistics=(ChannelStatistics *) RelinquishMagickMemory(
reconstruct_statistics);
image_statistics=(ChannelStatistics *) RelinquishMagickMemory(
image_statistics);
return(status);
}
static MagickBooleanType GetPeakAbsoluteDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
MagickBooleanType
status;
size_t
columns,
rows;
ssize_t
y;
status=MagickTrue;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
const Quantum
*magick_restrict p,
*magick_restrict q;
ssize_t
j,
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) memset(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
Da,
Sa;
ssize_t
i;
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,p);
Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
if (channel == AlphaPixelChannel)
distance=QuantumScale*fabs((double) (p[i]-(double)
GetPixelChannel(reconstruct_image,channel,q)));
else
distance=QuantumScale*fabs((double) (Sa*p[i]-Da*
GetPixelChannel(reconstruct_image,channel,q)));
if (distance > channel_distortion[i])
channel_distortion[i]=distance;
if (distance > channel_distortion[CompositePixelChannel])
channel_distortion[CompositePixelChannel]=distance;
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetPeakAbsoluteError)
#endif
for (j=0; j <= MaxPixelChannels; j++)
if (channel_distortion[j] > distortion[j])
distortion[j]=channel_distortion[j];
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
return(status);
}
static inline double MagickLog10(const double x)
{
#define Log10Epsilon (1.0e-11)
if (fabs(x) < Log10Epsilon)
return(log10(Log10Epsilon));
return(log10(fabs(x)));
}
static MagickBooleanType GetPeakSignalToNoiseRatio(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
i;
status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception);
for (i=0; i <= MaxPixelChannels; i++)
if (fabs(distortion[i]) < MagickEpsilon)
distortion[i]=INFINITY;
else
distortion[i]=10.0*MagickLog10(1.0)-10.0*MagickLog10(distortion[i]);
return(status);
}
static MagickBooleanType GetPerceptualHashDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
ChannelPerceptualHash
*channel_phash,
*reconstruct_phash;
const char
*artifact;
ssize_t
channel,
j;
/*
Compute perceptual hash in the sRGB colorspace.
*/
channel_phash=GetImagePerceptualHash(image,exception);
if (channel_phash == (ChannelPerceptualHash *) NULL)
return(MagickFalse);
reconstruct_phash=GetImagePerceptualHash(reconstruct_image,exception);
if (reconstruct_phash == (ChannelPerceptualHash *) NULL)
{
channel_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(
channel_phash);
return(MagickFalse);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static)
#endif
for (channel=0; channel < MaxPixelChannels; channel++)
{
double
difference;
ssize_t
i;
difference=0.0;
for (i=0; i < MaximumNumberOfImageMoments; i++)
{
double
alpha,
beta;
ssize_t
j;
for (j=0; j < (ssize_t) channel_phash[0].number_colorspaces; j++)
{
alpha=channel_phash[channel].phash[j][i];
beta=reconstruct_phash[channel].phash[j][i];
difference+=(beta-alpha)*(beta-alpha);
}
}
distortion[channel]+=difference;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetPerceptualHashDistortion)
#endif
distortion[CompositePixelChannel]+=difference;
}
artifact=GetImageArtifact(image,"phash:normalize");
if ((artifact != (const char *) NULL) &&
(IsStringTrue(artifact) != MagickFalse))
for (j=0; j <= MaxPixelChannels; j++)
distortion[j]=sqrt(distortion[j]/channel_phash[0].number_channels);
/*
Free resources.
*/
reconstruct_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(
reconstruct_phash);
channel_phash=(ChannelPerceptualHash *) RelinquishMagickMemory(channel_phash);
return(MagickTrue);
}
static MagickBooleanType GetRootMeanSquaredDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
i;
status=GetMeanSquaredDistortion(image,reconstruct_image,distortion,exception);
for (i=0; i <= MaxPixelChannels; i++)
distortion[i]=sqrt(distortion[i]);
return(status);
}
static MagickBooleanType GetStructuralSimilarityDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
#define SSIMRadius 5.0
#define SSIMSigma 1.5
#define SSIMBlocksize 8
#define SSIMK1 0.01
#define SSIMK2 0.03
#define SSIML 1.0
CacheView
*image_view,
*reconstruct_view;
char
geometry[MagickPathExtent];
const char
*artifact;
double
area,
c1,
c2,
radius,
sigma;
KernelInfo
*kernel_info;
MagickBooleanType
status;
ssize_t
j;
size_t
columns,
rows;
ssize_t
y;
/*
Compute structural similarity index @
https://en.wikipedia.org/wiki/Structural_similarity.
*/
radius=SSIMRadius;
artifact=GetImageArtifact(image,"compare:ssim-radius");
if (artifact != (const char *) NULL)
radius=StringToDouble(artifact,(char **) NULL);
sigma=SSIMSigma;
artifact=GetImageArtifact(image,"compare:ssim-sigma");
if (artifact != (const char *) NULL)
sigma=StringToDouble(artifact,(char **) NULL);
(void) FormatLocaleString(geometry,MagickPathExtent,"gaussian:%.20gx%.20g",
radius,sigma);
kernel_info=AcquireKernelInfo(geometry,exception);
if (kernel_info == (KernelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
c1=pow(SSIMK1*SSIML,2.0);
artifact=GetImageArtifact(image,"compare:ssim-k1");
if (artifact != (const char *) NULL)
c1=pow(StringToDouble(artifact,(char **) NULL)*SSIML,2.0);
c2=pow(SSIMK2*SSIML,2.0);
artifact=GetImageArtifact(image,"compare:ssim-k2");
if (artifact != (const char *) NULL)
c2=pow(StringToDouble(artifact,(char **) NULL)*SSIML,2.0);
status=MagickTrue;
area=0.0;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,reconstruct_image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
double
channel_distortion[MaxPixelChannels+1];
const Quantum
*magick_restrict p,
*magick_restrict q;
size_t
local_area = 0;
ssize_t
i,
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) kernel_info->width/2L),y-
((ssize_t) kernel_info->height/2L),columns+kernel_info->width,
kernel_info->height,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,-((ssize_t) kernel_info->width/
2L),y-((ssize_t) kernel_info->height/2L),columns+kernel_info->width,
kernel_info->height,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
{
status=MagickFalse;
continue;
}
(void) memset(channel_distortion,0,sizeof(channel_distortion));
for (x=0; x < (ssize_t) columns; x++)
{
double
x_pixel_mu[MaxPixelChannels+1],
x_pixel_sigma_squared[MaxPixelChannels+1],
xy_sigma[MaxPixelChannels+1],
y_pixel_mu[MaxPixelChannels+1],
y_pixel_sigma_squared[MaxPixelChannels+1];
const Quantum
*magick_restrict reference,
*magick_restrict target;
MagickRealType
*k;
ssize_t
v;
if ((GetPixelReadMask(image,p) <= (QuantumRange/2)) ||
(GetPixelReadMask(reconstruct_image,q) <= (QuantumRange/2)))
{
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
continue;
}
(void) memset(x_pixel_mu,0,sizeof(x_pixel_mu));
(void) memset(x_pixel_sigma_squared,0,sizeof(x_pixel_sigma_squared));
(void) memset(xy_sigma,0,sizeof(xy_sigma));
(void) memset(x_pixel_sigma_squared,0,sizeof(y_pixel_sigma_squared));
(void) memset(y_pixel_mu,0,sizeof(y_pixel_mu));
(void) memset(y_pixel_sigma_squared,0,sizeof(y_pixel_sigma_squared));
k=kernel_info->values;
reference=p;
target=q;
for (v=0; v < (ssize_t) kernel_info->height; v++)
{
ssize_t
u;
for (u=0; u < (ssize_t) kernel_info->width; u++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
x_pixel,
y_pixel;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(
reconstruct_image,channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
x_pixel=QuantumScale*reference[i];
x_pixel_mu[i]+=(*k)*x_pixel;
x_pixel_sigma_squared[i]+=(*k)*x_pixel*x_pixel;
y_pixel=QuantumScale*
GetPixelChannel(reconstruct_image,channel,target);
y_pixel_mu[i]+=(*k)*y_pixel;
y_pixel_sigma_squared[i]+=(*k)*y_pixel*y_pixel;
xy_sigma[i]+=(*k)*x_pixel*y_pixel;
}
k++;
reference+=GetPixelChannels(image);
target+=GetPixelChannels(reconstruct_image);
}
reference+=GetPixelChannels(image)*columns;
target+=GetPixelChannels(reconstruct_image)*columns;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
ssim,
x_pixel_mu_squared,
x_pixel_sigmas_squared,
xy_mu,
xy_sigmas,
y_pixel_mu_squared,
y_pixel_sigmas_squared;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(
reconstruct_image,channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
x_pixel_mu_squared=x_pixel_mu[i]*x_pixel_mu[i];
y_pixel_mu_squared=y_pixel_mu[i]*y_pixel_mu[i];
xy_mu=x_pixel_mu[i]*y_pixel_mu[i];
xy_sigmas=xy_sigma[i]-xy_mu;
x_pixel_sigmas_squared=x_pixel_sigma_squared[i]-x_pixel_mu_squared;
y_pixel_sigmas_squared=y_pixel_sigma_squared[i]-y_pixel_mu_squared;
ssim=((2.0*xy_mu+c1)*(2.0*xy_sigmas+c2))/
((x_pixel_mu_squared+y_pixel_mu_squared+c1)*
(x_pixel_sigmas_squared+y_pixel_sigmas_squared+c2));
channel_distortion[i]+=ssim;
channel_distortion[CompositePixelChannel]+=ssim;
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
local_area++;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetStructuralSimilarityDistortion)
#endif
{
area+=local_area;
for (i=0; i <= MaxPixelChannels; i++)
distortion[i]+=channel_distortion[i];
}
}
image_view=DestroyCacheView(image_view);
reconstruct_view=DestroyCacheView(reconstruct_view);
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel = GetPixelChannelChannel(image,j);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0))
continue;
distortion[j]/=area;
}
distortion[CompositePixelChannel]/=area;
distortion[CompositePixelChannel]/=(double) GetImageChannels(image);
kernel_info=DestroyKernelInfo(kernel_info);
return(status);
}
static MagickBooleanType GetStructuralDisimilarityDistortion(const Image *image,
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
i;
status=GetStructuralSimilarityDistortion(image,reconstruct_image,
distortion,exception);
for (i=0; i <= MaxPixelChannels; i++)
distortion[i]=(1.0-(distortion[i]))/2.0;
return(status);
}
MagickExport MagickBooleanType GetImageDistortion(Image *image,
const Image *reconstruct_image,const MetricType metric,double *distortion,
ExceptionInfo *exception)
{
double
*channel_distortion;
MagickBooleanType
status;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
assert(distortion != (double *) NULL);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*distortion=0.0;
/*
Get image distortion.
*/
length=MaxPixelChannels+1UL;
channel_distortion=(double *) AcquireQuantumMemory(length,
sizeof(*channel_distortion));
if (channel_distortion == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) memset(channel_distortion,0,length*
sizeof(*channel_distortion));
switch (metric)
{
case AbsoluteErrorMetric:
{
status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion,
exception);
break;
}
case FuzzErrorMetric:
{
status=GetFuzzDistortion(image,reconstruct_image,channel_distortion,
exception);
break;
}
case MeanAbsoluteErrorMetric:
{
status=GetMeanAbsoluteDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case MeanErrorPerPixelErrorMetric:
{
status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion,
exception);
break;
}
case MeanSquaredErrorMetric:
{
status=GetMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case NormalizedCrossCorrelationErrorMetric:
default:
{
status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PeakAbsoluteErrorMetric:
{
status=GetPeakAbsoluteDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PeakSignalToNoiseRatioErrorMetric:
{
status=GetPeakSignalToNoiseRatio(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PerceptualHashErrorMetric:
{
status=GetPerceptualHashDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case RootMeanSquaredErrorMetric:
{
status=GetRootMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case StructuralSimilarityErrorMetric:
{
status=GetStructuralSimilarityDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case StructuralDissimilarityErrorMetric:
{
status=GetStructuralDisimilarityDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
}
*distortion=channel_distortion[CompositePixelChannel];
channel_distortion=(double *) RelinquishMagickMemory(channel_distortion);
(void) FormatImageProperty(image,"distortion","%.*g",GetMagickPrecision(),
*distortion);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e D i s t o r t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageDistortions() compares the pixel channels of an image to a
% reconstructed image and returns the specified distortion metric for each
% channel.
%
% The format of the GetImageDistortions method is:
%
% double *GetImageDistortions(const Image *image,
% const Image *reconstruct_image,const MetricType metric,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o metric: the metric.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport double *GetImageDistortions(Image *image,
const Image *reconstruct_image,const MetricType metric,
ExceptionInfo *exception)
{
double
*channel_distortion;
MagickBooleanType
status;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
/*
Get image distortion.
*/
length=MaxPixelChannels+1UL;
channel_distortion=(double *) AcquireQuantumMemory(length,
sizeof(*channel_distortion));
if (channel_distortion == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) memset(channel_distortion,0,length*
sizeof(*channel_distortion));
status=MagickTrue;
switch (metric)
{
case AbsoluteErrorMetric:
{
status=GetAbsoluteDistortion(image,reconstruct_image,channel_distortion,
exception);
break;
}
case FuzzErrorMetric:
{
status=GetFuzzDistortion(image,reconstruct_image,channel_distortion,
exception);
break;
}
case MeanAbsoluteErrorMetric:
{
status=GetMeanAbsoluteDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case MeanErrorPerPixelErrorMetric:
{
status=GetMeanErrorPerPixel(image,reconstruct_image,channel_distortion,
exception);
break;
}
case MeanSquaredErrorMetric:
{
status=GetMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case NormalizedCrossCorrelationErrorMetric:
default:
{
status=GetNormalizedCrossCorrelationDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PeakAbsoluteErrorMetric:
{
status=GetPeakAbsoluteDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PeakSignalToNoiseRatioErrorMetric:
{
status=GetPeakSignalToNoiseRatio(image,reconstruct_image,
channel_distortion,exception);
break;
}
case PerceptualHashErrorMetric:
{
status=GetRootMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case RootMeanSquaredErrorMetric:
{
status=GetRootMeanSquaredDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case StructuralSimilarityErrorMetric:
{
status=GetStructuralSimilarityDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
case StructuralDissimilarityErrorMetric:
{
status=GetStructuralDisimilarityDistortion(image,reconstruct_image,
channel_distortion,exception);
break;
}
}
if (status == MagickFalse)
{
channel_distortion=(double *) RelinquishMagickMemory(channel_distortion);
return((double *) NULL);
}
return(channel_distortion);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s I m a g e s E q u a l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsImagesEqual() compare the pixels of two images and returns immediately
% if any pixel is not identical.
%
% The format of the IsImagesEqual method is:
%
% MagickBooleanType IsImagesEqual(const Image *image,
% const Image *reconstruct_image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType IsImagesEqual(const Image *image,
const Image *reconstruct_image,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
size_t
columns,
rows;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
for (y=0; y < (ssize_t) rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q;
ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
break;
for (x=0; x < (ssize_t) columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=fabs((double) (p[i]-(double) GetPixelChannel(reconstruct_image,
channel,q)));
if (distance >= MagickEpsilon)
break;
}
if (i < (ssize_t) GetPixelChannels(image))
break;
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
if (x < (ssize_t) columns)
break;
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
return(y < (ssize_t) rows ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C o l o r M e t r i c %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageColorMetric() measures the difference between colors at each pixel
% location of two images. A value other than 0 means the colors match
% exactly. Otherwise an error measure is computed by summing over all
% pixels in an image the distance squared in RGB space between each image
% pixel and its corresponding pixel in the reconstruct image. The error
% measure is assigned to these image members:
%
% o mean_error_per_pixel: The mean error for any single pixel in
% the image.
%
% o normalized_mean_error: The normalized mean quantization error for
% any single pixel in the image. This distance measure is normalized to
% a range between 0 and 1. It is independent of the range of red, green,
% and blue values in the image.
%
% o normalized_maximum_error: The normalized maximum quantization
% error for any single pixel in the image. This distance measure is
% normalized to a range between 0 and 1. It is independent of the range
% of red, green, and blue values in your image.
%
% A small normalized mean square error, accessed as
% image->normalized_mean_error, suggests the images are very similar in
% spatial layout and color.
%
% The format of the SetImageColorMetric method is:
%
% MagickBooleanType SetImageColorMetric(Image *image,
% const Image *reconstruct_image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o reconstruct_image: the reconstruct image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageColorMetric(Image *image,
const Image *reconstruct_image,ExceptionInfo *exception)
{
CacheView
*image_view,
*reconstruct_view;
double
area,
maximum_error,
mean_error,
mean_error_per_pixel;
MagickBooleanType
status;
size_t
columns,
rows;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(reconstruct_image != (const Image *) NULL);
assert(reconstruct_image->signature == MagickCoreSignature);
area=0.0;
maximum_error=0.0;
mean_error_per_pixel=0.0;
mean_error=0.0;
rows=MagickMax(image->rows,reconstruct_image->rows);
columns=MagickMax(image->columns,reconstruct_image->columns);
image_view=AcquireVirtualCacheView(image,exception);
reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
for (y=0; y < (ssize_t) rows; y++)
{
const Quantum
*magick_restrict p,
*magick_restrict q;
ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
distance;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait reconstruct_traits = GetPixelChannelTraits(reconstruct_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(reconstruct_traits == UndefinedPixelTrait) ||
((reconstruct_traits & UpdatePixelTrait) == 0))
continue;
distance=fabs((double) (p[i]-(double) GetPixelChannel(reconstruct_image,
channel,q)));
if (distance >= MagickEpsilon)
{
mean_error_per_pixel+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
}
area++;
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(reconstruct_image);
}
}
reconstruct_view=DestroyCacheView(reconstruct_view);
image_view=DestroyCacheView(image_view);
image->error.mean_error_per_pixel=(double) (mean_error_per_pixel/area);
image->error.normalized_mean_error=(double) (QuantumScale*QuantumScale*
mean_error/area);
image->error.normalized_maximum_error=(double) (QuantumScale*maximum_error);
status=image->error.mean_error_per_pixel == 0.0 ? MagickTrue : MagickFalse;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S i m i l a r i t y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SimilarityImage() compares the reference image of the image and returns the
% best match offset. In addition, it returns a similarity image such that an
% exact match location is completely white and if none of the pixels match,
% black, otherwise some gray level in-between.
%
% The format of the SimilarityImageImage method is:
%
% Image *SimilarityImage(const Image *image,const Image *reference,
% const MetricType metric,const double similarity_threshold,
% RectangleInfo *offset,double *similarity,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o reference: find an area of the image that closely resembles this image.
%
% o metric: the metric.
%
% o similarity_threshold: minimum distortion for (sub)image match.
%
% o offset: the best match offset of the reference image within the image.
%
% o similarity: the computed similarity between the images.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_HDRI_SUPPORT) && defined(MAGICKCORE_FFTW_DELEGATE)
static Image *CrossCorrelationImage(const Image *alpha_image,
const Image *beta_image,ExceptionInfo *exception)
{
Image
*clone_image,
*complex_conjugate,
*complex_multiplication,
*cross_correlation,
*fft_images;
/*
Take the FFT of beta image.
*/
clone_image=CloneImage(beta_image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return(clone_image);
(void) SetImageArtifact(clone_image,"fourier:normalize","inverse");
fft_images=ForwardFourierTransformImage(clone_image,MagickFalse,
exception);
clone_image=DestroyImageList(clone_image);
if (fft_images == (Image *) NULL)
return(fft_images);
/*
Take the complex conjugate of beta image.
*/
complex_conjugate=ComplexImages(fft_images,ConjugateComplexOperator,
exception);
fft_images=DestroyImageList(fft_images);
if (complex_conjugate == (Image *) NULL)
return(complex_conjugate);
/*
Take the FFT of the alpha image.
*/
clone_image=CloneImage(alpha_image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
{
complex_conjugate=DestroyImageList(complex_conjugate);
return(clone_image);
}
(void) SetImageArtifact(clone_image,"fourier:normalize","inverse");
fft_images=ForwardFourierTransformImage(clone_image,MagickFalse,exception);
clone_image=DestroyImageList(clone_image);
if (fft_images == (Image *) NULL)
{
complex_conjugate=DestroyImageList(complex_conjugate);
return(fft_images);
}
complex_conjugate->next->next=fft_images;
/*
Do complex multiplication.
*/
(void) SetImageArtifact(complex_conjugate,"compose:clamp","false");
complex_multiplication=ComplexImages(complex_conjugate,
MultiplyComplexOperator,exception);
complex_conjugate=DestroyImageList(complex_conjugate);
if (fft_images == (Image *) NULL)
return(fft_images);
/*
Do the IFT and return the cross-correlation result.
*/
cross_correlation=InverseFourierTransformImage(complex_multiplication,
complex_multiplication->next,MagickFalse,exception);
complex_multiplication=DestroyImageList(complex_multiplication);
return(cross_correlation);
}
static Image *NCCDivideImage(const Image *alpha_image,const Image *beta_image,
ExceptionInfo *exception)
{
CacheView
*alpha_view,
*beta_view;
Image
*divide_image;
MagickBooleanType
status;
ssize_t
y;
/*
Divide one image into another.
*/
divide_image=CloneImage(alpha_image,0,0,MagickTrue,exception);
if (divide_image == (Image *) NULL)
return(divide_image);
status=MagickTrue;
alpha_view=AcquireAuthenticCacheView(divide_image,exception);
beta_view=AcquireVirtualCacheView(beta_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(beta_image,divide_image,divide_image->rows,1)
#endif
for (y=0; y < (ssize_t) divide_image->rows; y++)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(beta_view,0,y,beta_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(alpha_view,0,y,divide_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) divide_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(divide_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(divide_image,i);
PixelTrait traits = GetPixelChannelTraits(divide_image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (fabs(p[i]) >= MagickEpsilon)
q[i]*=PerceptibleReciprocal(QuantumScale*p[i]);
}
p+=GetPixelChannels(beta_image);
q+=GetPixelChannels(divide_image);
}
if (SyncCacheViewAuthenticPixels(alpha_view,exception) == MagickFalse)
status=MagickFalse;
}
beta_view=DestroyCacheView(beta_view);
alpha_view=DestroyCacheView(alpha_view);
if (status == MagickFalse)
divide_image=DestroyImage(divide_image);
return(divide_image);
}
static MagickBooleanType NCCMaximaImage(const Image *image,double *maxima,
RectangleInfo *offset,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
/*
Identify the maxima value in the image and its location.
*/
status=MagickTrue;
*maxima=0.0;
offset->x=0;
offset->y=0;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*magick_restrict p;
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
sum = 0.0;
ssize_t
channels = 0,
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;
sum+=p[i];
channels++;
}
if ((channels != 0) && ((sum/channels) > *maxima))
{
*maxima=sum/channels;
offset->x=x;
offset->y=y;
}
p+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType NCCMultiplyImage(Image *image,const double factor,
const ChannelStatistics *channel_statistics,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
/*
Multiply each pixel by a factor.
*/
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
*magick_restrict q;
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++)
{
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 (channel_statistics != (const ChannelStatistics *) NULL)
q[i]*=QuantumScale*channel_statistics[channel].standard_deviation;
q[i]*=factor;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
static Image *NCCSquareImage(const Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
Image
*square_image;
MagickBooleanType
status;
ssize_t
y;
/*
Square each pixel in the image.
*/
square_image=CloneImage(image,0,0,MagickTrue,exception);
if (square_image == (Image *) NULL)
return(square_image);
status=MagickTrue;
image_view=AcquireAuthenticCacheView(square_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(square_image,square_image,square_image->rows,1)
#endif
for (y=0; y < (ssize_t) square_image->rows; y++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,square_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) square_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(square_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(square_image,i);
PixelTrait traits = GetPixelChannelTraits(square_image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]*=QuantumScale*q[i];
}
q+=GetPixelChannels(square_image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
square_image=DestroyImage(square_image);
return(square_image);
}
static Image *NCCSubtractImageMean(const Image *alpha_image,
const Image *beta_image,const ChannelStatistics *channel_statistics,
ExceptionInfo *exception)
{
CacheView
*beta_view,
*image_view;
Image
*gamma_image;
MagickBooleanType
status;
ssize_t
y;
/*
Subtract the image mean and pad.
*/
gamma_image=CloneImage(beta_image,alpha_image->columns,alpha_image->rows,
MagickTrue,exception);
if (gamma_image == (Image *) NULL)
return(gamma_image);
status=MagickTrue;
image_view=AcquireAuthenticCacheView(gamma_image,exception);
beta_view=AcquireVirtualCacheView(beta_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(beta_image,gamma_image,gamma_image->rows,1)
#endif
for (y=0; y < (ssize_t) gamma_image->rows; y++)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(beta_view,0,y,beta_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,gamma_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) gamma_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(gamma_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(gamma_image,i);
PixelTrait traits = GetPixelChannelTraits(gamma_image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if ((x >= (ssize_t) beta_image->columns) ||
(y >= (ssize_t) beta_image->rows))
q[i]=(Quantum) 0;
else
q[i]=p[i]-channel_statistics[channel].mean;
}
p+=GetPixelChannels(beta_image);
q+=GetPixelChannels(gamma_image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
beta_view=DestroyCacheView(beta_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
gamma_image=DestroyImage(gamma_image);
return(gamma_image);
}
static Image *NCCUnityImage(const Image *alpha_image,const Image *beta_image,
ExceptionInfo *exception)
{
CacheView
*image_view;
Image
*unity_image;
MagickBooleanType
status;
ssize_t
y;
/*
Create a padded unity image.
*/
unity_image=CloneImage(alpha_image,alpha_image->columns,alpha_image->rows,
MagickTrue,exception);
if (unity_image == (Image *) NULL)
return(unity_image);
status=MagickTrue;
image_view=AcquireAuthenticCacheView(unity_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(unity_image,unity_image,unity_image->rows,1)
#endif
for (y=0; y < (ssize_t) unity_image->rows; y++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,unity_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) unity_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(unity_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(unity_image,i);
PixelTrait traits = GetPixelChannelTraits(unity_image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=QuantumRange;
if ((x >= (ssize_t) beta_image->columns) ||
(y >= (ssize_t) beta_image->rows))
q[i]=(Quantum) 0;
}
q+=GetPixelChannels(unity_image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
unity_image=DestroyImage(unity_image);
return(unity_image);
}
static Image *NCCVarianceImage(Image *alpha_image,const Image *beta_image,
ExceptionInfo *exception)
{
CacheView
*beta_view,
*image_view;
Image
*variance_image;
MagickBooleanType
status;
ssize_t
y;
/*
Compute the variance of the two images.
*/
variance_image=CloneImage(alpha_image,0,0,MagickTrue,exception);
if (variance_image == (Image *) NULL)
return(variance_image);
status=MagickTrue;
image_view=AcquireAuthenticCacheView(variance_image,exception);
beta_view=AcquireVirtualCacheView(beta_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(beta_image,variance_image,variance_image->rows,1)
#endif
for (y=0; y < (ssize_t) variance_image->rows; y++)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(beta_view,0,y,beta_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,variance_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) variance_image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(variance_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(variance_image,i);
PixelTrait traits = GetPixelChannelTraits(variance_image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum((QuantumRange*sqrt(fabs((double) QuantumScale*
(q[i]-p[i])))))/sqrt((double) QuantumRange);
}
p+=GetPixelChannels(beta_image);
q+=GetPixelChannels(variance_image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
beta_view=DestroyCacheView(beta_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
variance_image=DestroyImage(variance_image);
return(variance_image);
}
static Image *NCCSimilarityImage(const Image *image,const Image *reference,
RectangleInfo *offset,double *similarity_metric,ExceptionInfo *exception)
{
#define DestroySimilarityResources() \
{ \
if (channel_statistics != (ChannelStatistics *) NULL) \
channel_statistics=(ChannelStatistics *) \
RelinquishMagickMemory(channel_statistics); \
if (beta_image != (Image *) NULL) \
beta_image=DestroyImage(beta_image); \
if (gamma_image != (Image *) NULL) \
gamma_image=DestroyImage(gamma_image); \
if (ncc_image != (Image *) NULL) \
ncc_image=DestroyImage(ncc_image); \
if (normalize_image != (Image *) NULL) \
normalize_image=DestroyImage(normalize_image); \
if (square_image != (Image *) NULL) \
square_image=DestroyImage(square_image); \
if (unity_image != (Image *) NULL) \
unity_image=DestroyImage(unity_image); \
}
#define ThrowSimilarityException() \
{ \
DestroySimilarityResources() \
return((Image *) NULL); \
}
ChannelStatistics
*channel_statistics = (ChannelStatistics *) NULL;
double
maxima = 0.0;
Image
*beta_image = (Image *) NULL,
*correlation_image = (Image *) NULL,
*gamma_image = (Image *) NULL,
*ncc_image = (Image *) NULL,
*normalize_image = (Image *) NULL,
*square_image = (Image *) NULL,
*unity_image = (Image *) NULL;
MagickBooleanType
status;
RectangleInfo
geometry;
/*
Accelerated correlation-based image similary using FFT local statistics.
Contributed by Fred Weinhaus.
*/
square_image=NCCSquareImage(image,exception);
if (square_image == (Image *) NULL)
ThrowSimilarityException();
unity_image=NCCUnityImage(image,reference,exception);
if (unity_image == (Image *) NULL)
ThrowSimilarityException();
/*
Compute the cross correlation of the square and unity images.
*/
ncc_image=CrossCorrelationImage(square_image,unity_image,exception);
square_image=DestroyImage(square_image);
if (ncc_image == (Image *) NULL)
ThrowSimilarityException();
status=NCCMultiplyImage(ncc_image,(double) QuantumRange*reference->columns*
reference->rows,(const ChannelStatistics *) NULL,exception);
if (status == MagickFalse)
ThrowSimilarityException();
/*
Compute the cross correlation of the source and unity images.
*/
gamma_image=CrossCorrelationImage(image,unity_image,exception);
unity_image=DestroyImage(unity_image);
if (gamma_image == (Image *) NULL)
ThrowSimilarityException();
square_image=NCCSquareImage(gamma_image,exception);
gamma_image=DestroyImage(gamma_image);
status=NCCMultiplyImage(square_image,(double) QuantumRange,
(const ChannelStatistics *) NULL,exception);
if (status == MagickFalse)
ThrowSimilarityException();
/*
Compute the variance of the two images.
*/
gamma_image=NCCVarianceImage(ncc_image,square_image,exception);
square_image=DestroyImage(square_image);
ncc_image=DestroyImage(ncc_image);
if (gamma_image == (Image *) NULL)
ThrowSimilarityException();
channel_statistics=GetImageStatistics(reference,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
ThrowSimilarityException();
/*
Subtract the image mean.
*/
status=NCCMultiplyImage(gamma_image,1.0,channel_statistics,exception);
if (status == MagickFalse)
ThrowSimilarityException();
normalize_image=NCCSubtractImageMean(image,reference,channel_statistics,
exception);
if (normalize_image == (Image *) NULL)
ThrowSimilarityException();
ncc_image=CrossCorrelationImage(image,normalize_image,exception);
normalize_image=DestroyImage(normalize_image);
if (ncc_image == (Image *) NULL)
ThrowSimilarityException();
/*
Divide the two images.
*/
beta_image=NCCDivideImage(ncc_image,gamma_image,exception);
ncc_image=DestroyImage(ncc_image);
gamma_image=DestroyImage(gamma_image);
if (beta_image == (Image *) NULL)
ThrowSimilarityException();
(void) ResetImagePage(beta_image,"0x0+0+0");
SetGeometry(image,&geometry);
geometry.width=image->columns-reference->columns;
geometry.height=image->rows-reference->rows;
/*
Crop padding.
*/
correlation_image=CropImage(beta_image,&geometry,exception);
beta_image=DestroyImage(beta_image);
if (correlation_image == (Image *) NULL)
ThrowSimilarityException();
(void) ResetImagePage(correlation_image,"0x0+0+0");
/*
Identify the maxima value in the image and its location.
*/
status=GrayscaleImage(correlation_image,AveragePixelIntensityMethod,
exception);
if (status == MagickFalse)
ThrowSimilarityException();
status=NCCMaximaImage(correlation_image,&maxima,offset,exception);
if (status == MagickFalse)
{
correlation_image=DestroyImage(correlation_image);
ThrowSimilarityException();
}
*similarity_metric=1.0-QuantumScale*maxima;
DestroySimilarityResources();
return(correlation_image);
}
#endif
static double GetSimilarityMetric(const Image *image,const Image *reference,
const MetricType metric,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
double
distortion;
Image
*similarity_image;
MagickBooleanType
status;
RectangleInfo
geometry;
SetGeometry(reference,&geometry);
geometry.x=x_offset;
geometry.y=y_offset;
similarity_image=CropImage(image,&geometry,exception);
if (similarity_image == (Image *) NULL)
return(0.0);
distortion=0.0;
status=GetImageDistortion(similarity_image,reference,metric,&distortion,
exception);
similarity_image=DestroyImage(similarity_image);
if (status == MagickFalse)
return(0.0);
return(distortion);
}
MagickExport Image *SimilarityImage(const Image *image,const Image *reference,
const MetricType metric,const double similarity_threshold,
RectangleInfo *offset,double *similarity_metric,ExceptionInfo *exception)
{
#define SimilarityImageTag "Similarity/Image"
CacheView
*similarity_view;
Image
*similarity_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
assert(offset != (RectangleInfo *) NULL);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
SetGeometry(reference,offset);
*similarity_metric=MagickMaximumValue;
#if defined(MAGICKCORE_HDRI_SUPPORT) && defined(MAGICKCORE_FFTW_DELEGATE)
if ((image->channels & ReadMaskChannel) != 0)
{
const char *artifact = GetImageArtifact(image,"compare:accelerate-ncc");
MagickBooleanType accelerate = (artifact != (const char *) NULL) &&
(IsStringTrue(artifact) == MagickFalse) ? MagickFalse : MagickTrue;
if ((accelerate != MagickFalse) &&
(metric == NormalizedCrossCorrelationErrorMetric))
{
similarity_image=NCCSimilarityImage(image,reference,offset,
similarity_metric,exception);
return(similarity_image);
}
}
#endif
similarity_image=CloneImage(image,image->columns-reference->columns+1,
image->rows-reference->rows+1,MagickTrue,exception);
if (similarity_image == (Image *) NULL)
return((Image *) NULL);
status=SetImageStorageClass(similarity_image,DirectClass,exception);
if (status == MagickFalse)
{
similarity_image=DestroyImage(similarity_image);
return((Image *) NULL);
}
(void) SetImageAlphaChannel(similarity_image,DeactivateAlphaChannel,
exception);
/*
Measure similarity of reference image against image.
*/
status=MagickTrue;
progress=0;
similarity_view=AcquireAuthenticCacheView(similarity_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) \
shared(progress,status,similarity_metric) \
magick_number_threads(image,image,image->rows-reference->rows+1,1)
#endif
for (y=0; y < (ssize_t) (image->rows-reference->rows+1); y++)
{
double
similarity;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp flush(similarity_metric)
#endif
if (*similarity_metric <= similarity_threshold)
continue;
q=GetCacheViewAuthenticPixels(similarity_view,0,y,similarity_image->columns,
1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) (image->columns-reference->columns+1); x++)
{
ssize_t
i;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp flush(similarity_metric)
#endif
if (*similarity_metric <= similarity_threshold)
break;
similarity=GetSimilarityMetric(image,reference,metric,x,y,exception);
if ((metric == NormalizedCrossCorrelationErrorMetric) ||
(metric == UndefinedErrorMetric))
similarity=1.0-similarity;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SimilarityImage)
#endif
if (similarity < *similarity_metric)
{
offset->x=x;
offset->y=y;
*similarity_metric=similarity;
}
if (metric == PerceptualHashErrorMetric)
similarity=MagickMin(0.01*similarity,1.0);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait similarity_traits=GetPixelChannelTraits(similarity_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(similarity_traits == UndefinedPixelTrait) ||
((similarity_traits & UpdatePixelTrait) == 0))
continue;
SetPixelChannel(similarity_image,channel,ClampToQuantum(QuantumRange-
QuantumRange*similarity),q);
}
q+=GetPixelChannels(similarity_image);
}
if (SyncCacheViewAuthenticPixels(similarity_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,SimilarityImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
similarity_view=DestroyCacheView(similarity_view);
if (status == MagickFalse)
similarity_image=DestroyImage(similarity_image);
return(similarity_image);
}
|
omp_num_threads.c | // Skip testing on 64 bit systems for now!
#ifndef __LP64__
#include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "omp_testsuite.h"
int
check_omp_num_threads (FILE * logFile)
{
int failed = 0;
int max_threads = 0;
int threads;
int nthreads;
/* first we check how many threads are available */
#pragma omp parallel
{
#pragma omp master
max_threads = omp_get_num_threads ();
}
/* we increase the number of threads from one to maximum: */
for (threads = 1; threads <= max_threads; threads++)
{
nthreads = 0;
#pragma omp parallel num_threads(threads) reduction(+:failed)
{
failed = failed + !(threads == omp_get_num_threads ());
#pragma omp atomic
nthreads += 1;
}
failed = failed + !(nthreads == threads);
}
return !failed;
}
int
crosscheck_omp_num_threads (FILE * logFile)
{
int failed = 0;
int max_threads = 0;
int threads;
int nthreads;
/* first we check how many threads are available */
#pragma omp parallel
{
#pragma omp master
max_threads = omp_get_num_threads ();
}
/* we increase the number of threads from one to maximum: */
for (threads = 1; threads <= max_threads; threads++)
{
nthreads = 0;
#pragma omp parallel reduction(+:failed)
{
failed = failed + !(threads == omp_get_num_threads ());
#pragma omp atomic
nthreads += 1;
}
failed = failed + !(nthreads == threads);
}
return !failed;
}
#else
#warning "Not tested on 64 bit systems"
#endif
|
LAGraph_pagerank3b.c | //------------------------------------------------------------------------------
// LAGraph_pagerank3b: pagerank using a real semiring
//------------------------------------------------------------------------------
/*
LAGraph: graph algorithms based on GraphBLAS
Copyright 2019 LAGraph Contributors.
(see Contributors.txt for a full list of Contributors; see
ContributionInstructions.txt for information on how you can Contribute to
this project).
All Rights Reserved.
NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH
CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR
PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF
THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH
RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.
Released under a BSD license, please see the LICENSE file distributed with
this Software or contact permission@sei.cmu.edu for full terms.
Created, in part, with funding and support from the United States
Government. (see Acknowledgments.txt file).
This program includes and/or can make use of certain third party source
code, object code, documentation and other files ("Third Party Software").
See LICENSE file for more details.
*/
// LAGraph_pagerank3b: Alternative PageRank implementation using a real
// semiring.
//
// This algorithm follows the specification given in the GAP Benchmark Suite:
// https://arxiv.org/abs/1508.03619
// For fastest results, the input matrix should be GrB_FP32, stored in
// GxB_BY_COL format.
#define LAGRAPH_EXPERIMENTAL_ASK_BEFORE_BENCHMARKING
#include "LAGraph.h"
#define LAGRAPH_FREE_ALL { \
GrB_free(&transpose_desc); \
GrB_free(&invmask_desc); \
GrB_free(&A); \
GrB_free(&G); \
GrB_free(&grb_d_out); \
GrB_free(&importance_vec); \
GrB_free(&grb_pr); \
};
// uncomment this to see the intermidiate resluts; lots of prints!!
//#undef NDEBUG
// uncomment this to see the timing info
#define PRINT_TIMING_INFO
GrB_Info LAGraph_pagerank3b // PageRank definition
(
GrB_Vector *result, // output: array of LAGraph_PageRank structs
GrB_Matrix A_input, // binary input graph, not modified
float damping_factor, // damping factor
unsigned long itermax, // maximum number of iterations
int* iters // output: number of iterations taken
)
{
GrB_Info info;
GrB_Index n;
GrB_Descriptor invmask_desc = NULL ;
GrB_Descriptor transpose_desc = NULL ;
GrB_Vector grb_d_out = NULL ;
GrB_Matrix A = NULL ;
#ifdef PRINT_TIMING_INFO
// start the timer
double tic [2] ;
LAGraph_tic (tic) ;
#endif
GrB_Vector importance_vec = NULL ;
GrB_Vector grb_pr = NULL;
GrB_Matrix G = NULL ; // a dense row of zeros zeroes(1,n)
GrB_Index ncols ; //number of columnns
LAGRAPH_OK(GrB_Matrix_ncols(&ncols , A_input));
LAGRAPH_OK(GrB_Matrix_nrows(&n, A_input));
GrB_Index nvals;
LAGRAPH_OK(GrB_Matrix_nvals(&nvals, A_input));
if (ncols != n)
{
return (GrB_DIMENSION_MISMATCH) ;
}
LAGRAPH_OK(GrB_Matrix_new (&G, GrB_FP32, n, n));
LAGRAPH_OK(GrB_Matrix_new (&A, GrB_FP32, n, n));
LAGRAPH_OK(GxB_set (A, GxB_FORMAT, GxB_BY_COL));
// G is zeros in last row
for (GrB_Index c = 0; c < n; c++){
LAGRAPH_OK(GrB_Matrix_setElement (G, 0.0, n-1, c));
}
#ifndef NDEBUG
int print_size = 5; //number of entries get printed
print_size = (print_size > n)? n : print_size;
// GxB_print (G, 3) ;
#endif
// A = A_input + G;
LAGRAPH_OK(GrB_eWiseAdd (A, NULL, NULL, GrB_PLUS_FP32, A_input, G, NULL));
GrB_free (&G) ;
#ifndef NDEBUG
// GxB_print (A, 3) ;
#endif
// Create complement descriptor
LAGRAPH_OK(GrB_Descriptor_new(&invmask_desc));
LAGRAPH_OK(GrB_Descriptor_set(invmask_desc, GrB_MASK, GrB_SCMP));
// Create transpose descriptor
LAGRAPH_OK(GrB_Descriptor_new(&transpose_desc));
LAGRAPH_OK(GrB_Descriptor_set(transpose_desc, GrB_INP0, GrB_TRAN));
LAGRAPH_OK(GrB_Descriptor_set(transpose_desc, GrB_OUTP, GrB_REPLACE));
// Matrix A row sum
// Stores the outbound degrees of all vertices
LAGRAPH_OK(GrB_Vector_new(&grb_d_out, GrB_FP32, n));
LAGRAPH_OK(GrB_reduce( grb_d_out, NULL, NULL, GxB_PLUS_FP32_MONOID,
A, NULL ));
#ifndef NDEBUG
GxB_print (grb_d_out, 1) ;
// GxB_print (A, 3) ;
#endif
// Iteration
// Initialize PR vector
LAGRAPH_OK(GrB_Vector_new(&grb_pr, GrB_FP32, n));
LAGRAPH_OK(GrB_Vector_new(&importance_vec, GrB_FP32, n));
// Teleport value
const float teleport = (1 - damping_factor) / n;
float tol = 1e-4;
float rdiff = 1 ; // first iteration is always done
GrB_Type type = GrB_FP32 ;
GrB_Index *dI = NULL ;
float *d_sp= NULL ;
GrB_Index d_nvals, d_size;
GrB_Index d_n;
bool jumbled ;
// d_sp <----- grb_d_out || export
#if GxB_IMPLEMENTATION >= GxB_VERSION (4,0,0)
LAGRAPH_OK (GxB_Vector_export_CSC (&grb_d_out, &type, &d_n, &d_size,
&d_nvals, &jumbled, &dI, (void **) (&d_sp), NULL)) ;
#else
LAGRAPH_OK (GxB_Vector_export (&grb_d_out, &type, &d_n, &d_nvals, &dI,
(void **) (&d_sp), NULL)) ;
#endif
// dens d_out
float *d_out = (float *) LAGraph_calloc (n, sizeof(float));
int nthreads = LAGraph_get_nthreads ( ) ;
nthreads = LAGRAPH_MIN (n , nthreads) ;
nthreads = LAGRAPH_MAX (nthreads, 1) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t i = 0 ; i < d_nvals; i++){
GrB_Index ind = (GrB_Index) dI[i];
d_out [ind] = d_sp [i];
}
free (d_sp);
free (dI);
#ifndef NDEBUG
for (int i = 0 ; i < print_size; i++){
printf("d_out [%d]=%g\n", i, d_out [i]);
}
#endif
// initializing pr
float *pr = (float *) malloc (n*sizeof(float));
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int i = 0; i < n ; i++){
pr [i] = 1.0/n;
}
#ifndef NDEBUG
for (int i = 0 ; i < print_size ; i++){
printf("pr[%d]=%f\n", i, pr [i]);
}
#endif
float *oldpr = (float *) malloc (n*sizeof(float));
#if GxB_IMPLEMENTATION >= GxB_VERSION (4,0,0)
// no need for I
#else
// initailze the dense indices
GrB_Index *I = LAGraph_malloc(n, sizeof(GrB_Index));
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (GrB_Index j = 0; j < n; j++){
I[j] = j;
}
#endif
#ifdef PRINT_TIMING_INFO
// stop the timer
double t1 = LAGraph_toc (tic);
printf ("\ninitialization time: %12.6e (sec)\n",t1);
LAGraph_tic (tic);
#endif
for ((*iters) = 0 ; (*iters) < itermax && rdiff > tol ; (*iters)++) {
// oldpr = pr; deep copy
//GrB_Vector_dup(&oldpr, pr);
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int i = 0; i < n ; i++){
oldpr [i] = pr [i];
}
// Importance calculation
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int i = 0 ; i < n; i++){
if (d_out [i] != 0){
pr [i] = damping_factor * pr [i] / d_out [i];
}
else{
pr [i] = 0;
}
}
#ifndef NDEBUG
for (int i = 0 ; i < print_size; i++){
printf (" pr [%d] = %f\n", i, pr [i]);
}
#endif
// importance_vec <----- pr
#if GxB_IMPLEMENTATION >= GxB_VERSION (4,0,0)
LAGRAPH_OK (GxB_Vector_import_Full (&importance_vec, GrB_FP32, n,
(void **) (&pr), NULL)) ;
#else
LAGRAPH_OK (GxB_Vector_import (&importance_vec, GrB_FP32, n, n, &I,
(void **) (&pr), NULL)) ;
#endif
#ifndef NDEBUG
printf ("after importance_vec import\n");
GxB_print (importance_vec, 2) ;
#endif
// Calculate total PR of all inbound vertices
// importance_vec = A' * importance_vec
LAGRAPH_OK(GrB_mxv( importance_vec, NULL, NULL, GxB_PLUS_TIMES_FP32,
A, importance_vec, transpose_desc ));
#ifndef NDEBUG
printf ("==============2\n");
printf ("after mxv\n");
GxB_print (importance_vec, 1) ;
#endif
GrB_Index nvals_exp;
// pr <----- importance_vec
GrB_Type ivtype;
#if GxB_IMPLEMENTATION >= GxB_VERSION (4,0,0)
LAGRAPH_OK (GxB_Vector_export_Full (&importance_vec, &ivtype, &n,
(void **) (&pr), NULL)) ;
#else
LAGRAPH_OK (GxB_Vector_export (&importance_vec, &ivtype, &n,&nvals_exp,
&I, (void **) (&pr), NULL)) ;
#endif
// assert (nvals_exp == n );
// PageRank summarization
// Add teleport, importance_vec, and dangling_vec components together
// pr = (1-df)/n + pr
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int i = 0 ; i < n; i++){
pr [i] += teleport;
}
#ifndef NDEBUG
for (int i = 0 ; i < print_size; i++){
printf (" pr [%d] = %f\n", i, pr [i]);
}
#endif
//----------------------------------------------------------------------
// rdiff = sum ((oldpr-pr).^2)
//----------------------------------------------------------------------
rdiff = 0;
// norm (oldpr pr, 1)
#pragma omp parallel for num_threads(nthreads) reduction(+:rdiff)
for (int i = 0 ; i < n; i++){
float d = (oldpr [i] - pr [i]);
d = (d > 0 ? d : -d); //abs(d)
rdiff += d;
}
#ifndef NDEBUG
printf("---------------------------iters %d rdiff=%f\n",*iters, rdiff);
#endif
}
#ifdef PRINT_TIMING_INFO
// stop the timer
double t2 = LAGraph_toc (tic);
printf ("compuatatin time: %12.6e (sec) ratio (comp/init): %f\n\n",
t2, t2/t1);
#endif
// grb_pr<----- pr || import back
#if GxB_IMPLEMENTATION >= GxB_VERSION (4,0,0)
LAGRAPH_OK (GxB_Vector_import_Full (&grb_pr, GrB_FP32, n,
(void **) (&pr), NULL)) ;
#else
LAGRAPH_OK (GxB_Vector_import (&grb_pr, GrB_FP32, n, n, &I,
(void **) (&pr), NULL)) ;
free(I);
#endif
(*result) = grb_pr;
free (oldpr);
return (GrB_SUCCESS);
}
|
math_utils_inl.h | /*
*
* Copyright (c) 2014, Nicola Pezzotti (Delft University of Technology)
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Delft University of Technology.
* 4. Neither the name of the Delft University of Technology 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 NICOLA PEZZOTTI ''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 NICOLA PEZZOTTI 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 MATH_INL
#define MATH_INL
#include "hdi/utils/math_utils.h"
#include <assert.h>
#include <cmath>
#include <stdexcept>
#include <limits>
#ifdef __USE_GCD__
#include <dispatch/dispatch.h>
#endif
namespace hdi{
namespace utils{
template <typename T>
T euclideanDistance(const std::vector<T>& a, const std::vector<T>& b){
assert(a.size() == b.size());
assert(a.size() != 0);
double res(0);
for(int i = 0; i < a.size(); ++i){
double diff(a[i] - b[i]);
res += diff*diff;
}
return static_cast<T>(std::sqrt(res));
}
template <typename T>
T euclideanDistanceSquared(const std::vector<T>& a, const std::vector<T>& b){
assert(a.size() == b.size());
assert(a.size() != 0);
double res(0);
for(int i = 0; i < a.size(); ++i){
double diff(a[i] - b[i]);
res += diff*diff;
}
return static_cast<T>(res);
}
template <typename T>
T euclideanDistance(typename std::vector<T>::const_iterator a_begin, typename std::vector<T>::const_iterator a_end, typename std::vector<T>::const_iterator b_begin, typename std::vector<T>::const_iterator b_end){
assert(std::distance(a_begin, a_end) == std::distance(b_begin, b_end));
assert(std::distance(a_begin, a_end) != 0);
double res(0);
for(; a_begin != a_end; ++a_begin, ++b_begin){
double diff(*a_begin - *b_begin);
res += diff*diff;
}
return static_cast<T>(std::sqrt(res));
}
template <typename T>
T euclideanDistanceSquared(typename std::vector<T>::const_iterator a_begin, typename std::vector<T>::const_iterator a_end, typename std::vector<T>::const_iterator b_begin, typename std::vector<T>::const_iterator b_end){
assert(std::distance(a_begin, a_end) == std::distance(b_begin, b_end));
assert(std::distance(a_begin, a_end) != 0);
double res(0);
for(; a_begin != a_end; ++a_begin, ++b_begin){
double diff(*a_begin - *b_begin);
res += diff*diff;
}
return static_cast<T>(res);
}
template <typename T>
T euclideanDistance(const T* a_begin, const T* a_end, const T* b_begin, const T* b_end){
assert(std::distance(a_begin, a_end) == std::distance(b_begin, b_end));
assert(std::distance(a_begin, a_end) != 0);
double res(0);
for(; a_begin != a_end; ++a_begin, ++b_begin){
double diff(*a_begin - *b_begin);
res += diff*diff;
}
return static_cast<T>(std::sqrt(res));
}
template <typename T>
T euclideanDistanceSquared(const T* a_begin, const T* a_end, const T* b_begin, const T* b_end){
assert(std::distance(a_begin, a_end) == std::distance(b_begin, b_end));
assert(std::distance(a_begin, a_end) != 0);
double res(0);
for(; a_begin != a_end; ++a_begin, ++b_begin){
double diff(*a_begin - *b_begin);
res += diff*diff;
}
return static_cast<T>(res);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template <typename vector_type, typename sparse_matrix_type>
void computeHeterogeneity(const sparse_matrix_type& matrix, vector_type& res){
auto n = matrix.size();
res.resize(n);
#ifdef __USE_GCD__
std::cout << "GCD dispatch, mat_utils_onl 131.\n";
dispatch_apply(matrix.size(), dispatch_get_global_queue(0, 0), ^(size_t i) {
#else
#pragma omp parallel for
for(int i = 0; i < matrix.size(); ++i){
#endif //__USE_GCD__
vector_type distr(n,0);
distr[i] = n;
computeStationaryDistribution(matrix,&distr,5,1);
res[i] = distr[i]/n;
}
#ifdef __USE_GCD__
);
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Vector>
double computeGaussianDistribution(typename Vector::const_iterator distances_begin, typename Vector::const_iterator distances_end, typename Vector::iterator distribution_begin, typename Vector::iterator distribution_end, double sigma){
assert(sigma > 0);
const int size(static_cast<int>(std::distance(distances_begin, distances_end)));
if(size != std::distance(distribution_begin, distribution_end) || size == 0){
throw std::logic_error("Invalid containers");
}
auto distance_iter = distances_begin;
auto distribution_iter = distribution_begin;
double mult(-1. / (2 * sigma * sigma));
double sum(0);
for(int idx = 0; distance_iter != distances_end; ++distance_iter, ++distribution_iter, ++idx){
*distribution_iter = std::exp((*distance_iter) * (*distance_iter) * mult);
sum += *distribution_iter;
}
for(auto distribution_iter = distribution_begin; distribution_iter != distribution_end; ++distribution_iter){
(*distribution_iter) /= sum;
}
return sum;
}
template <typename Vector>
double computeGaussianDistributionWithFixedPerplexity(typename Vector::const_iterator distances_begin, typename Vector::const_iterator distances_end, typename Vector::iterator distribution_begin, typename Vector::iterator distribution_end, double perplexity, int max_iterations, double tol, int ignore){
const int size(static_cast<int>(std::distance(distances_begin, distances_end)));
if(size != std::distance(distribution_begin, distribution_end) || size == 0){
throw std::logic_error("Invalid containers");
}
bool found = false;
double beta = 1.;
double sigma = std::sqrt(1/(2*beta));
double min_beta = -std::numeric_limits<double>::max();
double max_beta = std::numeric_limits<double>::max();
const double double_max = std::numeric_limits<double>::max();
// Iterate until we found a good perplexity
int iter = 0;
double sum_distribution = std::numeric_limits<double>::min();
while(!found && iter < max_iterations) {
// Compute Gaussian kernel row
sum_distribution = std::numeric_limits<double>::min();
{
auto distance_iter = distances_begin;
auto distribution_iter = distribution_begin;
for(int idx = 0; distance_iter != distances_end; ++distance_iter, ++distribution_iter, ++idx){
if(idx == ignore){
(*distribution_iter) = 0;
continue;
}
double v = exp(-beta * (*distance_iter));
sigma = std::sqrt(1/(2*beta));
//double v = exp(- (*distance_iter) / (2*sigma*sigma));
(*distribution_iter) = static_cast<typename Vector::value_type>(v);
sum_distribution += v;
}
}
double H = .0; //entropy
{
auto distance_iter = distances_begin;
auto distribution_iter = distribution_begin;
for(int idx = 0; distance_iter != distances_end; ++distance_iter, ++distribution_iter, ++idx){
if(idx == ignore)
continue;
H += beta * ((*distance_iter) * (*distribution_iter));
}
H = (H / sum_distribution) + log(sum_distribution);
}
// Evaluate whether the entropy is within the tolerance level
double Hdiff = H - log(perplexity);
if(Hdiff < tol && -Hdiff < tol){
found = true;
}
else{
if(Hdiff > 0){
min_beta = beta;
if(max_beta == double_max || max_beta == -double_max)
beta *= 2.0;
else
beta = (beta + max_beta) / 2.0;
}
else{
max_beta = beta;
if(min_beta == -double_max || min_beta == double_max)
beta /= 2.0;
else
beta = (beta + min_beta) / 2.0;
}
}
iter++;
}
if(!found){
double v = 1./(size+((ignore<0||ignore>=size)?0:-1));
for(auto distribution_iter = distribution_begin; distribution_iter != distribution_end; ++distribution_iter){
(*distribution_iter) = v;
}
return 0;
}
for(auto distribution_iter = distribution_begin; distribution_iter != distribution_end; ++distribution_iter){
(*distribution_iter) /= sum_distribution;
}
return sigma;
}
template <typename Vector>
double computeGaussianDistributionWithFixedWeight(typename Vector::const_iterator distances_begin, typename Vector::const_iterator distances_end, typename Vector::iterator distribution_begin, typename Vector::iterator distribution_end, double weight, int max_iterations, double tol, int ignore){
const int size(static_cast<int>(std::distance(distances_begin, distances_end)));
if(size != std::distance(distribution_begin, distribution_end) || size == 0){
throw std::logic_error("Invalid containers");
}
bool found = false;
double beta = 1.;
double min_beta = -std::numeric_limits<double>::max();
double max_beta = std::numeric_limits<double>::max();
const double double_max = std::numeric_limits<double>::max();
// Iterate until we found a good perplexity
int iter = 0;
double sum_distribution = std::numeric_limits<double>::min();
while(!found && iter < max_iterations) {
// Compute Gaussian kernel row
sum_distribution = std::numeric_limits<double>::min();
{
auto distance_iter = distances_begin;
auto distribution_iter = distribution_begin;
for(int idx = 0; distance_iter != distances_end; ++distance_iter, ++distribution_iter, ++idx){
if(idx == ignore)
continue;
//double v = exp(-beta * (*distance_iter));
double sigma =std::sqrt(1/(2*beta));
double v = exp(- (*distance_iter) / (2*sigma*sigma));
(*distribution_iter) = static_cast<typename Vector::value_type>(v);
sum_distribution += v;
}
}
// Evaluate whether the weight is within the tolerance level
if(sum_distribution-weight < tol && weight-sum_distribution < tol){
found = true;
}
else{
if(sum_distribution > weight){
min_beta = beta;
if(max_beta == double_max || max_beta == -double_max)
beta *= 2.0;
else
beta = (beta + max_beta) / 2.0;
}
else{
max_beta = beta;
if(min_beta == -double_max || min_beta == double_max)
beta /= 2.0;
else
beta = (beta + min_beta) / 2.0;
}
}
iter++;
}
if(!found){
double v = 1./(size+((ignore<0||ignore>=size)?0:-1));
for(auto distribution_iter = distribution_begin; distribution_iter != distribution_end; ++distribution_iter){
(*distribution_iter) = v;
}
return 1;
}
for(auto distribution_iter = distribution_begin; distribution_iter != distribution_end; ++distribution_iter){
(*distribution_iter) /= sum_distribution;
}
return sum_distribution;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template <typename Vector>
double computeGaussianFunction(typename Vector::const_iterator distances_begin, typename Vector::const_iterator distances_end, typename Vector::iterator distribution_begin, typename Vector::iterator distribution_end, double sigma, double alpha){
assert(sigma > 0);
assert(alpha > 0);
const int size(static_cast<int>(std::distance(distances_begin, distances_end)));
if(size != std::distance(distribution_begin, distribution_end) || size == 0){
throw std::logic_error("Invalid containers");
}
auto distance_iter = distances_begin;
auto distribution_iter = distribution_begin;
double beta(-1. / (2 * sigma * sigma));
double sum(0);
for(int idx = 0; distance_iter != distances_end; ++distance_iter, ++distribution_iter, ++idx){
*distribution_iter = alpha*std::exp((*distance_iter) * (*distance_iter) * beta);
sum += *distribution_iter;
}
return sum;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
}
}
#endif
|
blas_dh.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.6 $
***********************************************************************EHEADER*/
#include "blas_dh.h"
#undef __FUNC__
#define __FUNC__ "matvec_euclid_seq"
void matvec_euclid_seq(int n, int *rp, int *cval, double *aval, double *x, double *y)
{
START_FUNC_DH
int i, j;
int from, to, col;
double sum;
if (np_dh > 1) SET_V_ERROR("only for sequential case!\n");
#ifdef USING_OPENMP_DH
#pragma omp parallel private(j, col, sum, from, to) \
default(shared) \
firstprivate(n, rp, cval, aval, x, y)
#endif
{
#ifdef USING_OPENMP_DH
#pragma omp for schedule(static)
#endif
for (i=0; i<n; ++i) {
sum = 0.0;
from = rp[i];
to = rp[i+1];
for (j=from; j<to; ++j) {
col = cval[j];
sum += (aval[j]*x[col]);
}
y[i] = sum;
}
}
END_FUNC_DH
}
#undef __FUNC__
#define __FUNC__ "Axpy"
void Axpy(int n, double alpha, double *x, double *y)
{
START_FUNC_DH
int i;
#ifdef USING_OPENMP_DH
#pragma omp parallel for schedule(static) firstprivate(alpha, x, y) \
private(i)
#endif
for (i=0; i<n; ++i) {
y[i] = alpha*x[i] + y[i];
}
END_FUNC_DH
}
#undef __FUNC__
#define __FUNC__ "CopyVec"
void CopyVec(int n, double *xIN, double *yOUT)
{
START_FUNC_DH
int i;
#ifdef USING_OPENMP_DH
#pragma omp parallel for schedule(static) firstprivate(yOUT, xIN) \
private(i)
#endif
for (i=0; i<n; ++i) {
yOUT[i] = xIN[i];
}
END_FUNC_DH
}
#undef __FUNC__
#define __FUNC__ "ScaleVec"
void ScaleVec(int n, double alpha, double *x)
{
START_FUNC_DH
int i;
#ifdef USING_OPENMP_DH
#pragma omp parallel for schedule(static) firstprivate(alpha, x) \
private(i)
#endif
for (i=0; i<n; ++i) {
x[i] *= alpha;
}
END_FUNC_DH
}
#undef __FUNC__
#define __FUNC__ "InnerProd"
double InnerProd(int n, double *x, double *y)
{
START_FUNC_DH
double result, local_result = 0.0;
int i;
#ifdef USING_OPENMP_DH
#pragma omp parallel for schedule(static) firstprivate(x, y) \
private(i) \
reduction(+:local_result)
#endif
for (i=0; i<n; ++i) {
local_result += x[i] * y[i];
}
if (np_dh > 1) {
MPI_Allreduce(&local_result, &result, 1, MPI_DOUBLE, MPI_SUM, comm_dh);
} else {
result = local_result;
}
END_FUNC_VAL(result)
}
#undef __FUNC__
#define __FUNC__ "Norm2"
double Norm2(int n, double *x)
{
START_FUNC_DH
double result, local_result = 0.0;
int i;
#ifdef USING_OPENMP_DH
#pragma omp parallel for schedule(static) firstprivate(x) \
private(i) \
reduction(+:local_result)
#endif
for (i=0; i<n; ++i) {
local_result += (x[i]*x[i]);
}
if (np_dh > 1) {
MPI_Allreduce(&local_result, &result, 1, MPI_DOUBLE, MPI_SUM, comm_dh);
} else {
result = local_result;
}
result = sqrt(result);
END_FUNC_VAL(result)
}
|
elemwise_binary_op.h | /*
* 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) 2016 by Contributors
* \file elemwise_binary_op.h
* \brief Function definition of elementwise binary operators
*/
#ifndef MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_
#define MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_
#include <mxnet/operator_util.h>
#include <mxnet/op_attr_types.h>
#include <vector>
#include <string>
#include <utility>
#include <typeinfo>
#include <algorithm>
#include "../mxnet_op.h"
#include "../mshadow_op.h"
#include "../../engine/openmp.h"
#include "elemwise_unary_op.h"
#include "../../common/utils.h"
#include "./init_op.h"
namespace mxnet {
namespace op {
/*! Gather binary operator functions into ElemwiseBinaryOp class */
class ElemwiseBinaryOp : public OpBase {
public:
/*! \brief For sparse, assume missing rvalue is 0 */
template<typename OP, int Req>
struct MissingRValueOp {
typedef OP Operation;
template<typename DType>
MSHADOW_XINLINE static void Map(int i, DType *out, const DType *lhs) {
KERNEL_ASSIGN(out[i], Req, OP::Map(lhs[i], DType(0)));
}
};
/*! \brief For sparse, assume missing lvalue is 0 */
template<typename OP, int Req>
struct MissingLValueOp {
typedef OP Operation;
template<typename DType>
MSHADOW_XINLINE static void Map(int i, DType *out, const DType *rhs) {
KERNEL_ASSIGN(out[i], Req, OP::Map(DType(0), rhs[i]));
}
};
private:
/*!
* \brief CSR operation requires temp space
*/
enum ResourceRequestType {
kTempSpace
};
/*!
* \brief Fill contiguous dense output rows with value computed from 0 lhs and 0 rhs input
* CPU-Only version
*/
template<typename DType, typename OP, typename xpu>
static inline size_t FillDense(mshadow::Stream<xpu> *s,
const size_t idx_l,
const size_t idx_r,
const OpReqType req,
mshadow::Tensor<xpu, 2, DType> *out,
const size_t iter_out) {
const int index_out_min = static_cast<int>(std::min(idx_l, idx_r));
if (static_cast<size_t>(index_out_min) > iter_out) {
const DType zero_input_val = OP::Map(DType(0), DType(0));
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (int i = static_cast<int>(iter_out); i < index_out_min; ++i) {
Fill<false>(s, (*out)[i], req, zero_input_val);
}
}
return static_cast<size_t>(index_out_min); // MSVC wants OMP loops to always use 'int'
}
static inline bool IsSameArray(const NDArray& a1, const NDArray& a2) {
return a1.var() == a2.var();
}
/*! \brief Minimum of three */
static MSHADOW_XINLINE size_t minthree(const size_t a, const size_t b, const size_t c) {
return a < b ? (a < c ? a : c) : (b < c ? b : c);
}
template<typename xpu, typename LOP, typename ROP, typename DType>
static void BackwardUseNone_(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
using namespace mxnet_op;
Stream<xpu> *s = ctx.get_stream<xpu>();
const int size = static_cast<int>((outputs[0].Size() + DataType<DType>::kLanes - 1)
/ DataType<DType>::kLanes);
const DType *ograd_dptr = inputs[0].dptr<DType>();
if (std::is_same<LOP, mshadow_op::identity>::value && req[0] == kWriteInplace) {
CHECK_EQ(ograd_dptr, outputs[0].dptr<DType>());
} else if (req[0] != kNullOp) {
DType *lgrad_dptr = outputs[0].dptr<DType>();
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
Kernel<mxnet_op::op_with_req<LOP, Req>, xpu>::Launch(s, size, lgrad_dptr, ograd_dptr);
});
}
if (std::is_same<ROP, mshadow_op::identity>::value && req[1] == kWriteInplace) {
CHECK_EQ(ograd_dptr, outputs[1].dptr<DType>());
} else if (req[1] != kNullOp) {
DType *rgrad_dptr = outputs[1].dptr<DType>();
MXNET_ASSIGN_REQ_SWITCH(req[1], Req, {
Kernel<mxnet_op::op_with_req<ROP, Req>, xpu>::Launch(s, size, rgrad_dptr, ograd_dptr);
});
}
}
template<typename xpu, typename LOP, typename ROP, typename DType>
static void BackwardUseIn_(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
DCHECK_EQ(outputs.size(), 2U);
DCHECK_EQ(inputs.size(), 3U);
mxnet_op::Stream<xpu> *s = ctx.get_stream<xpu>();
const DType *ograd_dptr = inputs[0].dptr<DType>();
const DType *lhs_dptr = inputs[1].dptr<DType>();
const DType *rhs_dptr = inputs[2].dptr<DType>();
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
const int size = static_cast<int>(
(outputs[0].Size() + mxnet_op::DataType<DType>::kLanes - 1)
/ mxnet_op::DataType<DType>::kLanes);
DType * lgrad_dptr = outputs[0].dptr<DType>();
mxnet_op::Kernel<mxnet_op::op_with_req<mxnet_op::backward_grad_tuned<LOP>, Req>, xpu>::Launch(
s, size, lgrad_dptr, ograd_dptr, lhs_dptr, rhs_dptr);});
MXNET_ASSIGN_REQ_SWITCH(req[1], Req, {
const int size = static_cast<int>(
(outputs[1].Size() + mxnet_op::DataType<DType>::kLanes - 1)
/ mxnet_op::DataType<DType>::kLanes);
DType * rgrad_dptr = outputs[1].dptr<DType>();
mxnet_op::Kernel<mxnet_op::op_with_req<mxnet_op::backward_grad_tuned<ROP>, Req>, xpu>::Launch(
s, size, rgrad_dptr, ograd_dptr, lhs_dptr, rhs_dptr);});
}
template<
typename xpu,
typename LOP,
typename ROP,
bool in0_ok_dense = false,
bool in1_ok_dense = false,
bool in2_ok_dense = false,
typename BackupCompute>
static inline void RspRspOpBackward(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs,
BackupCompute backup_compute) {
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
// lhs grad
if (req[0] != kNullOp) {
// RspRspOp can handle dense outputs so long as OP(0, 0) == 0
RspRspOp<LOP>(
s, attrs, ctx, inputs[1], inputs[2], req[0], outputs[0],
false, false, false, false);
// lhs in-place
RspRspOp<op::mshadow_op::mul>(
s, attrs, ctx, outputs[0], inputs[0], req[0], outputs[0],
false, false, true, false);
}
// rhs grad
if (req[1] != kNullOp) {
RspRspOp<ROP>(
s, attrs, ctx, inputs[1], inputs[2], req[1], outputs[1],
false, false, false, false);
// rhs in-place
RspRspOp<op::mshadow_op::mul>(
s, attrs, ctx, inputs[0], outputs[1], req[1], outputs[1],
false, false, true, false);
}
}
template<typename xpu, typename LOP, typename ROP>
static inline void DnsCsrCsrOpBackward(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
const bool supported_ops = std::is_same<mshadow_op::right, LOP>::value &&
std::is_same<mshadow_op::left, ROP>::value;
CHECK(supported_ops)
<< "Only backward for mul is supported (LOP should be right, ROP should be left)";
const NDArray& out_grad = inputs[0];
const NDArray& lhs_in = inputs[1];
const NDArray& rhs_in = inputs[2];
const NDArray& lhs_grad = outputs[0];
const NDArray& rhs_grad = outputs[1];
const bool reverse = (outputs[0].storage_type() == kCSRStorage);
if (reverse) {
DnsCsrCsrOp<xpu, mshadow_op::mul>(attrs, ctx, out_grad, rhs_in, req[0], lhs_grad, false);
Compute<xpu, mshadow_op::mul>(attrs, ctx, {out_grad.data(), lhs_in.data()}, {req[1]},
{rhs_grad.data()});
} else {
DnsCsrCsrOp<xpu, mshadow_op::mul>(attrs, ctx, out_grad, lhs_in, req[1], rhs_grad, false);
Compute<xpu, mshadow_op::mul>(attrs, ctx, {out_grad.data(), rhs_in.data()}, {req[0]},
{lhs_grad.data()});
}
}
public:
/*! \brief Binary op handling for lhr/rhs: RspDns, RspRsp, DnsRsp, or RspRsp->Dns result */
template<typename OP>
static void RspRspOp(mshadow::Stream<cpu> *s,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &lhs,
const NDArray &rhs,
OpReqType req,
const NDArray &output,
bool lhs_may_be_dense,
bool rhs_may_be_dense,
bool allow_inplace,
bool scatter);
/*! \brief Binary op handling for lhr/rhs: RspDns, RspRsp, DnsRsp, or RspRsp->Dns result */
template<typename OP>
static void RspRspOp(mshadow::Stream<gpu> *s,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &lhs,
const NDArray &rhs,
OpReqType req,
const NDArray &output,
bool lhs_may_be_dense,
bool rhs_may_be_dense,
bool allow_inplace,
bool scatter);
/*! \brief CSR -op- CSR binary operator for non-canonical NDArray */
template<typename OP>
static void CsrCsrOp(mshadow::Stream<cpu> *s,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &lhs,
const NDArray &rhs,
OpReqType req,
const NDArray &output);
/*! \brief CSR -op- CSR binary operator for non-canonical NDArray */
template<typename OP>
static void CsrCsrOp(mshadow::Stream<gpu> *s,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &lhs,
const NDArray &rhs,
OpReqType req,
const NDArray &output);
/*! \brief DNS -op- CSR binary operator for non-canonical NDArray */
template<typename OP>
static void DnsCsrDnsOp(mshadow::Stream<cpu> *s,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &lhs,
const NDArray &rhs,
OpReqType req,
const NDArray &output,
const bool reverse);
/*! \brief DNS -op- CSR binary operator for non-canonical NDArray */
template<typename OP>
static void DnsCsrDnsOp(mshadow::Stream<gpu> *s,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &lhs,
const NDArray &rhs,
OpReqType req,
const NDArray &output,
const bool reverse);
/*! \brief DNS -op- CSR binary operator for non-canonical NDArray */
template<typename xpu, typename OP>
static void DnsCsrCsrOp(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &lhs,
const NDArray &rhs,
OpReqType req,
const NDArray &output,
const bool reverse);
/*! \brief DNS -op- RSP binary operator for non-canonical NDArray */
template<typename xpu, typename OP>
static void DnsRspDnsOp(mshadow::Stream<xpu> *s,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &lhs,
const NDArray &rhs,
OpReqType req,
const NDArray &output,
const bool reverse);
public:
/*!
* \brief Rsp-op-Rsp operation which produces a dense result
* \param attrs Attributes
* \param dev_mask Device mask
* \param dispatch_mode Dispatch Mode
* \param in_attrs Input storage attributes
* \param out_attrs Output storage attributes
* \return true if handled
*/
static bool SparseSparseWithDenseResult(const nnvm::NodeAttrs& attrs,
int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs);
/*!
* \brief Allow one of the binary inputs to be dense and still produce a sparse output.
* Typically used for sparse * dense = sparse.
* Note: for csr, it dispatches to fallback other than csr, csr -> csr
* \param attrs Attributes
* \param dev_mask Device mask
* \param dispatch_mode Dispatch Mode
* \param in_attrs Input storage attributes
* \param out_attrs Output storage attributes
* \return true if handled
*/
static bool PreferSparseStorageType(const nnvm::NodeAttrs& attrs,
int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
using namespace common;
CHECK_EQ(in_attrs->size(), 2U) << " in operator " << attrs.name;
CHECK_EQ(out_attrs->size(), 1U) << " in operator " << attrs.name;
const auto& lhs_stype = in_attrs->at(0);
const auto& rhs_stype = in_attrs->at(1);
auto& out_stype = out_attrs->at(0);
bool dispatched = false;
const bool invalid_ctx = dev_mask != mshadow::cpu::kDevMask;
const auto dispatch_ex = invalid_ctx ? DispatchMode::kFComputeFallback :
DispatchMode::kFComputeEx;
if (!dispatched && ContainsOnlyStorage(*in_attrs, kDefaultStorage)) {
// dns, dns -> dns
dispatched = storage_type_assign(&out_stype, kDefaultStorage,
dispatch_mode, DispatchMode::kFCompute);
}
if (!dispatched && ContainsOnlyStorage(*in_attrs, kRowSparseStorage)) {
// rsp, rsp -> rsp
dispatched = storage_type_assign(&out_stype, kRowSparseStorage,
dispatch_mode, dispatch_ex);
}
if (!dispatched && ContainsOnlyStorage(*in_attrs, kCSRStorage)) {
// csr, csr -> csr
dispatched = storage_type_assign(&out_stype, kCSRStorage,
dispatch_mode, dispatch_ex);
}
if (!dispatched &&
((lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage) ||
(lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage))) {
// rsp, dns -> rsp
// dns, rsp -> rsp
dispatched = storage_type_assign(&out_stype, kRowSparseStorage,
dispatch_mode, dispatch_ex);
}
if (!dispatched &&
((lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage) ||
(lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage))) {
// csr, dns -> csr
// dns, csr -> csr
dispatched = storage_type_assign(&out_stype, kCSRStorage,
dispatch_mode, DispatchMode::kFComputeEx);
}
if (!dispatched) {
dispatched = dispatch_fallback(out_attrs, dispatch_mode);
}
return dispatched;
}
/*!
* \brief Allow one of the inputs to be dense and produce a dense output,
* for rsp inputs only support when both inputs are rsp type.
* \param attrs Attributes
* \param dev_mask Device mask
* \param dispatch_mode Dispatch Mode
* \param in_attrs Input storage attributes
* \param out_attrs Output storage attributes
* \return true if handled
*/
template<bool cpu_only, bool rsp, bool csr>
static bool PreferDenseStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
using namespace common;
CHECK_EQ(in_attrs->size(), 2);
CHECK_EQ(out_attrs->size(), 1);
const auto lhs_stype = (*in_attrs)[0];
const auto rhs_stype = (*in_attrs)[1];
bool dispatched = false;
const bool invalid_ctx = cpu_only && dev_mask != mshadow::cpu::kDevMask;
const auto dispatch_ex = invalid_ctx ? DispatchMode::kFComputeFallback :
DispatchMode::kFComputeEx;
if (!dispatched && ContainsOnlyStorage(*in_attrs, kDefaultStorage)) {
// dns, dns ... -> dns
dispatched = storage_type_assign(out_attrs, kDefaultStorage,
dispatch_mode, DispatchMode::kFCompute);
}
if (!dispatched && rsp && ContainsOnlyStorage(*in_attrs, kRowSparseStorage)) {
// rsp, rsp, ... -> rsp
dispatched = storage_type_assign(out_attrs, kRowSparseStorage,
dispatch_mode, DispatchMode::kFComputeEx);
}
if (!dispatched && csr && ContainsOnlyStorage(*in_attrs, kCSRStorage)) {
// csr, csr, ... -> csr
dispatched = storage_type_assign(out_attrs, kCSRStorage,
dispatch_mode, dispatch_ex);
}
if (!dispatched && ((lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage) ||
(lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage))) {
// dense, csr -> dense / csr, dense -> dense
dispatched = storage_type_assign(out_attrs, kDefaultStorage,
dispatch_mode, DispatchMode::kFComputeEx);
}
if (!dispatched && ((lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage) ||
(lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage))) {
// dense, rsp -> dense / rsp, dense -> dense
dispatched = storage_type_assign(out_attrs, kDefaultStorage,
dispatch_mode, DispatchMode::kFComputeEx);
}
if (!dispatched) {
dispatch_fallback(out_attrs, dispatch_mode);
}
return true;
}
/*!
* \brief Backward pass computing input gradient using forward inputs
* \param attrs Attributes
* \param dev_mask Device mask
* \param dispatch_mode Dispatch Mode
* \param in_attrs Input storage attributes
* \param out_attrs Output storage attributes
* \return true if handled
*/
static bool BackwardUseInStorageType(const nnvm::NodeAttrs& attrs,
int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs);
template<typename xpu, typename OP>
static void Compute(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
using namespace mxnet_op;
if (req[0] != kNullOp) {
Stream<xpu> *s = ctx.get_stream<xpu>();
CHECK_EQ(inputs.size(), 2U);
CHECK_EQ(outputs.size(), 1U);
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size())
+ DataType<DType>::kLanes - 1) / DataType<DType>::kLanes;
if (size != 0) {
Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size,
outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(), inputs[1].dptr<DType>());
}
});
});
}
}
template<typename xpu, typename OP>
static void ComputeLogic(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
using namespace mxnet_op;
if (req[0] != kNullOp) {
Stream<xpu> *s = ctx.get_stream<xpu>();
CHECK_EQ(inputs.size(), 2U);
CHECK_EQ(outputs.size(), 1U);
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
MSHADOW_TYPE_SWITCH_WITH_BOOL(inputs[0].type_flag_, DType, {
const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size())
+ DataType<DType>::kLanes - 1) / DataType<DType>::kLanes;
if (size != 0) {
Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size,
outputs[0].dptr<bool>(),
inputs[0].dptr<DType>(),
inputs[1].dptr<DType>());
}
});
});
}
}
template<typename xpu, typename OP>
static void ComputeWithHalf2(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
using namespace mxnet_op;
if (req[0] != kNullOp) {
Stream<xpu> *s = ctx.get_stream<xpu>();
CHECK_EQ(inputs.size(), 2U);
CHECK_EQ(outputs.size(), 1U);
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
MSHADOW_TYPE_SWITCH_WITH_HALF2(outputs[0].type_flag_, DType, {
const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size())
+ DataType<DType>::kLanes - 1) / DataType<DType>::kLanes;
if (size != 0) {
Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size,
outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(), inputs[1].dptr<DType>());
}
});
});
}
}
template<typename xpu, typename OP>
static void ComputeEx(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
using namespace common;
CHECK_EQ(inputs.size(), 2);
CHECK_EQ(outputs.size(), 1);
if (req[0] == kNullOp) return;
const auto lhs_stype = inputs[0].storage_type();
const auto rhs_stype = inputs[1].storage_type();
const auto out_stype = outputs[0].storage_type();
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
if ((ContainsOnlyStorage(inputs, kRowSparseStorage)) &&
(out_stype == kRowSparseStorage || out_stype == kDefaultStorage)) {
// rsp, rsp -> rsp
// rsp, rsp -> dns
RspRspOp<OP>(
s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0], false, false, false, false);
} else if (ContainsOnlyStorage(inputs, kCSRStorage) && out_stype == kCSRStorage) {
// csr, csr -> csr
CsrCsrOp<OP>(s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0]);
} else if (((lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage) ||
(lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage)) &&
out_stype == kDefaultStorage) {
const NDArray& dns = (lhs_stype == kDefaultStorage)? inputs[0] : inputs[1];
const NDArray& csr = (lhs_stype == kCSRStorage)? inputs[0] : inputs[1];
const bool reverse = (lhs_stype == kCSRStorage);
DnsCsrDnsOp<OP>(s, attrs, ctx, dns, csr, req[0], outputs[0], reverse);
} else if (((lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage) ||
(lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage)) &&
out_stype == kDefaultStorage) {
const NDArray& dns = (lhs_stype == kDefaultStorage)? inputs[0] : inputs[1];
const bool reverse = (lhs_stype == kRowSparseStorage);
const NDArray& rsp = (reverse)? inputs[0] : inputs[1];
DnsRspDnsOp<xpu, OP>(s, attrs, ctx, dns, rsp, req[0], outputs[0], reverse);
} else {
LogUnimplementedOp(attrs, ctx, inputs, req, outputs);
}
}
/*! \brief ComputeEx allowing dense lvalue and/or rvalue */
template<typename xpu, typename OP, bool lhs_may_be_dense, bool rhs_may_be_dense>
static void ComputeDnsLRValueEx(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
using namespace mshadow;
using namespace mshadow::expr;
CHECK_EQ(inputs.size(), 2);
CHECK_EQ(outputs.size(), 1);
if (req[0] == kNullOp) return;
const auto lhs_stype = inputs[0].storage_type();
const auto rhs_stype = inputs[1].storage_type();
const auto out_stype = outputs[0].storage_type();
if ((out_stype == kRowSparseStorage || out_stype == kDefaultStorage) &&
((lhs_stype == kRowSparseStorage && rhs_stype == kRowSparseStorage) ||
(lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage) ||
(lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage)) &&
lhs_may_be_dense && rhs_may_be_dense) {
// rsp, rsp -> rsp
// rsp, rsp -> dns
// rsp, dns -> rsp
// dns, rsp -> rsp
// More than once dense not allowed (this will be checked in RspRspOp):
// rsp, dns -> dns <-- NOT ALLOWED
// dns, rsp -> dns <-- NOT ALLOWED
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
RspRspOp<OP>(
s, attrs, ctx, inputs[0], inputs[1],
req[0], outputs[0], lhs_may_be_dense, rhs_may_be_dense, false, false);
} else if (lhs_stype == kCSRStorage && rhs_stype == kCSRStorage) {
ComputeEx<xpu, OP>(attrs, ctx, inputs, req, outputs);
} else if (((lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage) ||
(lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage)) &&
out_stype == kCSRStorage) {
const NDArray& dns = (lhs_stype == kDefaultStorage)? inputs[0] : inputs[1];
const NDArray& csr = (lhs_stype == kCSRStorage)? inputs[0] : inputs[1];
const bool reverse = (lhs_stype == kCSRStorage);
DnsCsrCsrOp<xpu, OP>(attrs, ctx, dns, csr, req[0], outputs[0], reverse);
} else {
LogUnimplementedOp(attrs, ctx, inputs, req, outputs);
}
}
template<typename xpu, typename LOP, typename ROP>
static inline void BackwardUseNone(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
BackwardUseNone_<xpu, LOP, ROP, DType>(attrs, ctx, inputs, req, outputs);
});
}
template<typename xpu, typename LOP, typename ROP>
static inline void BackwardUseNoneWithHalf2(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
MSHADOW_TYPE_SWITCH_WITH_HALF2(outputs[0].type_flag_, DType, {
BackwardUseNone_<xpu, LOP, ROP, DType>(attrs, ctx, inputs, req, outputs);
});
}
template<typename xpu, typename LOP, typename ROP>
static inline void BackwardUseNoneEx(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
CHECK_EQ(inputs.size(), 1U); // output grad
CHECK_EQ(outputs.size(), 2U); // lhs input grad, rhs input grad
const auto in_stype = inputs[0].storage_type();
const auto lhs_stype = outputs[0].storage_type();
const auto rhs_stype = outputs[1].storage_type();
// lhs grad
if (req[0] != kNullOp) {
if (in_stype == lhs_stype && (in_stype == kRowSparseStorage || in_stype == kCSRStorage)) {
CHECK_EQ(outputs[0].storage_type(), in_stype);
// rsp -> rsp, _. op requires 0-input returns 0-output
DCHECK_LT(std::fabs(static_cast<float>(LOP::Map(0))), 1e-5f);
UnaryOp::ComputeEx<xpu, LOP>(attrs, ctx, inputs, req, {outputs[0]});
} else {
LogUnimplementedOp(attrs, ctx, inputs, req, outputs);
}
}
// rhs grad
if (req[1] != kNullOp) {
if (in_stype == rhs_stype && (in_stype == kRowSparseStorage || in_stype == kCSRStorage)) {
CHECK_EQ(outputs[0].storage_type(), in_stype);
// rsp -> _, rsp. op requires 0-input returns 0-output
DCHECK_LT(std::fabs(static_cast<float>(ROP::Map(0))), 1e-5f);
UnaryOp::ComputeEx<xpu, ROP>(attrs, ctx, inputs, req, {outputs[1]});
} else {
LogUnimplementedOp(attrs, ctx, inputs, req, outputs);
}
}
}
template<typename xpu, typename LOP, typename ROP>
static inline void BackwardUseIn(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
BackwardUseIn_<xpu, LOP, ROP, DType>(attrs, ctx, inputs, req, outputs);
});
}
template<typename xpu, typename LOP, typename ROP>
static inline void BackwardUseInWithHalf2(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
MSHADOW_TYPE_SWITCH_WITH_HALF2(outputs[0].type_flag_, DType, {
BackwardUseIn_<xpu, LOP, ROP, DType>(attrs, ctx, inputs, req, outputs);
});
}
template<
typename xpu, typename LOP, typename ROP,
bool in0_ok_dense = false, bool in1_ok_dense = false, bool in2_ok_dense = false>
static inline void BackwardUseInEx(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
using namespace common;
CHECK_EQ(inputs.size(), 3U);
CHECK_EQ(outputs.size(), 2U); // lhs input grad, rhs input grad
const auto out_grad_stype = inputs[0].storage_type();
const auto lhs_grad_stype = outputs[0].storage_type();
const auto rhs_grad_stype = outputs[1].storage_type();
if (ContainsOnlyStorage(inputs, kRowSparseStorage) &&
(lhs_grad_stype == kDefaultStorage || lhs_grad_stype == kRowSparseStorage) &&
(rhs_grad_stype == kDefaultStorage || rhs_grad_stype == kRowSparseStorage)) {
// rsp, rsp, rsp -> [dns, rsp], [dns, rsp]
RspRspOpBackward<xpu, LOP, ROP, in0_ok_dense, in1_ok_dense, in2_ok_dense>(
attrs, ctx, inputs, req, outputs, BackwardUseIn<xpu, LOP, ROP>);
}
if (((lhs_grad_stype == kDefaultStorage && rhs_grad_stype == kCSRStorage) ||
(lhs_grad_stype == kCSRStorage && rhs_grad_stype == kDefaultStorage)) &&
out_grad_stype == kDefaultStorage) {
// dns, csr, dns -> [csr, dns] / csr, dns, dns -> [dns, csr]
DnsCsrCsrOpBackward<xpu, LOP, ROP>(attrs, ctx, inputs, req, outputs);
}
}
}; // class ElemwiseBinaryOp
/*! \brief Binary launch */
#define MXNET_OPERATOR_REGISTER_BINARY(name) \
NNVM_REGISTER_OP(name) \
.set_num_inputs(2) \
.set_num_outputs(1) \
.set_attr<nnvm::FListInputNames>("FListInputNames", \
[](const NodeAttrs& attrs) { \
return std::vector<std::string>{"lhs", "rhs"}; \
}) \
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<2, 1>) \
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>) \
.set_attr<nnvm::FInplaceOption>("FInplaceOption", \
[](const NodeAttrs& attrs){ \
return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}}; \
}) \
.add_argument("lhs", "NDArray-or-Symbol", "first input") \
.add_argument("rhs", "NDArray-or-Symbol", "second input")
/*! \brief Binary launch, with FComputeEx for csr and rsp available */
#define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU(__name$, __kernel$) \
MXNET_OPERATOR_REGISTER_BINARY(__name$) \
.set_attr<FInferStorageType>("FInferStorageType", \
ElemwiseStorageType<2, 1, true, true, true>) \
.set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \
.set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) \
.set_attr<FResourceRequest>("FResourceRequest", /* For Sparse CSR */ \
[](const NodeAttrs& attrs) { \
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};})
/*! \brief Binary launch, with FComputeEx for csr and rsp available.
when inputs contain both sparse and dense, sparse output is preferred. */
#define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_PS(__name$, __kernel$) \
MXNET_OPERATOR_REGISTER_BINARY(__name$) \
.set_attr<FInferStorageType>("FInferStorageType", \
ElemwiseBinaryOp::PreferSparseStorageType) \
.set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \
.set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) \
.set_attr<FResourceRequest>("FResourceRequest", /* For Sparse CSR */ \
[](const NodeAttrs& attrs) { \
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};})
/*! \brief Binary launch, dense result
* FInferStorageType attr is not set using this macro.
* By default DefaultStorageType is used.
*/
#define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(__name$, __kernel$) \
MXNET_OPERATOR_REGISTER_BINARY(__name$) \
.set_attr<FInferStorageType>("FInferStorageType", \
ElemwiseBinaryOp::SparseSparseWithDenseResult) \
.set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \
.set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>)
/*! \brief Binary launch, with FComputeEx for prefer dense */
#define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_PD(__name$, __kernel$) \
MXNET_OPERATOR_REGISTER_BINARY(__name$) \
.set_attr<FInferStorageType>("FInferStorageType", \
ElemwiseBinaryOp::PreferDenseStorageType<true, true, true>) \
.set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \
.set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) \
.set_attr<FResourceRequest>("FResourceRequest", /* For Sparse CSR */ \
[](const NodeAttrs& attrs) { \
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};})
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_
|
ndsbrkga.h | #ifndef NDSBRKGA_H
#define NDSBRKGA_H
#include "data.h"
#include <iostream>
#include <cmath>
#include <vector>
#include <set>
#include <random>
#include <algorithm>
#include <climits>
#include <fstream>
#include <iomanip>
const double INF = 987654321;
const double EPS = 1E-5;
using namespace std;
class Population;
//=====================================================================================================================//
class Decoder {
public:
static Decoder& getInstance() {
static Decoder instance;
return instance;
}
Decoder(Decoder const&) = delete;
void operator=(Decoder const&) = delete;
void decode(std::pair < std::vector < double >, std::vector < double > >&);
void localSearch(std::pair < std::vector < double >, std::vector < double > >&, Population*);
bool compare(const std::pair < std::vector < double >, std::vector < double > >&, const std::pair < std::vector < double >, std::vector < double > >&) const;
void save(const std::pair < std::vector < double >, std::vector < double > >&, ofstream&) const;
static std::default_random_engine generator;
const double alpha = 0.5;
private:
void repairOperator(std::pair < std::vector < double >, std::vector < double > >&, std::vector < std::pair < double, int > >&, std::vector < int >&, std::vector < int >&, std::vector < int >&, int) const;
Decoder() {};
};
//=====================================================================================================================//
class MTRand {
// Data
public:
typedef unsigned long uint32; // unsigned integer type, at least 32 bits
enum { N = 624 }; // length of state vector
enum { SAVE = N + 1 }; // length of array for save()
protected:
enum { M = 397 }; // period parameter
uint32 state[N]; // internal state
uint32 *pNext; // next value to get from state
int left; // number of values left before reload needed
// Methods
public:
MTRand( const uint32 oneSeed ); // initialize with a simple uint32
MTRand( uint32 *const bigSeed, uint32 const seedLength = N ); // or array
MTRand(); // auto-initialize with /dev/urandom or time() and clock()
MTRand( const MTRand& o ); // copy
// Do NOT use for CRYPTOGRAPHY without securely hashing several returned
// values together, otherwise the generator state can be learned after
// reading 624 consecutive values.
// Access to 32-bit random numbers
uint32 randInt(); // integer in [0,2^32-1]
uint32 randInt( const uint32 n ); // integer in [0,n] for n < 2^32
//double rand(); // real number in [0,1] -- disabled by rtoso
//double rand( const double n ); // real number in [0,n] -- disabled by rtoso
double randExc(); // real number in [0,1)
double randExc( const double n ); // real number in [0,n)
double randDblExc(); // real number in (0,1)
double randDblExc( const double n ); // real number in (0,n)
double operator()(); // same as rand53()
// Access to 53-bit random numbers (capacity of IEEE double precision)
double rand(); // calls rand53() -- modified by rtoso
double rand53(); // real number in [0,1)
// Access to nonuniform random number distributions
double randNorm( const double mean = 0.0, const double stddev = 1.0 );
// Re-seeding functions with same behavior as initializers
void seed( const uint32 oneSeed );
void seed( uint32 *const bigSeed, const uint32 seedLength = N );
void seed();
// Saving and loading generator state
void save( uint32* saveArray ) const; // to array of size SAVE
void load( uint32 *const loadArray ); // from such array
friend std::ostream& operator <<( std::ostream& os, const MTRand& mtrand );
friend std::istream& operator>>( std::istream& is, MTRand& mtrand );
MTRand& operator=( const MTRand& o );
protected:
void initialize( const uint32 oneSeed );
void reload();
uint32 hiBit( const uint32 u ) const { return u & 0x80000000UL; }
uint32 loBit( const uint32 u ) const { return u & 0x00000001UL; }
uint32 loBits( const uint32 u ) const { return u & 0x7fffffffUL; }
uint32 mixBits( const uint32 u, const uint32 v ) const { return hiBit(u) | loBits(v); }
uint32 magic( const uint32 u ) const { return loBit(u) ? 0x9908b0dfUL : 0x0UL; }
uint32 twist( const uint32 m, const uint32 s0, const uint32 s1 ) const { return m ^ (mixBits(s0,s1)>>1) ^ magic(s1); }
static uint32 hash( time_t t, clock_t c );
};
// Functions are defined in order of usage to assist inlining
inline MTRand::uint32 MTRand::hash( time_t t, clock_t c ) {
// Get a uint32 from t and c
// Better than uint32(x) in case x is floating point in [0,1]
// Based on code by Lawrence Kirby (fred@genesis.demon.co.uk)
static uint32 differ = 0; // guarantee time-based seeds will change
uint32 h1 = 0;
unsigned char *p = (unsigned char *) &t;
for( size_t i = 0; i < sizeof(t); ++i ) {
h1 *= UCHAR_MAX + 2U;
h1 += p[i];
}
uint32 h2 = 0;
p = (unsigned char *) &c;
for( size_t j = 0; j < sizeof(c); ++j ){
h2 *= UCHAR_MAX + 2U;
h2 += p[j];
}
return ( h1 + differ++ ) ^ h2;
}
inline void MTRand::initialize( const uint32 seed ) {
// Initialize generator state with seed
// See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
// In previous versions, most significant bits (MSBs) of the seed affect
// only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto.
register uint32 *s = state;
register uint32 *r = state;
register int i = 1;
*s++ = seed & 0xffffffffUL;
for( ; i < N; ++i ) {
*s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
r++;
}
}
inline void MTRand::reload() {
// Generate N new values in state
// Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
static const int MmN = int(M) - int(N); // in case enums are unsigned
register uint32 *p = state;
register int i;
for( i = N - M; i--; ++p ) {
*p = twist( p[M], p[0], p[1] );
}
for( i = M; --i; ++p ) {
*p = twist( p[MmN], p[0], p[1] );
}
*p = twist( p[MmN], p[0], state[0] );
left = N, pNext = state;
}
inline void MTRand::seed( const uint32 oneSeed ) {
// Seed the generator with a simple uint32
initialize(oneSeed);
reload();
}
inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength ) {
// Seed the generator with an array of uint32's
// There are 2^19937-1 possible initial states. This function allows
// all of those to be accessed by providing at least 19937 bits (with a
// default seed length of N = 624 uint32's). Any bits above the lower 32
// in each element are discarded.
// Just call seed() if you want to get array from /dev/urandom
initialize(19650218UL);
register int i = 1;
register uint32 j = 0;
register int k = ( N > seedLength ? N : seedLength );
for( ; k; --k ) {
state[i] =
state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL );
state[i] += ( bigSeed[j] & 0xffffffffUL ) + j;
state[i] &= 0xffffffffUL;
++i; ++j;
if( i >= N ) { state[0] = state[N-1]; i = 1; }
if( j >= seedLength ) j = 0;
}
for( k = N - 1; k; --k ) {
state[i] =
state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL );
state[i] -= i;
state[i] &= 0xffffffffUL;
++i;
if( i >= N ) { state[0] = state[N-1]; i = 1; }
}
state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array
reload();
}
inline void MTRand::seed() {
// Seed the generator with an array from /dev/urandom if available
// Otherwise use a hash of time() and clock() values
// First try getting an array from /dev/urandom
FILE* urandom = fopen( "/dev/urandom", "rb" );
if( urandom ) {
uint32 bigSeed[N];
register uint32 *s = bigSeed;
register int i = N;
register bool success = true;
while( success && i-- ) {
success = fread( s++, sizeof(uint32), 1, urandom );
}
fclose(urandom);
if( success ) { seed( bigSeed, N ); return; }
}
// Was not successful, so use time() and clock() instead
seed( hash( time(NULL), clock() ) );
}
inline MTRand::MTRand( const uint32 oneSeed ) { seed(oneSeed); }
inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength ) { seed(bigSeed,seedLength); }
inline MTRand::MTRand() { seed(); }
inline MTRand::MTRand( const MTRand& o ) {
register const uint32 *t = o.state;
register uint32 *s = state;
register int i = N;
for( ; i--; *s++ = *t++ ) {}
left = o.left;
pNext = &state[N-left];
}
inline MTRand::uint32 MTRand::randInt() {
// Pull a 32-bit integer from the generator state
// Every other access function simply transforms the numbers extracted here
if( left == 0 ) reload();
--left;
register uint32 s1;
s1 = *pNext++;
s1 ^= (s1 >> 11);
s1 ^= (s1 << 7) & 0x9d2c5680UL;
s1 ^= (s1 << 15) & 0xefc60000UL;
return ( s1 ^ (s1 >> 18) );
}
inline MTRand::uint32 MTRand::randInt( const uint32 n ) {
// Find which bits are used in n
// Optimized by Magnus Jonsson (magnus@smartelectronix.com)
uint32 used = n;
used |= used >> 1;
used |= used >> 2;
used |= used >> 4;
used |= used >> 8;
used |= used >> 16;
// Draw numbers until one is found in [0,n]
uint32 i;
do {
i = randInt() & used; // toss unused bits to shorten search
} while( i > n );
return i;
}
//inline double MTRand::rand()
// { return double(randInt()) * (1.0/4294967295.0); }
//inline double MTRand::rand( const double n )
// { return rand() * n; }
inline double MTRand::randExc() { return double(randInt()) * (1.0/4294967296.0); }
inline double MTRand::randExc( const double n ) { return randExc() * n; }
inline double MTRand::randDblExc() { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); }
inline double MTRand::randDblExc( const double n ) { return randDblExc() * n; }
inline double MTRand::rand53() {
uint32 a = randInt() >> 5, b = randInt() >> 6;
return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0); // by Isaku Wada
}
inline double MTRand::rand() { return rand53(); }
inline double MTRand::randNorm( const double mean, const double stddev ) {
// Return a real number from a normal (Gaussian) distribution with given
// mean and standard deviation by polar form of Box-Muller transformation
double x, y, r;
do
{
x = 2.0 * rand53() - 1.0;
y = 2.0 * rand53() - 1.0;
r = x * x + y * y;
}
while ( r >= 1.0 || r == 0.0 );
double s = sqrt( -2.0 * log(r) / r );
return mean + x * s * stddev;
}
inline double MTRand::operator()() {
return rand53();
}
inline void MTRand::save( uint32* saveArray ) const {
register const uint32 *s = state;
register uint32 *sa = saveArray;
register int i = N;
for( ; i--; *sa++ = *s++ ) {}
*sa = left;
}
inline void MTRand::load( uint32 *const loadArray ) {
register uint32 *s = state;
register uint32 *la = loadArray;
register int i = N;
for( ; i--; *s++ = *la++ ) {}
left = *la;
pNext = &state[N-left];
}
inline std::ostream& operator <<( std::ostream& os, const MTRand& mtrand ) {
register const MTRand::uint32 *s = mtrand.state;
register int i = mtrand.N;
for( ; i--; os << *s++ << " " ) {}
return os << mtrand.left;
}
inline std::istream& operator>>( std::istream& is, MTRand& mtrand ) {
register MTRand::uint32 *s = mtrand.state;
register int i = mtrand.N;
for( ; i--; is >> *s++ ) {}
is >> mtrand.left;
mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left];
return is;
}
inline MTRand& MTRand::operator=( const MTRand& o ) {
if( this == &o ) return (*this);
register const uint32 *t = o.state;
register uint32 *s = state;
register int i = N;
for( ; i--; *s++ = *t++ ) {}
left = o.left;
pNext = &state[N-left];
return (*this);
}
//=====================================================================================================================//
class Population {
template< class Decoder, class RNG >
friend class NDSBRKGA;
friend class Decoder;
public:
unsigned getN() const; // Size of each chromosome
unsigned getP() const; // Size of population
//double operator()(unsigned i, unsigned j) const; // Direct access to allele j of chromosome i
// These methods REQUIRE fitness to be sorted, and thus a call to sortFitness() beforehand
// (this is done by NDSBRKGA, so rest assured: everything will work just fine with NDSBRKGA).
const std::pair < std::vector < double >, std::vector < double > >& getChromosome(unsigned i) const; // Returns i-th best chromosome
void saveReferenceSolutionSet(ofstream &fout, bool printsol) const;
void storeReferenceSolutionSet(vector < pair < double, double > > &inputNDS) const;
void clear();
private:
Population();
Population(const Population& other);
Population(unsigned n, unsigned p);
~Population();
std::vector < std::pair < std::vector < double >, std::vector < double > > > population; // Population as vectors of prob.
std::vector < std::pair < std::pair < unsigned, double >, unsigned > > fitness; // Fitness < < level, crowding_distance > , id_chromosome_position > >
int getRelation(unsigned p, unsigned q);
bool equalsInDesignSpace(unsigned p, unsigned q);
void sortFitness(unsigned eliteSize); // Sorts 'fitness' by its first parameter
std::pair < std::vector < double >, std::vector < double > >& getChromosome(unsigned i); // Returns a chromosome
double& operator()(unsigned i, unsigned j); // Direct access to allele j of chromosome i
std::pair < std::vector < double >, std::vector < double > > & operator()(unsigned i); // Direct access to chromosome i
};
inline Population::Population() { }
inline Population::Population(const Population& pop) : population(pop.population), fitness(pop.fitness) { }
inline Population::Population(const unsigned n, const unsigned p) : population(p, std::make_pair(std::vector < double >(n, 0.0), std::vector < double > ())), fitness(p) {
if(p == 0) { std::clog << "Population size p cannot be zero." << endl; exit(0); }
if(n == 0) { std::clog << "Chromosome size n cannot be zero." << endl; exit(0); }
}
inline Population::~Population() { }
inline unsigned Population::getN() const {
return population[0].first.size();
}
inline unsigned Population::getP() const {
return population.size();
}
inline const std::pair < std::vector < double >, std::vector < double > >& Population::getChromosome(unsigned i) const {
return population[ fitness[i].second ];
}
inline std::pair < std::vector < double >, std::vector < double > >& Population::getChromosome(unsigned i) {
return population[ fitness[i].second ];
}
inline void Population::saveReferenceSolutionSet(ofstream &fout, bool printsol) const {
std::vector < std::pair < double, double > > vt;
for(unsigned i = 0; i < population.size(); ++i) {
if(fitness[i].first.first != 0) break;
if(printsol) Decoder::getInstance().save( population[ fitness[i].second ], fout );
else {
//for(unsigned j = 0; j < population[0].second.size(); ++j) {
//fout << fixed << setw(40) << setprecision(20) << fabs(population[ fitness[i].second ].second[j]) << ' ';
//}
//fout << endl;
vt.push_back(std::make_pair(fabs(population[ fitness[i].second ].second[0]), fabs(population[ fitness[i].second ].second[1])));
}
}
sort(vt.begin(), vt.end());
for(unsigned i = 0; i < vt.size(); ++i) {
fout << fixed << setprecision(5) << vt[i].first << ' ' << fixed << setprecision(0) << vt[i].second << endl;
}
}
inline void Population::storeReferenceSolutionSet(std::vector < pair < double, double > > &inputNDS) const {
std::vector < std::pair < double, double > > vt;
for(unsigned i = 0; i < population.size(); ++i) {
if(fitness[i].first.first != 0) break;
inputNDS.push_back(std::make_pair(population[ fitness[i].second ].second[0], population[ fitness[i].second ].second[1]));
}
}
inline void Population::clear() {
std::vector < std::pair < std::vector < double >, std::vector < double > > >().swap(population);
std::vector < std::pair < std::pair < unsigned, double >, unsigned > >().swap(fitness);
}
inline int Population::getRelation(unsigned p, unsigned q) {
/*
if p dominates q:
return 1
else if q dominates p:
return -1
else:
return 0
*/
int val = 0;
for(unsigned i = 0; i < population[p].second.size(); ++i) {
if(population[p].second[i] + EPS < population[q].second[i]) {
if(val == -1) return 0;
val = 1;
}
else if(population[p].second[i] - EPS > population[q].second[i]) {
if (val == 1) return 0;
val = -1;
}
}
return val;
}
inline bool Population::equalsInDesignSpace(unsigned p, unsigned q) {
for(unsigned i = 0; i < population[p].second.size(); ++i) {
if(fabs(population[p].second[i] - population[q].second[i]) > EPS) {
return false;
}
}
return true;
// return Decoder::getInstance().compare(population[p], population[q]);
}
inline void Population::sortFitness(unsigned eliteSize) {
std::vector < std::vector < unsigned > > graph; // (p -> q) if p dominates q
graph.resize(getP());
std::vector < int > degree(getP(), 0);
std::vector < std::vector < unsigned > > levels;
levels.push_back(std::vector < unsigned > ());
unsigned levelId = 0;
unsigned numberOfObjectives = population[0].second.size();
std::vector < bool > removed(getP(), false);
for(unsigned p = 0; p < getP(); ++p) {
if(removed[p]) continue;
for(unsigned q = p + 1; q < getP(); ++q) {
if(removed[q]) continue;
int relation = getRelation(p, q);
if(relation == 1) {
graph[p].push_back(q);
degree[q] += 1;
}
else if(relation == -1) {
graph[q].push_back(p);
degree[p] += 1;
}
else if(equalsInDesignSpace(p, q)) {
removed[q] = true;
}
}
}
for(unsigned p = 0; p < getP(); ++p) {
if(removed[p]) continue;
if(degree[p] == 0) {
levels[levelId].push_back(p);
}
}
while(1) {
levels.push_back(std::vector < unsigned > ());
for(unsigned i = 0; i < levels[levelId].size(); ++i) {
unsigned p = levels[levelId][i];
for(unsigned j = 0; j < graph[p].size(); ++j) {
unsigned q = graph[p][j];
degree[q] -= 1;
if(degree[q] == 0) {
levels[levelId + 1].push_back(q);
}
}
}
if(levels.back().size() == 0) {
levels.erase(--levels.end());
break;
}
levelId += 1;
}
for(unsigned p = 0; p < getP(); ++p) {
fitness[p].second = p;
fitness[p].first.second = -population[p].second[0];
fitness[p].first.first = INF;
}
for(unsigned i = 0; i < levels.size(); ++i) {
for(unsigned j = 0; j < levels[i].size(); ++j) {
fitness[ levels[i][j] ].first.first = i;
}
}
unsigned total = 0;
for(unsigned i = 0; i < levels.size(); ++i) {
if(total < eliteSize && total + levels[i].size() > eliteSize) {
for(unsigned j = 0; j < levels[i].size(); ++j) {
fitness[ levels[i][j] ].first.second = 0.0;
}
for(unsigned k = 0; k < numberOfObjectives; ++k) {
std::vector < std::pair < double, unsigned > > vt;
for(unsigned j = 0; j < levels[i].size(); ++j) {
vt.push_back(std::make_pair(population[ levels[i][j] ].second[k], levels[i][j]));
}
sort(vt.begin(), vt.end());
double fmin = vt.front().first;
double fmax = vt.back().first;
fitness[ vt.front().second ].first.second = INF;
fitness[ vt.back().second ].first.second = INF;
for(unsigned l = 1; l < vt.size() - 1; ++l) {
fitness[ vt[l].second ].first.second += (population[ vt[l + 1].second ].second[k] - population[ vt[l - 1].second ].second[k]) / (fmax - fmin);
}
}
break;
}
else {
total += levels[i].size();
}
}
sort(fitness.begin(), fitness.end(), [](const std::pair < std::pair < unsigned, double >, unsigned > &a, const std::pair < std::pair < unsigned, double >, unsigned > &b) {
if(a.first.first < b.first.first) return true;
else if(a.first.first == b.first.first && a.first.second > b.first.second) return true;
return false;});
}
//inline double Population::operator()(unsigned chromosome, unsigned allele) const {
// return population[chromosome][allele];
//}
inline double& Population::operator()(unsigned chromosome, unsigned allele) {
return population[chromosome].first[allele];
}
inline std::pair < std::vector < double >, std::vector < double > >& Population::operator()(unsigned chromosome) {
return population[chromosome];
}
//=====================================================================================================================//
template< class Decoder, class RNG >
class NDSBRKGA {
public:
/*
* Default constructor
* Required hyperparameters:
* - n: number of genes in each chromosome
* - p: number of elements in each population
* - pe: pct of elite items into each population
* - pm: pct of mutants introduced at each generation into the population
* - rhoe: probability that an offspring inherits the allele of its elite parent
*
* Optional parameters:
* - K: number of independent Populations
* - MAX_THREADS: number of threads to perform parallel decoding
* WARNING: Decoder::decode() MUST be thread-safe; safe if implemented as
* + double Decoder::decode(std::vector < double >& chromosome) const
*/
NDSBRKGA(unsigned n, unsigned p, double pe, double pm, double rhoe, double alpha, std::string tspSolutionFileName, std::string kpSolutionFileName, RNG& refRNG, unsigned K = 1, unsigned MAX_THREADS = 1);
/**
* Destructor
*/
~NDSBRKGA();
/**
* Resets all populations with brand new keys
*/
void reset();
/**
* Evolve the current populations following the guidelines of NDSBRKGAs
* @param generations number of generations (must be even and nonzero)
* @param J interval to exchange elite chromosomes (must be even; 0 ==> no synchronization)
* @param M number of elite chromosomes to select from each population in order to exchange
*/
void evolve(unsigned generations = 1);
void localSearch();
/**
* Exchange elite-solutions between the populations
* @param M number of elite chromosomes to select from each population
*/
void exchangeElite(unsigned M);
/**
* Returns the current population
*/
const Population& getPopulation(unsigned k = 0) const;
void saveReferenceSolutionSet(ofstream &fout, bool printsol = true) const;
void storeReferenceSolutionSet(std::vector < pair < double, double > > &inputNDS) const;
// Return copies to the internal parameters:
unsigned getN() const;
unsigned getP() const;
unsigned getPe() const;
unsigned getPm() const;
unsigned getPo() const;
double getRhoe() const;
double getAlpha() const;
unsigned getK() const;
unsigned getMAX_THREADS() const;
private:
// Hyperparameters:
const unsigned n; // number of genes in the chromosome
const unsigned p; // number of elements in the population
const unsigned pe; // number of elite items in the population
const unsigned pm; // number of mutants introduced at each generation into the population
const double rhoe; // probability that an offspring inherits the allele of its elite parent
const double alpha; // fraction of the initial population created from TSP and KP solutions
const string tspSolutionFileName;
const string kpSolutionFileName;
// Templates:
RNG& refRNG; // reference to the random number generator
// Parallel populations parameters:
const unsigned K; // number of independent parallel populations
const unsigned MAX_THREADS; // number of threads for parallel decoding
// Data:
std::vector < Population* > previous; // previous populations
std::vector < Population* > current; // current populations
// Local operations:
void initialize(const unsigned i); // initialize current population 'i' with random keys
void evolution(Population& curr, Population& next, const unsigned k);
};
template< class Decoder, class RNG >
NDSBRKGA< Decoder, RNG >::NDSBRKGA(unsigned _n, unsigned _p, double _pe, double _pm, double _rhoe, double _alpha, std::string _tspSolutionFileName, std::string _kpSolutionFileName, RNG& rng, unsigned _K, unsigned MAX) : n(_n), p(_p), pe(unsigned(_pe * p)), pm(unsigned(_pm * p)), rhoe(_rhoe), alpha(_alpha), tspSolutionFileName(_tspSolutionFileName), kpSolutionFileName(_kpSolutionFileName), refRNG(rng), K(_K), MAX_THREADS(MAX), previous(K, 0), current(K, 0) {
// Error check:
//using std::range_error;
if(n == 0) { std::clog << "Chromosome size equals zero." << endl; exit(0); }
if(p == 0) { std::clog << "Population size equals zero." << endl; exit(0); }
if(pe == 0) { std::clog << "Elite-set size equals zero." << endl; exit(0); }
if(pe > p) { std::clog << "Elite-set size greater than population size (pe > p)." << endl; exit(0); }
if(pm > p) { std::clog << "Mutant-set size (pm) greater than population size (p)." << endl; exit(0); }
if(pe + pm > p) { std::clog << "elite + mutant sets greater than population size (p)." << endl; exit(0); }
if(K == 0) { std::clog << "Number of parallel populations cannot be zero." << endl; exit(0); }
// Initialize and decode each chromosome of the current population, then copy to previous:
for(unsigned i = 0; i < K; ++i) {
// Allocate:
current[i] = new Population(n, p);
// Initialize:
initialize(i);
// Then just copy to previous:
previous[i] = new Population(*current[i]);
}
}
template< class Decoder, class RNG >
NDSBRKGA< Decoder, RNG >::~NDSBRKGA() {
for(unsigned i = 0; i < K; ++i) { delete current[i]; delete previous[i]; }
}
template< class Decoder, class RNG >
const Population& NDSBRKGA< Decoder, RNG >::getPopulation(unsigned k) const {
return (*current[k]);
}
template< class Decoder, class RNG >
void NDSBRKGA< Decoder, RNG >::reset() {
for(unsigned i = 0; i < K; ++i) { initialize(i); }
}
template< class Decoder, class RNG >
void NDSBRKGA< Decoder, RNG >::evolve(unsigned generations) {
if(generations == 0) { std::clog << "Cannot evolve for 0 generations." << endl; exit(0); }
for(unsigned i = 0; i < generations; ++i) {
for(unsigned j = 0; j < K; ++j) {
evolution(*current[j], *previous[j], j); // First evolve the population (curr, next)
std::swap(current[j], previous[j]); // Update (prev = curr; curr = prev == next)
}
}
}
template< class Decoder, class RNG >
void NDSBRKGA< Decoder, RNG >::exchangeElite(unsigned M) {
if(M == 0 || M >= p) { std::clog << "M cannot be zero or >= p." << endl; exit(0); }
for(unsigned i = 0; i < K; ++i) {
// Population i will receive some elite members from each Population j below:
unsigned dest = p - 1; // Last chromosome of i (will be updated below)
for(unsigned j = 0; j < K; ++j) {
if(j == i) { continue; }
// Copy the M individual from Population j to Population i:
for(unsigned _m = 0; _m < M; ++_m) {
unsigned m = (refRNG.randInt(pe - 1));
const std::pair < std::vector < double >, std::vector < double > >& bestOfJ = current[j]->getChromosome(m);
current[i]->population[dest] = bestOfJ;
current[i]->fitness[dest].second = current[j]->fitness[m].second;
--dest;
}
}
}
for(int j = 0; j < int(K); ++j) { current[j]->sortFitness(getPe()); }
}
template< class Decoder, class RNG >
inline void NDSBRKGA< Decoder, RNG >::initialize(const unsigned k) {
vector < int > tour, stolenItems;
//========================================================================================//
// read tsp solution found by LKH
ifstream fin(tspSolutionFileName.c_str());
if(!fin) {
clog << "ERROR!" << endl;
clog << tspSolutionFileName << endl;
exit(0);
}
string line;
getline(fin, line); // NAME : a280.2613.tour
getline(fin, line); // COMMENT : Length = 2613
getline(fin, line); // COMMENT : Found by LKH [Keld Helsgaun] Thu Jan 17 13:00:40 2019
getline(fin, line); // TYPE : TOUR
getline(fin, line); // DIMENSION : 280
getline(fin, line); // TOUR_SECTION
int tmp;
while(1) {
fin >> tmp;
if(tmp == -1) break;
tour.push_back(tmp);
}
fin.close();
//========================================================================================//
//========================================================================================//
// read kp solution found our greedy heuristic + dynamic programming
fin.open(kpSolutionFileName.c_str());
if(!fin) {
clog << "ERROR!" << endl;
clog << kpSolutionFileName << endl;
exit(0);
}
fin >> tmp; // total profit
while(fin >> tmp) {
stolenItems.push_back(tmp);
}
fin.close();
//========================================================================================//
std::vector < std::vector < double > > chromosomes;
vector < double > chromosome1(Data::getInstance().numCities + Data::getInstance().numItems, 0.0);
vector < double > chromosome2(Data::getInstance().numCities + Data::getInstance().numItems, 0.0);
double _delta = 1.0/(int)tour.size();
double key = 0.0;
for (unsigned i = 1; i < tour.size(); i++) {
chromosome1[ tour[i] - 2 ] = key;
key += _delta;
}
key = 0.0;
for (unsigned i = tour.size() - 1; i >= 1; i--) {
chromosome2[ tour[i] - 2 ] = key;
key += _delta;
}
vector < int > cityPositions(Data::getInstance().numCities+1, 0);
for(int i = 0; i < (int)tour.size(); ++i) {
cityPositions[tour[i]] = i;
}
vector < pair < double, int > > orderItems;
for(int i = 0; i < (int)stolenItems.size(); ++i) {
double weight = Data::getInstance().items[stolenItems[i]].weight;
double profit = Data::getInstance().items[stolenItems[i]].profit;
orderItems.push_back(make_pair(-profit/weight, stolenItems[i]));
}
sort(orderItems.begin(), orderItems.end());
vector < int > indices;
std::default_random_engine generator(refRNG.randInt(1000000));
std::uniform_int_distribution < int > distribution(0, (int)orderItems.size()-2);
if(getP() * getAlpha() >= 1) {
indices.push_back(-1);
}
if(getP() * getAlpha() >= 2) {
indices.push_back((int)orderItems.size()-1);
}
if(getP() * getAlpha() >= 3) {
indices.push_back(-2);
}
while((int)indices.size() < getP() * getAlpha()) {
indices.push_back(distribution(generator));
}
std::set < int > st(indices.begin(), indices.end());
if(st.find(-2) != st.end()) chromosomes.push_back(chromosome1);
if(st.find(-1) != st.end()) chromosomes.push_back(chromosome2);
for(int i = 0; i < (int)orderItems.size(); ++i) {
chromosome1[Data::getInstance().numCities - 1 + orderItems[i].second - 1] = 1.0;
chromosome2[Data::getInstance().numCities - 1 + orderItems[i].second - 1] = 1.0;
if(st.find(i) != st.end()) {
std::pair < std::vector < double >, std::vector < double > > _chromosome1;
_chromosome1.first = chromosome1;
std::pair < std::vector < double >, std::vector < double > > _chromosome2;
_chromosome2.first = chromosome2;
Decoder::getInstance().decode(_chromosome1);
Decoder::getInstance().decode(_chromosome2);
if(_chromosome1.second[0] < _chromosome2.second[0]) chromosomes.push_back(chromosome1);
else chromosomes.push_back(chromosome2);
}
}
unsigned pos = 0;
for(unsigned i = 0; i < (int)chromosomes.size(); ++i) {
for(unsigned j = 0; j < n; ++j) { (*current[k])(pos, j) = chromosomes[i][j]; }
pos += 1;
}
for(; pos < getP(); ++pos) {
for(unsigned j = 0; j < n; ++j) { (*current[k])(pos, j) = refRNG.rand(); }
}
// Decode:
#ifdef _OPENMP
#pragma omp parallel for num_threads(MAX_THREADS)
#endif
for(int j = 0; j < int(p); ++j) {
Decoder::getInstance().decode((*current[k])(j));
}
current[k]->sortFitness(getPe());
}
template< class Decoder, class RNG >
inline void NDSBRKGA< Decoder, RNG >::saveReferenceSolutionSet(ofstream &fout, bool printsol) const {
for(unsigned k = 0; k < K; ++k) {
current[k]->saveReferenceSolutionSet(fout, printsol);
}
}
template< class Decoder, class RNG >
inline void NDSBRKGA< Decoder, RNG >::storeReferenceSolutionSet(std::vector < pair < double, double > > &inputNDS) const {
for(unsigned k = 0; k < K; ++k) {
current[k]->storeReferenceSolutionSet(inputNDS);
}
}
template< class Decoder, class RNG >
inline void NDSBRKGA< Decoder, RNG >::evolution(Population& curr, Population& next, const unsigned k) {
//clog << "K: " << k << endl;
// We now will set every chromosome of 'current', iterating with 'i':
unsigned i = 0; // Iterate chromosome by chromosome
unsigned j = 0; // Iterate allele by allele
// 2. The 'pe' best chromosomes are maintained, so we just copy these into 'current':
while(i < pe) {
next(i) = curr(curr.fitness[i].second);
next.fitness[i].first = curr.fitness[i].first;
next.fitness[i].second = i;
++i;
}
// 3. We'll mate 'p - pe - pm' pairs; initially, i = pe, so we need to iterate until i < p - pm:
while(i < p - pm) {
unsigned eliteParent, anotherParent;
do {
// Select an elite parent:
eliteParent = (refRNG.randInt(pe - 1));
// Select an elite or non-elite parent:
anotherParent = (refRNG.randInt(p - 1));
} while(eliteParent == anotherParent);
// Mate:
for(j = 0; j < n; ++j) {
const unsigned sourceParent = ((refRNG.rand() < rhoe) ? eliteParent : anotherParent);
next(i, j) = curr(curr.fitness[sourceParent].second, j);
//next(i, j) = (refRNG.rand() < rhoe) ? curr(curr.fitness[eliteParent].second, j) :
// curr(curr.fitness[anotherParent].second, j);
}
++i;
}
/*
while(i < p - pm) {
int parent1, parent2, a, b;
a = (refRNG.randInt(pe - 1));
do {
b = (refRNG.randInt(p - 1));
} while (a == b);
if(a < pe && b >= pe) parent1 = a;
else if(b < pe && a >= pe) parent1 = b;
else parent1 = ((refRNG.rand() < 0.5) ? a : b);
a = (refRNG.randInt(p - 1));
do {
b = (refRNG.randInt(p - 1));
} while (a == b);
if(a < pe && b >= pe) parent2 = a;
else if(b < pe && a >= pe) parent2 = b;
else if(refRNG.rand() < 0.5) parent2 = a;
else parent2 = b;
// Mate:
for(j = 0; j < n; ++j) {
const unsigned sourceParent = ((refRNG.rand() < 0.5) ? parent1 : parent2);
next(i, j) = curr(curr.fitness[sourceParent].second, j);
//next(i, j) = (refRNG.rand() < rhoe) ? curr(curr.fitness[eliteParent].second, j) :
// curr(curr.fitness[anotherParent].second, j);
}
++i;
}
*/
// We'll introduce 'pm' mutants:
while(i < p) {
for(j = 0; j < n; ++j) { next(i, j) = refRNG.rand(); }
++i;
}
// Time to compute fitness, in parallel:
#ifdef _OPENMP
#pragma omp parallel for num_threads(MAX_THREADS)
#endif
for(int i = int(pe); i < int(p); ++i) {
Decoder::getInstance().decode(next.population[i]);
}
// Now we must sort 'current' by fitness, since things might have changed:
next.sortFitness(getPe());
}
template< class Decoder, class RNG >
inline void NDSBRKGA< Decoder, RNG >::localSearch() {
std::default_random_engine generator(refRNG.randInt(1000000));
std::uniform_int_distribution < int > distribution(0, getPe()-1);
for(unsigned k = 0; k < K; ++k) {
Population* all = new Population();
std::set < int > st;
while((int)st.size() < getPe() * 0.1) {
st.insert(distribution(generator));
}
std::set < int > :: iterator it = st.begin();
for(; it != st.end(); ++it) {
unsigned i = *it;
//for(unsigned i = 0; i < getPe(); ++i) {
Decoder::getInstance().localSearch(current[k]->population[i], all);
}
for(unsigned i = 0; i < getPe(); ++i) {
all->population.push_back(current[k]->population[i]);
//clog << i + 1 << ' ' << current[k]->population[i].second[1] << endl;
}
/*
for(unsigned i = 0; i < all->population.size(); ++i) {
clog << i + 1 << ' ' << all->population.size() << ' ' << all->population[i].second[1] << endl;
}
*/
all->fitness.resize(all->population.size());
//clog << "sortFitness()" << endl;
//clog << all->population.size() << endl;
all->sortFitness(getPe());
for(unsigned i = 0; i < getPe(); ++i) {
current[k]->population[i] = all->population[all->fitness[i].second];
current[k]->fitness[i].second = i;
}
all->clear();
delete all;
}
}
template< class Decoder, class RNG >
unsigned NDSBRKGA<Decoder, RNG>::getN() const { return n; }
template< class Decoder, class RNG >
unsigned NDSBRKGA<Decoder, RNG>::getP() const { return p; }
template< class Decoder, class RNG >
unsigned NDSBRKGA<Decoder, RNG>::getPe() const { return pe; }
template< class Decoder, class RNG >
unsigned NDSBRKGA<Decoder, RNG>::getPm() const { return pm; }
template< class Decoder, class RNG >
unsigned NDSBRKGA<Decoder, RNG>::getPo() const { return p - pe - pm; }
template< class Decoder, class RNG >
double NDSBRKGA<Decoder, RNG>::getRhoe() const { return rhoe; }
template< class Decoder, class RNG >
double NDSBRKGA<Decoder, RNG>::getAlpha() const { return alpha; }
template< class Decoder, class RNG >
unsigned NDSBRKGA<Decoder, RNG>::getK() const { return K; }
template< class Decoder, class RNG >
unsigned NDSBRKGA<Decoder, RNG>::getMAX_THREADS() const { return MAX_THREADS; }
#endif
|
convolution_sgemm_pack8to1_int8.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 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 NCNN_RUNTIME_CPU && NCNN_ARM82DOT && __ARM_NEON && __aarch64__ && !__ARM_FEATURE_DOTPROD
void im2col_sgemm_pack8to1_int8_neon_asimddp(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt);
void convolution_im2col_sgemm_transform_kernel_pack8to1_int8_neon_asimddp(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h);
#endif
static void im2col_sgemm_pack8to1_int8_neon(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt)
{
#if NCNN_RUNTIME_CPU && NCNN_ARM82DOT && __ARM_NEON && __aarch64__ && !__ARM_FEATURE_DOTPROD
if (ncnn::cpu_support_arm_asimddp())
{
im2col_sgemm_pack8to1_int8_neon_asimddp(bottom_im2col, top_blob, kernel, opt);
return;
}
#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 __aarch64__
#if __ARM_FEATURE_DOTPROD
if (size >= 16)
tmp.create(16 * maxk, inch, size / 16 + (size % 16) / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else 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 // __ARM_FEATURE_DOTPROD
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);
#endif // __ARM_FEATURE_DOTPROD
#else // __aarch64__
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 // __aarch64__
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
int nn_size = size >> 4;
int remain_size_start = 0;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 16;
signed char* tmpptr = tmp.channel(i / 16);
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
// split pack8to1 to pack4
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld2 {v0.4s, v1.4s}, [%0], #32 \n"
"ld2 {v2.4s, v3.4s}, [%0], #32 \n"
"ld2 {v4.4s, v5.4s}, [%0], #32 \n"
"ld2 {v6.4s, v7.4s}, [%0] \n"
"sub %0, %0, #96 \n"
"st1 {v0.16b}, [%1], #16 \n"
"st1 {v2.16b}, [%1], #16 \n"
"st1 {v4.16b}, [%1], #16 \n"
"st1 {v6.16b}, [%1], #16 \n"
"st1 {v1.16b}, [%1], #16 \n"
"st1 {v3.16b}, [%1], #16 \n"
"st1 {v5.16b}, [%1], #16 \n"
"st1 {v7.16b}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7");
img0 += size * 8;
}
}
}
remain_size_start += nn_size << 4;
nn_size = (size - remain_size_start) >> 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 8;
signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8);
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld2 {v0.4s, v1.4s}, [%0], #32 \n"
"ld2 {v2.4s, v3.4s}, [%0] \n"
"sub %0, %0, #32 \n"
"st1 {v0.16b}, [%1], #16 \n"
"st1 {v2.16b}, [%1], #16 \n"
"st1 {v1.16b}, [%1], #16 \n"
"st1 {v3.16b}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3");
img0 += size * 8;
}
}
}
remain_size_start += nn_size << 3;
nn_size = (size - remain_size_start) >> 2;
#else // __ARM_FEATURE_DOTPROD
int remain_size_start = 0;
int nn_size = (size - remain_size_start) >> 2;
#endif // __ARM_FEATURE_DOTPROD
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 4;
#if __ARM_FEATURE_DOTPROD
signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4);
#else
signed char* tmpptr = tmp.channel(i / 4);
#endif
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
#if __ARM_FEATURE_DOTPROD
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld2 {v0.4s, v1.4s}, [%0] \n"
"st1 {v0.4s, v1.4s}, [%1], #32 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1");
#else
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v0.16b, v1.16b}, [%0] \n"
"st1 {v0.16b, v1.16b}, [%1], #32 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1");
#endif // __ARM_FEATURE_DOTPROD
img0 += size * 8;
}
}
}
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 __aarch64__
#if __ARM_FEATURE_DOTPROD
signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2);
#else
signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2);
#endif
#else
signed char* tmpptr = tmp.channel(i / 2);
#endif
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
asm volatile(
"prfm pldl1keep, [%0, #128] \n"
"ld2 {v0.2s, v1.2s}, [%0] \n"
"st1 {v0.2s, v1.2s}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1");
#else
asm volatile(
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v0.16b}, [%0] \n"
"st1 {v0.16b}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0");
#endif // __ARM_FEATURE_DOTPROD
#else
asm volatile(
"pld [%0, #128] \n"
"vld1.s8 {d0-d1}, [%0 :64] \n"
"vst1.s8 {d0-d1}, [%1 :64]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0");
#endif
img0 += size * 8;
}
}
}
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 __aarch64__
#if __ARM_FEATURE_DOTPROD
signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
#else
signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2);
#endif
#else
signed char* tmpptr = tmp.channel(i / 2 + i % 2);
#endif
for (int q = 0; q < inch; q++)
{
const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i * 8;
for (int k = 0; k < maxk; k++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #64] \n"
"ld1 {v0.8b}, [%0] \n"
"st1 {v0.8b}, [%1], #8 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0");
#else
asm volatile(
"pld [%0, #64] \n"
"vld1.s8 {d0}, [%0 :64] \n"
"vst1.s8 {d0}, [%1 :64]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "d0");
#endif
img0 += size * 8;
}
}
}
}
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 __aarch64__
#if __ARM_FEATURE_DOTPROD
for (; i + 15 < size; i += 16)
{
const signed char* tmpptr = tmp.channel(i / 16);
const signed char* kptr0 = kernel.channel(p / 4);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v24.16b}, [%6], #16 \n" // _w0123_l
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"ld1 {v16.16b}, [%5], #16 \n" // _val0123_l
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"eor v4.16b, v4.16b, v4.16b \n"
"eor v5.16b, v5.16b, v5.16b \n"
"eor v6.16b, v6.16b, v6.16b \n"
"eor v7.16b, v7.16b, v7.16b \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"
"eor v12.16b, v12.16b, v12.16b \n"
"eor v13.16b, v13.16b, v13.16b \n"
"eor v14.16b, v14.16b, v14.16b \n"
"eor v15.16b, v15.16b, v15.16b \n"
"0: \n"
"ld1 {v17.16b}, [%5], #16 \n" // _val4567_l
"sdot v0.4s, v24.16b, v16.4b[0] \n"
"sdot v1.4s, v24.16b, v16.4b[1] \n"
"sdot v2.4s, v24.16b, v16.4b[2] \n"
"sdot v3.4s, v24.16b, v16.4b[3] \n"
"ld1 {v18.16b}, [%5], #16 \n" // _val891011_l
"sdot v4.4s, v24.16b, v17.4b[0] \n"
"sdot v5.4s, v24.16b, v17.4b[1] \n"
"sdot v6.4s, v24.16b, v17.4b[2] \n"
"sdot v7.4s, v24.16b, v17.4b[3] \n"
"ld1 {v19.16b}, [%5], #16 \n" // _val12131415_l
"sdot v8.4s, v24.16b, v18.4b[0] \n"
"sdot v9.4s, v24.16b, v18.4b[1] \n"
"ld1 {v25.16b}, [%6], #16 \n" // _w0123_h
"sdot v10.4s, v24.16b, v18.4b[2] \n"
"sdot v11.4s, v24.16b, v18.4b[3] \n"
"ld1 {v20.16b}, [%5], #16 \n" // _val0123_h
"sdot v12.4s, v24.16b, v19.4b[0] \n"
"sdot v13.4s, v24.16b, v19.4b[1] \n"
"sdot v14.4s, v24.16b, v19.4b[2] \n"
"sdot v15.4s, v24.16b, v19.4b[3] \n"
"ld1 {v21.16b}, [%5], #16 \n" // _val4567_h
"sdot v0.4s, v25.16b, v20.4b[0] \n"
"sdot v1.4s, v25.16b, v20.4b[1] \n"
"sdot v2.4s, v25.16b, v20.4b[2] \n"
"sdot v3.4s, v25.16b, v20.4b[3] \n"
"ld1 {v22.16b}, [%5], #16 \n" // _val891011_h
"sdot v4.4s, v25.16b, v21.4b[0] \n"
"sdot v5.4s, v25.16b, v21.4b[1] \n"
"sdot v6.4s, v25.16b, v21.4b[2] \n"
"sdot v7.4s, v25.16b, v21.4b[3] \n"
"ld1 {v23.16b}, [%5], #16 \n" // _val12131415_h
"sdot v8.4s, v25.16b, v22.4b[0] \n"
"sdot v9.4s, v25.16b, v22.4b[1] \n"
"ld1 {v24.16b}, [%6], #16 \n" // _w0123_l
"sdot v10.4s, v25.16b, v22.4b[2] \n"
"sdot v11.4s, v25.16b, v22.4b[3] \n"
"ld1 {v16.16b}, [%5], #16 \n" // _val0123_l
"sdot v12.4s, v25.16b, v23.4b[0] \n"
"sdot v13.4s, v25.16b, v23.4b[1] \n"
"subs %w4, %w4, #1 \n"
"sdot v14.4s, v25.16b, v23.4b[2] \n"
"sdot v15.4s, v25.16b, v23.4b[3] \n"
"bne 0b \n"
"sub %5, %5, #16 \n"
"sub %6, %6, #16 \n"
// transpose 4x16
"trn1 v16.4s, v0.4s, v1.4s \n"
"trn2 v17.4s, v0.4s, v1.4s \n"
"trn1 v18.4s, v2.4s, v3.4s \n"
"trn2 v19.4s, v2.4s, v3.4s \n"
"trn1 v20.4s, v4.4s, v5.4s \n"
"trn2 v21.4s, v4.4s, v5.4s \n"
"trn1 v22.4s, v6.4s, v7.4s \n"
"trn2 v23.4s, v6.4s, v7.4s \n"
"trn1 v24.4s, v8.4s, v9.4s \n"
"trn2 v25.4s, v8.4s, v9.4s \n"
"trn1 v26.4s, v10.4s, v11.4s \n"
"trn2 v27.4s, v10.4s, v11.4s \n"
"trn1 v28.4s, v12.4s, v13.4s \n"
"trn2 v29.4s, v12.4s, v13.4s \n"
"trn1 v30.4s, v14.4s, v15.4s \n"
"trn2 v31.4s, v14.4s, v15.4s \n"
"trn1 v0.2d, v16.2d, v18.2d \n"
"trn2 v8.2d, v16.2d, v18.2d \n"
"trn1 v4.2d, v17.2d, v19.2d \n"
"trn2 v12.2d, v17.2d, v19.2d \n"
"trn1 v1.2d, v20.2d, v22.2d \n"
"trn2 v9.2d, v20.2d, v22.2d \n"
"trn1 v5.2d, v21.2d, v23.2d \n"
"trn2 v13.2d, v21.2d, v23.2d \n"
"trn1 v2.2d, v24.2d, v26.2d \n"
"trn2 v10.2d, v24.2d, v26.2d \n"
"trn1 v6.2d, v25.2d, v27.2d \n"
"trn2 v14.2d, v25.2d, v27.2d \n"
"trn1 v3.2d, v28.2d, v30.2d \n"
"trn2 v11.2d, v28.2d, v30.2d \n"
"trn1 v7.2d, v29.2d, v31.2d \n"
"trn2 v15.2d, v29.2d, v31.2d \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"st1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n"
"st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%2], #64 \n"
"st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%3], #64 \n"
: "=r"(outptr0),
"=r"(outptr1),
"=r"(outptr2),
"=r"(outptr3),
"=r"(nn),
"=r"(tmpptr),
"=r"(kptr0)
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(nn),
"5"(tmpptr),
"6"(kptr0)
: "memory", "x4", "x5", "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 + 7 < size; i += 8)
{
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8);
const signed char* kptr0 = kernel.channel(p / 4);
int nn = inch * maxk; // inch always > 0
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int32x4_t _sum4 = vdupq_n_s32(0);
int32x4_t _sum5 = vdupq_n_s32(0);
int32x4_t _sum6 = vdupq_n_s32(0);
int32x4_t _sum7 = vdupq_n_s32(0);
for (int j = 0; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _val4567_l = vld1q_s8(tmpptr + 16);
int8x16_t _w0123_l = vld1q_s8(kptr0);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_l, _val0123_l, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_l, _val0123_l, 1);
_sum2 = vdotq_laneq_s32(_sum2, _w0123_l, _val0123_l, 2);
_sum3 = vdotq_laneq_s32(_sum3, _w0123_l, _val0123_l, 3);
_sum4 = vdotq_laneq_s32(_sum4, _w0123_l, _val4567_l, 0);
_sum5 = vdotq_laneq_s32(_sum5, _w0123_l, _val4567_l, 1);
_sum6 = vdotq_laneq_s32(_sum6, _w0123_l, _val4567_l, 2);
_sum7 = vdotq_laneq_s32(_sum7, _w0123_l, _val4567_l, 3);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 32);
int8x16_t _val4567_h = vld1q_s8(tmpptr + 48);
int8x16_t _w0123_h = vld1q_s8(kptr0 + 16);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_h, _val0123_h, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_h, _val0123_h, 1);
_sum2 = vdotq_laneq_s32(_sum2, _w0123_h, _val0123_h, 2);
_sum3 = vdotq_laneq_s32(_sum3, _w0123_h, _val0123_h, 3);
_sum4 = vdotq_laneq_s32(_sum4, _w0123_h, _val4567_h, 0);
_sum5 = vdotq_laneq_s32(_sum5, _w0123_h, _val4567_h, 1);
_sum6 = vdotq_laneq_s32(_sum6, _w0123_h, _val4567_h, 2);
_sum7 = vdotq_laneq_s32(_sum7, _w0123_h, _val4567_h, 3);
tmpptr += 64;
kptr0 += 32;
}
// transpose 4x8
int32x4x2_t _s01 = vtrnq_s32(_sum0, _sum1);
int32x4x2_t _s23 = vtrnq_s32(_sum2, _sum3);
int32x4x2_t _s45 = vtrnq_s32(_sum4, _sum5);
int32x4x2_t _s67 = vtrnq_s32(_sum6, _sum7);
_sum0 = vcombine_s32(vget_low_s32(_s01.val[0]), vget_low_s32(_s23.val[0]));
_sum1 = vcombine_s32(vget_low_s32(_s01.val[1]), vget_low_s32(_s23.val[1]));
_sum2 = vcombine_s32(vget_high_s32(_s01.val[0]), vget_high_s32(_s23.val[0]));
_sum3 = vcombine_s32(vget_high_s32(_s01.val[1]), vget_high_s32(_s23.val[1]));
_sum4 = vcombine_s32(vget_low_s32(_s45.val[0]), vget_low_s32(_s67.val[0]));
_sum5 = vcombine_s32(vget_low_s32(_s45.val[1]), vget_low_s32(_s67.val[1]));
_sum6 = vcombine_s32(vget_high_s32(_s45.val[0]), vget_high_s32(_s67.val[0]));
_sum7 = vcombine_s32(vget_high_s32(_s45.val[1]), vget_high_s32(_s67.val[1]));
vst1q_s32(outptr0, _sum0);
vst1q_s32(outptr1, _sum1);
vst1q_s32(outptr2, _sum2);
vst1q_s32(outptr3, _sum3);
vst1q_s32(outptr0 + 4, _sum4);
vst1q_s32(outptr1 + 4, _sum5);
vst1q_s32(outptr2 + 4, _sum6);
vst1q_s32(outptr3 + 4, _sum7);
outptr0 += 8;
outptr1 += 8;
outptr2 += 8;
outptr3 += 8;
}
#endif
for (; i + 3 < size; i += 4)
{
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4);
#else
const signed char* tmpptr = tmp.channel(i / 4);
#endif
const signed char* kptr0 = kernel.channel(p / 4);
int nn = inch * maxk; // inch always > 0
#if __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
for (int j = 0; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _w0123_l = vld1q_s8(kptr0);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_l, _val0123_l, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_l, _val0123_l, 1);
_sum2 = vdotq_laneq_s32(_sum2, _w0123_l, _val0123_l, 2);
_sum3 = vdotq_laneq_s32(_sum3, _w0123_l, _val0123_l, 3);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 16);
int8x16_t _w0123_h = vld1q_s8(kptr0 + 16);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_h, _val0123_h, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_h, _val0123_h, 1);
_sum2 = vdotq_laneq_s32(_sum2, _w0123_h, _val0123_h, 2);
_sum3 = vdotq_laneq_s32(_sum3, _w0123_h, _val0123_h, 3);
tmpptr += 32;
kptr0 += 32;
}
// transpose 4x4
int32x4x2_t _s01 = vtrnq_s32(_sum0, _sum1);
int32x4x2_t _s23 = vtrnq_s32(_sum2, _sum3);
_sum0 = vcombine_s32(vget_low_s32(_s01.val[0]), vget_low_s32(_s23.val[0]));
_sum1 = vcombine_s32(vget_low_s32(_s01.val[1]), vget_low_s32(_s23.val[1]));
_sum2 = vcombine_s32(vget_high_s32(_s01.val[0]), vget_high_s32(_s23.val[0]));
_sum3 = vcombine_s32(vget_high_s32(_s01.val[1]), vget_high_s32(_s23.val[1]));
vst1q_s32(outptr0, _sum0);
vst1q_s32(outptr1, _sum1);
vst1q_s32(outptr2, _sum2);
vst1q_s32(outptr3, _sum3);
outptr0 += 4;
outptr1 += 4;
outptr2 += 4;
outptr3 += 4;
#else // __ARM_FEATURE_DOTPROD
asm volatile(
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"eor v4.16b, v4.16b, v4.16b \n"
"eor v5.16b, v5.16b, v5.16b \n"
"eor v6.16b, v6.16b, v6.16b \n"
"eor v7.16b, v7.16b, v7.16b \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"
"eor v12.16b, v12.16b, v12.16b \n"
"eor v13.16b, v13.16b, v13.16b \n"
"eor v14.16b, v14.16b, v14.16b \n"
"eor v15.16b, v15.16b, v15.16b \n"
"prfm pldl1keep, [%5, #128] \n"
"prfm pldl1keep, [%6, #256] \n"
"lsr w4, %w4, #1 \n" // w4 = nn >> 1
"cmp w4, #0 \n"
"beq 1f \n"
"prfm pldl1keep, [%6, #512] \n"
"add x5, %5, #16 \n"
"prfm pldl1keep, [x5, #128] \n"
"ld1 {v16.16b}, [%5] \n" // val L H
"ld1 {v20.16b, v21.16b, v22.16b, v23.16b}, [%6], #64 \n"
"add %5, %5, #32 \n"
"ext v17.16b, v16.16b, v16.16b, #8 \n" // val H L
"ld1 {v18.16b}, [%5] \n"
"add %5, %5, #32 \n"
"0: \n"
"smull v24.8h, v16.8b, v20.8b \n"
"prfm pldl1keep, [%6, #256] \n"
"smull2 v25.8h, v17.16b, v20.16b \n"
"prfm pldl1keep, [%6, #512] \n"
"smull v26.8h, v16.8b, v21.8b \n"
"subs w4, w4, #1 \n"
"smull2 v27.8h, v17.16b, v21.16b \n"
"ext v19.16b, v18.16b, v18.16b, #8 \n" // val H L
"smlal v24.8h, v18.8b, v22.8b \n"
"smlal2 v25.8h, v19.16b, v22.16b \n"
"smlal v26.8h, v18.8b, v23.8b \n"
"smlal2 v27.8h, v19.16b, v23.16b \n"
"smull2 v29.8h, v16.16b, v20.16b \n"
"sadalp v0.4s, v24.8h \n"
"smull v28.8h, v17.8b, v20.8b \n"
"sadalp v1.4s, v25.8h \n"
"smull2 v31.8h, v16.16b, v21.16b \n"
"ld1 {v16.16b}, [x5] \n" // val L H
"smull v30.8h, v17.8b, v21.8b \n"
"add x5, x5, #32 \n"
"smlal2 v29.8h, v18.16b, v22.16b \n"
"sadalp v2.4s, v26.8h \n"
"smlal v28.8h, v19.8b, v22.8b \n"
"sadalp v3.4s, v27.8h \n"
"smlal2 v31.8h, v18.16b, v23.16b \n"
"ld1 {v18.16b}, [x5] \n"
"smlal v30.8h, v19.8b, v23.8b \n"
"ext v17.16b, v16.16b, v16.16b, #8 \n" // val H L
"smull v24.8h, v16.8b, v20.8b \n"
"add x5, x5, #32 \n"
"smull2 v25.8h, v17.16b, v20.16b \n"
"prfm pldl1keep, [x5, #128] \n"
"smull v26.8h, v16.8b, v21.8b \n"
"prfm pldl1keep, [x5, #384] \n"
"smull2 v27.8h, v17.16b, v21.16b \n"
"ext v19.16b, v18.16b, v18.16b, #8 \n" // val H L
"smlal v24.8h, v18.8b, v22.8b \n"
"sadalp v5.4s, v29.8h \n"
"smlal2 v25.8h, v19.16b, v22.16b \n"
"sadalp v4.4s, v28.8h \n"
"smlal v26.8h, v18.8b, v23.8b \n"
"sadalp v7.4s, v31.8h \n"
"smlal2 v27.8h, v19.16b, v23.16b \n"
"sadalp v6.4s, v30.8h \n"
"smull2 v29.8h, v16.16b, v20.16b \n"
"sadalp v8.4s, v24.8h \n"
"smull v28.8h, v17.8b, v20.8b \n"
"sadalp v9.4s, v25.8h \n"
"smull2 v31.8h, v16.16b, v21.16b \n"
"ld1 {v16.16b}, [%5] \n" // val L H
"smull v30.8h, v17.8b, v21.8b \n"
"add %5, %5, #32 \n"
"smlal2 v29.8h, v18.16b, v22.16b \n"
"sadalp v10.4s, v26.8h \n"
"smlal v28.8h, v19.8b, v22.8b \n"
"sadalp v11.4s, v27.8h \n"
"smlal2 v31.8h, v18.16b, v23.16b \n"
"ld1 {v18.16b}, [%5] \n"
"smlal v30.8h, v19.8b, v23.8b \n"
"add %5, %5, #32 \n"
"ld1 {v20.16b, v21.16b, v22.16b, v23.16b}, [%6], #64 \n"
"sadalp v13.4s, v29.8h \n"
"prfm pldl1keep, [%5, #128] \n"
"sadalp v12.4s, v28.8h \n"
"prfm pldl1keep, [%5, #384] \n"
"sadalp v15.4s, v31.8h \n"
"ext v17.16b, v16.16b, v16.16b, #8 \n" // val H L
"sadalp v14.4s, v30.8h \n"
"bne 0b \n"
"sub %5, %5, #64 \n"
"sub %6, %6, #64 \n"
"1: \n"
"and w4, %w4, #1 \n" // w4 = remain = nn & 1
"cmp w4, #0 \n" // w4 > 0
"beq 2f \n"
"ld1 {v16.8b, v17.8b}, [%5], #16 \n"
"ld1 {v20.8b, v21.8b, v22.8b, v23.8b}, [%6], #32 \n"
"smull v24.8h, v16.8b, v20.8b \n"
"smull v25.8h, v16.8b, v21.8b \n"
"smull v26.8h, v16.8b, v22.8b \n"
"ld1 {v18.8b, v19.8b}, [%5], #16 \n"
"smull v27.8h, v16.8b, v23.8b \n"
"sadalp v0.4s, v24.8h \n"
"smull v28.8h, v17.8b, v20.8b \n"
"sadalp v1.4s, v25.8h \n"
"smull v29.8h, v17.8b, v21.8b \n"
"sadalp v2.4s, v26.8h \n"
"smull v30.8h, v17.8b, v22.8b \n"
"sadalp v3.4s, v27.8h \n"
"smull v31.8h, v17.8b, v23.8b \n"
"sadalp v4.4s, v28.8h \n"
"smull v24.8h, v18.8b, v20.8b \n"
"sadalp v5.4s, v29.8h \n"
"smull v25.8h, v18.8b, v21.8b \n"
"sadalp v6.4s, v30.8h \n"
"smull v26.8h, v18.8b, v22.8b \n"
"sadalp v7.4s, v31.8h \n"
"smull v27.8h, v18.8b, v23.8b \n"
"sadalp v8.4s, v24.8h \n"
"smull v28.8h, v19.8b, v20.8b \n"
"sadalp v9.4s, v25.8h \n"
"smull v29.8h, v19.8b, v21.8b \n"
"sadalp v10.4s, v26.8h \n"
"smull v30.8h, v19.8b, v22.8b \n"
"sadalp v11.4s, v27.8h \n"
"smull v31.8h, v19.8b, v23.8b \n"
"sadalp v12.4s, v28.8h \n"
"sadalp v13.4s, v29.8h \n"
"sadalp v14.4s, v30.8h \n"
"sadalp v15.4s, v31.8h \n"
"2: \n"
"addp v0.4s, v0.4s, v4.4s \n"
"addp v1.4s, v1.4s, v5.4s \n"
"addp v2.4s, v2.4s, v6.4s \n"
"addp v3.4s, v3.4s, v7.4s \n"
"addp v8.4s, v8.4s, v12.4s \n"
"addp v9.4s, v9.4s, v13.4s \n"
"addp v10.4s, v10.4s, v14.4s \n"
"addp v11.4s, v11.4s, v15.4s \n"
"addp v0.4s, v0.4s, v8.4s \n"
"addp v1.4s, v1.4s, v9.4s \n"
"addp v2.4s, v2.4s, v10.4s \n"
"addp v3.4s, v3.4s, v11.4s \n"
"st1 {v0.4s}, [%0], #16 \n"
"st1 {v1.4s}, [%1], #16 \n"
"st1 {v2.4s}, [%2], #16 \n"
"st1 {v3.4s}, [%3], #16 \n"
: "=r"(outptr0),
"=r"(outptr1),
"=r"(outptr2),
"=r"(outptr3),
"=r"(nn),
"=r"(tmpptr),
"=r"(kptr0)
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(nn),
"5"(tmpptr),
"6"(kptr0)
: "memory", "x4", "x5", "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");
#endif // __ARM_FEATURE_DOTPROD
}
#endif // __aarch64__
for (; i + 1 < size; i += 2)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2);
#else
const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2);
#endif
#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 __aarch64__
#if __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
for (int j = 0; j < nn; j++)
{
int8x16_t _val01_l_h = vld1q_s8(tmpptr);
int8x16_t _w0123_l = vld1q_s8(kptr0);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_l, _val01_l_h, 0);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_l, _val01_l_h, 1);
int8x16_t _w0123_h = vld1q_s8(kptr0 + 16);
_sum0 = vdotq_laneq_s32(_sum0, _w0123_h, _val01_l_h, 2);
_sum1 = vdotq_laneq_s32(_sum1, _w0123_h, _val01_l_h, 3);
tmpptr += 16;
kptr0 += 32;
}
vst1q_lane_s32(outptr0, _sum0, 0);
vst1q_lane_s32(outptr1, _sum0, 1);
vst1q_lane_s32(outptr2, _sum0, 2);
vst1q_lane_s32(outptr3, _sum0, 3);
vst1q_lane_s32(outptr0 + 1, _sum1, 0);
vst1q_lane_s32(outptr1 + 1, _sum1, 1);
vst1q_lane_s32(outptr2 + 1, _sum1, 2);
vst1q_lane_s32(outptr3 + 1, _sum1, 3);
outptr0 += 2;
outptr1 += 2;
outptr2 += 2;
outptr3 += 2;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum00 = vdupq_n_s32(0);
int32x4_t _sum01 = vdupq_n_s32(0);
int32x4_t _sum02 = vdupq_n_s32(0);
int32x4_t _sum03 = vdupq_n_s32(0);
int32x4_t _sum10 = vdupq_n_s32(0);
int32x4_t _sum11 = vdupq_n_s32(0);
int32x4_t _sum12 = vdupq_n_s32(0);
int32x4_t _sum13 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val0 = vld1q_s8(tmpptr);
int8x16_t _val1 = vld1q_s8(tmpptr + 16);
int8x16_t _w01 = vld1q_s8(kptr0);
int8x16_t _w23 = vld1q_s8(kptr0 + 16);
int16x8_t _wv00 = vmull_s8(vget_low_s8(_val0), vget_low_s8(_w01));
int16x8_t _wv01 = vmull_s8(vget_low_s8(_val0), vget_high_s8(_w01));
int16x8_t _wv02 = vmull_s8(vget_low_s8(_val0), vget_low_s8(_w23));
int16x8_t _wv03 = vmull_s8(vget_low_s8(_val0), vget_high_s8(_w23));
int16x8_t _wv10 = vmull_s8(vget_high_s8(_val0), vget_low_s8(_w01));
int16x8_t _wv11 = vmull_s8(vget_high_s8(_val0), vget_high_s8(_w01));
int16x8_t _wv12 = vmull_s8(vget_high_s8(_val0), vget_low_s8(_w23));
int16x8_t _wv13 = vmull_s8(vget_high_s8(_val0), vget_high_s8(_w23));
int8x16_t _w45 = vld1q_s8(kptr0 + 32);
int8x16_t _w67 = vld1q_s8(kptr0 + 48);
_wv00 = vmlal_s8(_wv00, vget_low_s8(_val1), vget_low_s8(_w45));
_wv01 = vmlal_s8(_wv01, vget_low_s8(_val1), vget_high_s8(_w45));
_wv02 = vmlal_s8(_wv02, vget_low_s8(_val1), vget_low_s8(_w67));
_wv03 = vmlal_s8(_wv03, vget_low_s8(_val1), vget_high_s8(_w67));
_wv10 = vmlal_s8(_wv10, vget_high_s8(_val1), vget_low_s8(_w45));
_wv11 = vmlal_s8(_wv11, vget_high_s8(_val1), vget_high_s8(_w45));
_wv12 = vmlal_s8(_wv12, vget_high_s8(_val1), vget_low_s8(_w67));
_wv13 = vmlal_s8(_wv13, vget_high_s8(_val1), vget_high_s8(_w67));
_sum00 = vpadalq_s16(_sum00, _wv00);
_sum01 = vpadalq_s16(_sum01, _wv01);
_sum02 = vpadalq_s16(_sum02, _wv02);
_sum03 = vpadalq_s16(_sum03, _wv03);
_sum10 = vpadalq_s16(_sum10, _wv10);
_sum11 = vpadalq_s16(_sum11, _wv11);
_sum12 = vpadalq_s16(_sum12, _wv12);
_sum13 = vpadalq_s16(_sum13, _wv13);
tmpptr += 32;
kptr0 += 64;
}
for (; j < nn; j++)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x16_t _w01 = vld1q_s8(kptr0);
int8x16_t _w23 = vld1q_s8(kptr0 + 16);
int16x8_t _wv00 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w01));
int16x8_t _wv01 = vmull_s8(vget_low_s8(_val), vget_high_s8(_w01));
int16x8_t _wv02 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w23));
int16x8_t _wv03 = vmull_s8(vget_low_s8(_val), vget_high_s8(_w23));
int16x8_t _wv10 = vmull_s8(vget_high_s8(_val), vget_low_s8(_w01));
int16x8_t _wv11 = vmull_s8(vget_high_s8(_val), vget_high_s8(_w01));
int16x8_t _wv12 = vmull_s8(vget_high_s8(_val), vget_low_s8(_w23));
int16x8_t _wv13 = vmull_s8(vget_high_s8(_val), vget_high_s8(_w23));
_sum00 = vpadalq_s16(_sum00, _wv00);
_sum01 = vpadalq_s16(_sum01, _wv01);
_sum02 = vpadalq_s16(_sum02, _wv02);
_sum03 = vpadalq_s16(_sum03, _wv03);
_sum10 = vpadalq_s16(_sum10, _wv10);
_sum11 = vpadalq_s16(_sum11, _wv11);
_sum12 = vpadalq_s16(_sum12, _wv12);
_sum13 = vpadalq_s16(_sum13, _wv13);
tmpptr += 16;
kptr0 += 32;
}
int32x4_t _s001 = vpaddq_s32(_sum00, _sum01);
int32x4_t _s023 = vpaddq_s32(_sum02, _sum03);
int32x4_t _s101 = vpaddq_s32(_sum10, _sum11);
int32x4_t _s123 = vpaddq_s32(_sum12, _sum13);
int32x4_t _sum0 = vpaddq_s32(_s001, _s023);
int32x4_t _sum1 = vpaddq_s32(_s101, _s123);
vst1q_lane_s32(outptr0, _sum0, 0);
vst1q_lane_s32(outptr1, _sum0, 1);
vst1q_lane_s32(outptr2, _sum0, 2);
vst1q_lane_s32(outptr3, _sum0, 3);
vst1q_lane_s32(outptr0 + 1, _sum1, 0);
vst1q_lane_s32(outptr1 + 1, _sum1, 1);
vst1q_lane_s32(outptr2 + 1, _sum1, 2);
vst1q_lane_s32(outptr3 + 1, _sum1, 3);
outptr0 += 2;
outptr1 += 2;
outptr2 += 2;
outptr3 += 2;
#endif // __ARM_FEATURE_DOTPROD
#else // __aarch64__
asm volatile(
"veor q0, q0 \n"
"veor q1, q1 \n"
"veor q2, q2 \n"
"veor q3, q3 \n"
"veor q4, q4 \n"
"veor q5, q5 \n"
"veor q6, q6 \n"
"veor q7, q7 \n"
"pld [%5, #256] \n"
"lsr r4, %4, #1 \n" // r4 = nn = size >> 1
"cmp r4, #0 \n"
"beq 1f \n"
"add r5, %6, #16 \n"
"pld [%6, #128] \n"
"mov r6, #32 \n"
"pld [%6, #384] \n"
"vld1.s8 {d20-d21}, [%6 :128], r6 \n" // _w01
"vld1.s8 {d16-d19}, [%5 :128]! \n" // _val0 _val1
"vld1.s8 {d22-d23}, [%6 :128], r6 \n" // _w45
"0: \n"
"vmull.s8 q12, d16, d20 \n"
"pld [%5, #256] \n"
"vmull.s8 q13, d16, d21 \n"
"pld [%6, #384] \n"
"vmull.s8 q14, d17, d20 \n"
"vmull.s8 q15, d17, d21 \n"
"vld1.s8 {d20-d21}, [r5 :128], r6 \n" // _w23
"vmlal.s8 q12, d18, d22 \n"
"vmlal.s8 q13, d18, d23 \n"
"subs r4, r4, #1 \n"
"vmlal.s8 q14, d19, d22 \n"
"vmlal.s8 q15, d19, d23 \n"
"vld1.s8 {d22-d23}, [r5 :128], r6 \n" // _w67
"vpadal.s16 q0, q12 \n"
"vmull.s8 q12, d16, d20 \n"
"vpadal.s16 q1, q13 \n"
"vmull.s8 q13, d16, d21 \n"
"vpadal.s16 q4, q14 \n"
"vmull.s8 q14, d17, d20 \n"
"vpadal.s16 q5, q15 \n"
"vmull.s8 q15, d17, d21 \n"
"vld1.s8 {d16-d17}, [%5 :128]! \n" // _val0
"vmlal.s8 q12, d18, d22 \n"
"vld1.s8 {d20-d21}, [%6 :128], r6 \n" // _w01
"vmlal.s8 q13, d18, d23 \n"
"pld [r5, #128] \n"
"vmlal.s8 q14, d19, d22 \n"
"pld [r5, #384] \n"
"vmlal.s8 q15, d19, d23 \n"
"vld1.s8 {d18-d19}, [%5 :128]! \n" // _val1
"vpadal.s16 q2, q12 \n"
"vld1.s8 {d22-d23}, [%6 :128], r6 \n" // _w45
"vpadal.s16 q3, q13 \n"
"pld [%5, #128] \n"
"vpadal.s16 q6, q14 \n"
"pld [%6, #128] \n"
"vpadal.s16 q7, q15 \n"
"bne 0b \n"
"sub %5, %5, #32 \n"
"sub %6, %6, #64 \n"
"1: \n"
"and r4, %4, #1 \n" // r4 = remain = size & 1
"cmp r4, #0 \n" // r4 > 0
"beq 2f \n"
"vld1.s8 {d16-d17}, [%5 :128]! \n" // _val
"vld1.s8 {d20-d21}, [%6 :128]! \n" // _w01
"vmull.s8 q12, d16, d20 \n"
"vld1.s8 {d22-d23}, [%6 :128]! \n" // _w23
"vmull.s8 q13, d16, d21 \n"
"vmull.s8 q14, d17, d20 \n"
"vmull.s8 q15, d17, d21 \n"
"vpadal.s16 q0, q12 \n"
"vmull.s8 q12, d16, d22 \n"
"vpadal.s16 q1, q13 \n"
"vmull.s8 q13, d16, d23 \n"
"vpadal.s16 q4, q14 \n"
"vmull.s8 q14, d17, d22 \n"
"vpadal.s16 q5, q15 \n"
"vmull.s8 q15, d17, d23 \n"
"vpadal.s16 q2, q12 \n"
"vpadal.s16 q3, q13 \n"
"vpadal.s16 q6, q14 \n"
"vpadal.s16 q7, q15 \n"
"2: \n"
"vpadd.s32 d16, d0, d1 \n"
"vpadd.s32 d17, d2, d3 \n"
"vpadd.s32 d18, d4, d5 \n"
"vpadd.s32 d19, d6, d7 \n"
"vpadd.s32 d20, d8, d9 \n"
"vpadd.s32 d21, d10, d11 \n"
"vpadd.s32 d22, d12, d13 \n"
"vpadd.s32 d23, d14, d15 \n"
"vpadd.s32 d0, d16, d17 \n"
"vpadd.s32 d1, d18, d19 \n"
"vpadd.s32 d2, d20, d21 \n"
"vpadd.s32 d3, d22, d23 \n"
"vst1.s32 {d0[0]}, [%0]! \n"
"vst1.s32 {d0[1]}, [%1]! \n"
"vst1.s32 {d1[0]}, [%2]! \n"
"vst1.s32 {d1[1]}, [%3]! \n"
"vst1.s32 {d2[0]}, [%0]! \n"
"vst1.s32 {d2[1]}, [%1]! \n"
"vst1.s32 {d3[0]}, [%2]! \n"
"vst1.s32 {d3[1]}, [%3]! \n"
: "=r"(outptr0),
"=r"(outptr1),
"=r"(outptr2),
"=r"(outptr3),
"=r"(nn),
"=r"(tmpptr),
"=r"(kptr0)
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(nn),
"5"(tmpptr),
"6"(kptr0)
: "memory", "r4", "r5", "r6", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
}
for (; i < size; i++)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
#else
const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2);
#endif
#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 __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
for (int j = 0; j < nn; j++)
{
int8x8_t _val0_l_h = vld1_s8(tmpptr);
int8x16_t _w0123_l = vld1q_s8(kptr0);
_sum0 = vdotq_lane_s32(_sum0, _w0123_l, _val0_l_h, 0);
int8x16_t _w0123_h = vld1q_s8(kptr0 + 16);
_sum0 = vdotq_lane_s32(_sum0, _w0123_h, _val0_l_h, 1);
tmpptr += 8;
kptr0 += 32;
}
vst1q_lane_s32(outptr0, _sum0, 0);
vst1q_lane_s32(outptr1, _sum0, 1);
vst1q_lane_s32(outptr2, _sum0, 2);
vst1q_lane_s32(outptr3, _sum0, 3);
outptr0 += 1;
outptr1 += 1;
outptr2 += 1;
outptr3 += 1;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x16_t _w01 = vld1q_s8(kptr0);
int8x16_t _w23 = vld1q_s8(kptr0 + 16);
int16x8_t _wv0 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w01));
int16x8_t _wv1 = vmull_s8(vget_low_s8(_val), vget_high_s8(_w01));
int16x8_t _wv2 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w23));
int16x8_t _wv3 = vmull_s8(vget_low_s8(_val), vget_high_s8(_w23));
int8x16_t _w45 = vld1q_s8(kptr0 + 32);
int8x16_t _w67 = vld1q_s8(kptr0 + 48);
_wv0 = vmlal_s8(_wv0, vget_high_s8(_val), vget_low_s8(_w45));
_wv1 = vmlal_s8(_wv1, vget_high_s8(_val), vget_high_s8(_w45));
_wv2 = vmlal_s8(_wv2, vget_high_s8(_val), vget_low_s8(_w67));
_wv3 = vmlal_s8(_wv3, vget_high_s8(_val), vget_high_s8(_w67));
_sum0 = vpadalq_s16(_sum0, _wv0);
_sum1 = vpadalq_s16(_sum1, _wv1);
_sum2 = vpadalq_s16(_sum2, _wv2);
_sum3 = vpadalq_s16(_sum3, _wv3);
tmpptr += 16;
kptr0 += 64;
}
for (; j < nn; j++)
{
int8x8_t _val = vld1_s8(tmpptr);
int8x16_t _w01 = vld1q_s8(kptr0);
int8x16_t _w23 = vld1q_s8(kptr0 + 16);
int16x8_t _wv0 = vmull_s8(_val, vget_low_s8(_w01));
int16x8_t _wv1 = vmull_s8(_val, vget_high_s8(_w01));
int16x8_t _wv2 = vmull_s8(_val, vget_low_s8(_w23));
int16x8_t _wv3 = vmull_s8(_val, vget_high_s8(_w23));
_sum0 = vpadalq_s16(_sum0, _wv0);
_sum1 = vpadalq_s16(_sum1, _wv1);
_sum2 = vpadalq_s16(_sum2, _wv2);
_sum3 = vpadalq_s16(_sum3, _wv3);
tmpptr += 8;
kptr0 += 32;
}
#if __aarch64__
int32x4_t _s01 = vpaddq_s32(_sum0, _sum1);
int32x4_t _s23 = vpaddq_s32(_sum2, _sum3);
_sum0 = vpaddq_s32(_s01, _s23);
#else
int32x2_t _s01_low = vpadd_s32(vget_low_s32(_sum0), vget_high_s32(_sum0));
int32x2_t _s01_high = vpadd_s32(vget_low_s32(_sum1), vget_high_s32(_sum1));
int32x2_t _s23_low = vpadd_s32(vget_low_s32(_sum2), vget_high_s32(_sum2));
int32x2_t _s23_high = vpadd_s32(vget_low_s32(_sum3), vget_high_s32(_sum3));
_sum0 = vcombine_s32(vpadd_s32(_s01_low, _s01_high), vpadd_s32(_s23_low, _s23_high));
#endif
vst1q_lane_s32(outptr0, _sum0, 0);
vst1q_lane_s32(outptr1, _sum0, 1);
vst1q_lane_s32(outptr2, _sum0, 2);
vst1q_lane_s32(outptr3, _sum0, 3);
outptr0 += 1;
outptr1 += 1;
outptr2 += 1;
outptr3 += 1;
#endif // __ARM_FEATURE_DOTPROD
}
}
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 __aarch64__
#if __ARM_FEATURE_DOTPROD
for (; i + 15 < size; i += 16)
{
const signed char* tmpptr = tmp.channel(i / 16);
const signed char* kptr0 = kernel.channel(p / 4 + p % 4);
int nn = inch * maxk; // inch always > 0
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int j = 0;
for (; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _val4567_l = vld1q_s8(tmpptr + 16);
int8x16_t _val89ab_l = vld1q_s8(tmpptr + 32);
int8x16_t _valcdef_l = vld1q_s8(tmpptr + 48);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 64);
int8x16_t _val4567_h = vld1q_s8(tmpptr + 80);
int8x16_t _val89ab_h = vld1q_s8(tmpptr + 96);
int8x16_t _valcdef_h = vld1q_s8(tmpptr + 112);
int8x8_t _w_lh = vld1_s8(kptr0);
_sum0 = vdotq_lane_s32(_sum0, _val0123_l, _w_lh, 0);
_sum1 = vdotq_lane_s32(_sum1, _val4567_l, _w_lh, 0);
_sum2 = vdotq_lane_s32(_sum2, _val89ab_l, _w_lh, 0);
_sum3 = vdotq_lane_s32(_sum3, _valcdef_l, _w_lh, 0);
_sum0 = vdotq_lane_s32(_sum0, _val0123_h, _w_lh, 1);
_sum1 = vdotq_lane_s32(_sum1, _val4567_h, _w_lh, 1);
_sum2 = vdotq_lane_s32(_sum2, _val89ab_h, _w_lh, 1);
_sum3 = vdotq_lane_s32(_sum3, _valcdef_h, _w_lh, 1);
tmpptr += 128;
kptr0 += 8;
}
vst1q_s32(outptr0, _sum0);
vst1q_s32(outptr0 + 4, _sum1);
vst1q_s32(outptr0 + 8, _sum2);
vst1q_s32(outptr0 + 12, _sum3);
outptr0 += 16;
}
for (; i + 7 < size; i += 8)
{
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8);
const signed char* kptr0 = kernel.channel(p / 4 + p % 4);
int nn = inch * maxk; // inch always > 0
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int j = 0;
for (; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _val4567_l = vld1q_s8(tmpptr + 16);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 32);
int8x16_t _val4567_h = vld1q_s8(tmpptr + 48);
int8x8_t _w_lh = vld1_s8(kptr0);
_sum0 = vdotq_lane_s32(_sum0, _val0123_l, _w_lh, 0);
_sum1 = vdotq_lane_s32(_sum1, _val4567_l, _w_lh, 0);
_sum2 = vdotq_lane_s32(_sum2, _val0123_h, _w_lh, 1);
_sum3 = vdotq_lane_s32(_sum3, _val4567_h, _w_lh, 1);
tmpptr += 64;
kptr0 += 8;
}
_sum0 = vaddq_s32(_sum0, _sum2);
_sum1 = vaddq_s32(_sum1, _sum3);
vst1q_s32(outptr0, _sum0);
vst1q_s32(outptr0 + 4, _sum1);
outptr0 += 8;
}
#endif // __ARM_FEATURE_DOTPROD
for (; i + 3 < size; i += 4)
{
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4);
#else
const signed char* tmpptr = tmp.channel(i / 4);
#endif
const signed char* kptr0 = kernel.channel(p / 4 + p % 4);
int nn = inch * maxk; // inch always > 0
#if __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int j = 0;
for (; j < nn; j++)
{
int8x16_t _val0123_l = vld1q_s8(tmpptr);
int8x16_t _val0123_h = vld1q_s8(tmpptr + 16);
int8x8_t _w_lh = vld1_s8(kptr0);
_sum0 = vdotq_lane_s32(_sum0, _val0123_l, _w_lh, 0);
_sum1 = vdotq_lane_s32(_sum1, _val0123_h, _w_lh, 1);
tmpptr += 32;
kptr0 += 8;
}
_sum0 = vaddq_s32(_sum0, _sum1);
vst1q_s32(outptr0, _sum0);
outptr0 += 4;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int32x4_t _sum4 = vdupq_n_s32(0);
int32x4_t _sum5 = vdupq_n_s32(0);
int32x4_t _sum6 = vdupq_n_s32(0);
int32x4_t _sum7 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val0 = vld1q_s8(tmpptr);
int8x16_t _val1 = vld1q_s8(tmpptr + 16);
int8x16_t _val2 = vld1q_s8(tmpptr + 32);
int8x16_t _val3 = vld1q_s8(tmpptr + 48);
int8x16_t _w = vld1q_s8(kptr0);
int16x8_t _s0 = vmull_s8(vget_low_s8(_val0), vget_low_s8(_w));
int16x8_t _s1 = vmull_s8(vget_high_s8(_val0), vget_low_s8(_w));
int16x8_t _s2 = vmull_s8(vget_low_s8(_val1), vget_low_s8(_w));
int16x8_t _s3 = vmull_s8(vget_high_s8(_val1), vget_low_s8(_w));
_s0 = vmlal_s8(_s0, vget_low_s8(_val2), vget_high_s8(_w));
_s1 = vmlal_s8(_s1, vget_high_s8(_val2), vget_high_s8(_w));
_s2 = vmlal_s8(_s2, vget_low_s8(_val3), vget_high_s8(_w));
_s3 = vmlal_s8(_s3, vget_high_s8(_val3), vget_high_s8(_w));
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s0));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s0));
_sum2 = vaddw_s16(_sum2, vget_low_s16(_s1));
_sum3 = vaddw_s16(_sum3, vget_high_s16(_s1));
_sum4 = vaddw_s16(_sum4, vget_low_s16(_s2));
_sum5 = vaddw_s16(_sum5, vget_high_s16(_s2));
_sum6 = vaddw_s16(_sum6, vget_low_s16(_s3));
_sum7 = vaddw_s16(_sum7, vget_high_s16(_s3));
tmpptr += 64;
kptr0 += 16;
}
for (; j < nn; j++)
{
int8x16_t _val0 = vld1q_s8(tmpptr);
int8x16_t _val1 = vld1q_s8(tmpptr + 16);
int8x8_t _w = vld1_s8(kptr0);
int16x8_t _s0 = vmull_s8(vget_low_s8(_val0), _w);
int16x8_t _s1 = vmull_s8(vget_high_s8(_val0), _w);
int16x8_t _s2 = vmull_s8(vget_low_s8(_val1), _w);
int16x8_t _s3 = vmull_s8(vget_high_s8(_val1), _w);
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s0));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s0));
_sum2 = vaddw_s16(_sum2, vget_low_s16(_s1));
_sum3 = vaddw_s16(_sum3, vget_high_s16(_s1));
_sum4 = vaddw_s16(_sum4, vget_low_s16(_s2));
_sum5 = vaddw_s16(_sum5, vget_high_s16(_s2));
_sum6 = vaddw_s16(_sum6, vget_low_s16(_s3));
_sum7 = vaddw_s16(_sum7, vget_high_s16(_s3));
tmpptr += 32;
kptr0 += 8;
}
_sum0 = vaddq_s32(_sum0, _sum1);
_sum2 = vaddq_s32(_sum2, _sum3);
_sum4 = vaddq_s32(_sum4, _sum5);
_sum6 = vaddq_s32(_sum6, _sum7);
int32x2_t _s0 = vadd_s32(vget_low_s32(_sum0), vget_high_s32(_sum0));
int32x2_t _s2 = vadd_s32(vget_low_s32(_sum2), vget_high_s32(_sum2));
int32x2_t _s4 = vadd_s32(vget_low_s32(_sum4), vget_high_s32(_sum4));
int32x2_t _s6 = vadd_s32(vget_low_s32(_sum6), vget_high_s32(_sum6));
int32x2_t _ss0 = vpadd_s32(_s0, _s2);
int32x2_t _ss1 = vpadd_s32(_s4, _s6);
int32x4_t _ss = vcombine_s32(_ss0, _ss1);
vst1q_s32(outptr0, _ss);
outptr0 += 4;
#endif // __ARM_FEATURE_DOTPROD
}
#endif // __aarch64__
for (; i + 1 < size; i += 2)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2);
#else
const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2);
#endif
#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 __ARM_FEATURE_DOTPROD
int32x2_t _sum0 = vdup_n_s32(0);
int32x2_t _sum1 = vdup_n_s32(0);
int j = 0;
for (; j < nn; j++)
{
int8x16_t _val01_lh = vld1q_s8(tmpptr);
int8x8_t _w_lh = vld1_s8(kptr0);
_sum0 = vdot_lane_s32(_sum0, vget_low_s8(_val01_lh), _w_lh, 0);
_sum1 = vdot_lane_s32(_sum1, vget_high_s8(_val01_lh), _w_lh, 1);
tmpptr += 16;
kptr0 += 8;
}
int32x2_t _sum = vadd_s32(_sum0, _sum1);
vst1_s32(outptr0, _sum);
outptr0 += 2;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int32x4_t _sum2 = vdupq_n_s32(0);
int32x4_t _sum3 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val0 = vld1q_s8(tmpptr);
int8x16_t _val1 = vld1q_s8(tmpptr + 16);
int8x16_t _w = vld1q_s8(kptr0);
int16x8_t _s0 = vmull_s8(vget_low_s8(_val0), vget_low_s8(_w));
int16x8_t _s1 = vmull_s8(vget_high_s8(_val0), vget_low_s8(_w));
_s0 = vmlal_s8(_s0, vget_low_s8(_val1), vget_high_s8(_w));
_s1 = vmlal_s8(_s1, vget_high_s8(_val1), vget_high_s8(_w));
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s0));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s0));
_sum2 = vaddw_s16(_sum2, vget_low_s16(_s1));
_sum3 = vaddw_s16(_sum3, vget_high_s16(_s1));
tmpptr += 32;
kptr0 += 16;
}
for (; j < nn; j++)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x8_t _w = vld1_s8(kptr0);
int16x8_t _s0 = vmull_s8(vget_low_s8(_val), _w);
int16x8_t _s1 = vmull_s8(vget_high_s8(_val), _w);
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s0));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s0));
_sum2 = vaddw_s16(_sum2, vget_low_s16(_s1));
_sum3 = vaddw_s16(_sum3, vget_high_s16(_s1));
tmpptr += 16;
kptr0 += 8;
}
_sum0 = vaddq_s32(_sum0, _sum1);
_sum2 = vaddq_s32(_sum2, _sum3);
int32x2_t _s0 = vadd_s32(vget_low_s32(_sum0), vget_high_s32(_sum0));
int32x2_t _s2 = vadd_s32(vget_low_s32(_sum2), vget_high_s32(_sum2));
int32x2_t _ss = vpadd_s32(_s0, _s2);
vst1_s32(outptr0, _ss);
outptr0 += 2;
#endif // __ARM_FEATURE_DOTPROD
}
for (; i < size; i++)
{
#if __aarch64__
#if __ARM_FEATURE_DOTPROD
const signed char* tmpptr = tmp.channel(i / 16 + (i % 16) / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
#else
const signed char* tmpptr = tmp.channel(i / 4 + (i % 4) / 2 + i % 2);
#endif
#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
#if __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x2_t _sum1 = vdup_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x16_t _w = vld1q_s8(kptr0);
_sum0 = vdotq_s32(_sum0, _val, _w);
tmpptr += 16;
kptr0 += 16;
}
for (; j < nn; j++)
{
int8x8_t _val = vld1_s8(tmpptr);
int8x8_t _w = vld1_s8(kptr0);
_sum1 = vdot_s32(_sum1, _val, _w);
tmpptr += 8;
kptr0 += 8;
}
int sum = vaddvq_s32(_sum0) + vaddv_s32(_sum1);
outptr0[0] = sum;
outptr0 += 1;
#else // __ARM_FEATURE_DOTPROD
int32x4_t _sum0 = vdupq_n_s32(0);
int32x4_t _sum1 = vdupq_n_s32(0);
int j = 0;
for (; j + 1 < nn; j += 2)
{
int8x16_t _val = vld1q_s8(tmpptr);
int8x16_t _w = vld1q_s8(kptr0);
int16x8_t _s8 = vmull_s8(vget_low_s8(_val), vget_low_s8(_w));
_s8 = vmlal_s8(_s8, vget_high_s8(_val), vget_high_s8(_w));
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s8));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s8));
tmpptr += 16;
kptr0 += 16;
}
for (; j < nn; j++)
{
int8x8_t _val = vld1_s8(tmpptr);
int8x8_t _w = vld1_s8(kptr0);
int16x8_t _s8 = vmull_s8(_val, _w);
_sum0 = vaddw_s16(_sum0, vget_low_s16(_s8));
_sum1 = vaddw_s16(_sum1, vget_high_s16(_s8));
tmpptr += 8;
kptr0 += 8;
}
int32x4_t _sum = vaddq_s32(_sum0, _sum1);
#if __aarch64__
int sum = vaddvq_s32(_sum); // dot
#else
int32x2_t _ss = vadd_s32(vget_low_s32(_sum), vget_high_s32(_sum));
_ss = vpadd_s32(_ss, _ss);
int sum = vget_lane_s32(_ss, 0);
#endif
outptr0[0] = sum;
outptr0 += 1;
#endif // __ARM_FEATURE_DOTPROD
}
}
}
static void convolution_im2col_sgemm_transform_kernel_pack8to1_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h)
{
#if NCNN_RUNTIME_CPU && NCNN_ARM82DOT && __ARM_NEON && __aarch64__ && !__ARM_FEATURE_DOTPROD
if (ncnn::cpu_support_arm_asimddp())
{
convolution_im2col_sgemm_transform_kernel_pack8to1_int8_neon_asimddp(_kernel, kernel_tm, inch, outch, kernel_w, kernel_h);
return;
}
#endif
const int maxk = kernel_w * kernel_h;
// interleave
// src = maxk-inch-outch
// dst = 8a-4b-maxk-inch/8a-outch/4b
// dst = 4a-4b-2-maxk-inch/8a-outch/4b (arm82)
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++)
{
#if __ARM_FEATURE_DOTPROD
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
const signed char* k00 = kernel.channel(q + i).row<const signed char>(p + j);
g00[0] = k00[k];
g00++;
}
}
for (int i = 0; i < 4; i++)
{
for (int j = 4; j < 8; j++)
{
const signed char* k00 = kernel.channel(q + i).row<const signed char>(p + j);
g00[0] = k00[k];
g00++;
}
}
#else
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++;
}
}
#endif
}
}
}
// 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_neon(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) * 8;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const Mat img = bottom_blob.channel(p);
signed char* ptr = bottom_im2col.channel(p);
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
const signed char* sptr = img.row<const signed char>(dilation_h * u) + dilation_w * v * 8;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
int8x8_t _val0 = vld1_s8(sptr);
int8x8_t _val1 = vld1_s8(sptr + stride_w * 8);
int8x8_t _val2 = vld1_s8(sptr + stride_w * 16);
int8x8_t _val3 = vld1_s8(sptr + stride_w * 24);
vst1_s8(ptr, _val0);
vst1_s8(ptr + 8, _val1);
vst1_s8(ptr + 16, _val2);
vst1_s8(ptr + 24, _val3);
sptr += stride_w * 32;
ptr += 32;
}
for (; j + 1 < outw; j += 2)
{
int8x8_t _val0 = vld1_s8(sptr);
int8x8_t _val1 = vld1_s8(sptr + stride_w * 8);
vst1_s8(ptr, _val0);
vst1_s8(ptr + 8, _val1);
sptr += stride_w * 16;
ptr += 16;
}
for (; j < outw; j++)
{
int8x8_t _val = vld1_s8(sptr);
vst1_s8(ptr, _val);
sptr += stride_w * 8;
ptr += 8;
}
sptr += gap;
}
}
}
}
}
im2col_sgemm_pack8to1_int8_neon(bottom_im2col, top_blob, kernel, opt);
}
|
GB_bitmap_assign_M_all_template.c | //------------------------------------------------------------------------------
// GB_bitmap_assign_M_all_template: traverse M for GB_ASSIGN
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// M is sparse or hypersparse, not bitmap or full. C<M>(I,J) = ... is being
// computed (or !M), and all entries in M are traversed. For a given entry
// M (iM,jM) in the mask, the entry C(iM,jM) is accessed at location pC.
// C is bitmap/full. M is sparse/hyper, and can be jumbled.
{
const int64_t *restrict kfirst_Mslice = M_ek_slicing ;
const int64_t *restrict klast_Mslice = M_ek_slicing + M_ntasks ;
const int64_t *restrict pstart_Mslice = M_ek_slicing + M_ntasks * 2 ;
int tid ;
#pragma omp parallel for num_threads(M_nthreads) schedule(dynamic,1) \
reduction(+:cnvals)
for (tid = 0 ; tid < M_ntasks ; tid++)
{
int64_t kfirst = kfirst_Mslice [tid] ;
int64_t klast = klast_Mslice [tid] ;
int64_t task_cnvals = 0 ;
//----------------------------------------------------------------------
// traverse over M (:,kfirst:klast)
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// find the part of M(:,k) for this task
//------------------------------------------------------------------
int64_t jM = GBH (Mh, k) ;
int64_t pM_start, pM_end ;
GB_get_pA (&pM_start, &pM_end, tid, k, kfirst,
klast, pstart_Mslice, Mp, mvlen) ;
//------------------------------------------------------------------
// traverse over M(:,jM), the kth vector of M
//------------------------------------------------------------------
// for assign: M is a matrix the same size as C
int64_t jC = jM ;
for (int64_t pM = pM_start ; pM < pM_end ; pM++)
{
bool mij = GB_mcast (Mx, pM, msize) ;
if (mij)
{
int64_t iC = Mi [pM] ;
int64_t pC = iC + jC * cvlen ;
GB_MASK_WORK (pC) ;
}
}
}
cnvals += task_cnvals ;
}
}
|
exchange_boundary_overlap.c | //------------------------------------------------------------------------------------------------------------------------------
// Samuel Williams
// SWWilliams@lbl.gov
// Lawrence Berkeley National Lab
//------------------------------------------------------------------------------------------------------------------------------
// perform a (intra-level) ghost zone exchange
// NOTE exchange_boundary() only exchanges the boundary.
// It will not enforce any boundary conditions
// BC's are either the responsibility of a separate function or should be fused into the stencil
void exchange_boundary(level_type * level, int id, int shape){
double _timeCommunicationStart = getTime();
if(shape>=STENCIL_MAX_SHAPES)shape=STENCIL_SHAPE_BOX; // shape must be < STENCIL_MAX_SHAPES in order to safely index into exchange_ghosts[]
#pragma omp parallel
{
double _timeStart;
int tid = omp_get_thread_num();
int nth = omp_get_num_threads();
int my_tag = (level->tag<<4) | shape;
int buffer=0;
int n;
#ifdef USE_MPI
int nMessages = level->exchange_ghosts[shape].num_recvs + level->exchange_ghosts[shape].num_sends;
MPI_Request *recv_requests = level->exchange_ghosts[shape].requests;
MPI_Request *send_requests = level->exchange_ghosts[shape].requests + level->exchange_ghosts[shape].num_recvs;
// loop through packed list of MPI receives and prepost Irecv's...
if(tid==0){
if(level->exchange_ghosts[shape].num_recvs>0){
_timeStart = getTime();
for(n=0;n<level->exchange_ghosts[shape].num_recvs;n++){
MPI_Irecv(level->exchange_ghosts[shape].recv_buffers[n],
level->exchange_ghosts[shape].recv_sizes[n],
MPI_DOUBLE,
level->exchange_ghosts[shape].recv_ranks[n],
my_tag,
MPI_COMM_WORLD,
&recv_requests[n]
);
}
level->timers.ghostZone_recv += (getTime()-_timeStart);
}
}
// pack MPI send buffers...
if(tid>0){
if(level->exchange_ghosts[shape].num_blocks[0]){
if(tid==1)_timeStart = getTime();
int lo = ((tid-1)*level->exchange_ghosts[shape].num_blocks[0])/(nth-1);
int hi = ((tid )*level->exchange_ghosts[shape].num_blocks[0])/(nth-1);
for(buffer=lo;buffer<hi;buffer++){
CopyBlock(level,id,&level->exchange_ghosts[shape].blocks[0][buffer]);
}
if(tid==1)level->timers.ghostZone_pack += (getTime()-_timeStart);
}}
#pragma omp barrier // wait for packing
// loop through MPI send buffers and post Isend's...
if(tid==0){
if(level->exchange_ghosts[shape].num_sends>0){
_timeStart = getTime();
for(n=0;n<level->exchange_ghosts[shape].num_sends;n++){
MPI_Isend(level->exchange_ghosts[shape].send_buffers[n],
level->exchange_ghosts[shape].send_sizes[n],
MPI_DOUBLE,
level->exchange_ghosts[shape].send_ranks[n],
my_tag,
MPI_COMM_WORLD,
&send_requests[n]
);
}
level->timers.ghostZone_send += (getTime()-_timeStart);
}
}
#endif
// exchange locally... try and hide within Isend latency...
if(tid>0){
if(level->exchange_ghosts[shape].num_blocks[1]){
if(tid==1)_timeStart = getTime();
int lo = ((tid-1)*level->exchange_ghosts[shape].num_blocks[1])/(nth-1);
int hi = ((tid )*level->exchange_ghosts[shape].num_blocks[1])/(nth-1);
if(hi>level->exchange_ghosts[shape].num_blocks[1])hi=level->exchange_ghosts[shape].num_blocks[1];
for(buffer=lo;buffer<hi;buffer++){
CopyBlock(level,id,&level->exchange_ghosts[shape].blocks[1][buffer]);
}
if(tid==1)level->timers.ghostZone_local += (getTime()-_timeStart);
}}
// wait for MPI to finish...
#ifdef USE_MPI
if(tid==0){
if(nMessages){
_timeStart = getTime();
MPI_Waitall(nMessages,level->exchange_ghosts[shape].requests,level->exchange_ghosts[shape].status);
level->timers.ghostZone_wait += (getTime()-_timeStart);
}
}
#pragma omp barrier // wait for master to WaitAll
// unpack MPI receive buffers
if(level->exchange_ghosts[shape].num_blocks[2]){
if(tid==0)_timeStart = getTime();
#pragma omp for private(buffer) schedule(static,1)
for(buffer=0;buffer<level->exchange_ghosts[shape].num_blocks[2];buffer++){
CopyBlock(level,id,&level->exchange_ghosts[shape].blocks[2][buffer]);
}
if(tid==0)level->timers.ghostZone_unpack += (getTime()-_timeStart);
}
#endif
}
level->timers.ghostZone_total += (double)(getTime()-_timeCommunicationStart);
}
|
GB_binop__rdiv_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 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__rdiv_int8
// A.*B function (eWiseMult): GB_AemultB__rdiv_int8
// A*D function (colscale): GB_AxD__rdiv_int8
// D*A function (rowscale): GB_DxB__rdiv_int8
// C+=B function (dense accum): GB_Cdense_accumB__rdiv_int8
// C+=b function (dense accum): GB_Cdense_accumb__rdiv_int8
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__rdiv_int8
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__rdiv_int8
// C=scalar+B GB_bind1st__rdiv_int8
// C=scalar+B' GB_bind1st_tran__rdiv_int8
// C=A+scalar GB_bind2nd__rdiv_int8
// C=A'+scalar GB_bind2nd_tran__rdiv_int8
// C type: int8_t
// A type: int8_t
// B,b type: int8_t
// BinaryOp: cij = GB_IDIV_SIGNED (bij, aij, 8)
#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) \
int8_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
int8_t bij = Bx [pB]
// 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) \
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_SIGNED (y, x, 8) ;
// 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_RDIV || GxB_NO_INT8 || GxB_NO_RDIV_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__rdiv_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__rdiv_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__rdiv_int8
(
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__rdiv_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__rdiv_int8
(
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
int8_t *GB_RESTRICT Cx = (int8_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_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 *GB_RESTRICT Cx = (int8_t *) 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__rdiv_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 *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__rdiv_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 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__rdiv_int8
(
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
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 < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
int8_t bij = Bx [p] ;
Cx [p] = GB_IDIV_SIGNED (bij, x, 8) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__rdiv_int8
(
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 ;
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 = Ax [p] ;
Cx [p] = GB_IDIV_SIGNED (y, aij, 8) ;
}
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 = Ax [pA] ; \
Cx [pC] = GB_IDIV_SIGNED (aij, x, 8) ; \
}
GrB_Info GB_bind1st_tran__rdiv_int8
(
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 \
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 = Ax [pA] ; \
Cx [pC] = GB_IDIV_SIGNED (y, aij, 8) ; \
}
GrB_Info GB_bind2nd_tran__rdiv_int8
(
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
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
stream.c | /*-----------------------------------------------------------------------*/
/* Program: Stream */
/* Revision: $Id: stream.c,v 1.11 2012/07/18 14:24:24 rajamony Exp $ */
/* Original code developed by John D. McCalpin */
/* Programmers: John D. McCalpin */
/* Joe R. Zagar */
/* */
/* This program measures memory transfer rates in GB/s for simple */
/* computational kernels coded in C. */
/*-----------------------------------------------------------------------*/
/* Copyright 1991-2003: John D. McCalpin */
/*-----------------------------------------------------------------------*/
/* License: */
/* 1. You are free to use this program and/or to redistribute */
/* this program. */
/* 2. You are free to modify this program for your own use, */
/* including commercial use, subject to the publication */
/* restrictions in item 3. */
/* 3. You are free to publish results obtained from running this */
/* program, or from works that you derive from this program, */
/* with the following limitations: */
/* 3a. In order to be referred to as "STREAM benchmark results", */
/* published results must be in conformance to the STREAM */
/* Run Rules, (briefly reviewed below) published at */
/* http://www.cs.virginia.edu/stream/ref.html */
/* and incorporated herein by reference. */
/* As the copyright holder, John McCalpin retains the */
/* right to determine conformity with the Run Rules. */
/* 3b. Results based on modified source code or on runs not in */
/* accordance with the STREAM Run Rules must be clearly */
/* labelled whenever they are published. Examples of */
/* proper labelling include: */
/* "tuned STREAM benchmark results" */
/* "based on a variant of the STREAM benchmark code" */
/* Other comparable, clear and reasonable labelling is */
/* acceptable. */
/* 3c. Submission of results to the STREAM benchmark web site */
/* is encouraged, but not required. */
/* 4. Use of this program or creation of derived works based on this */
/* program constitutes acceptance of these licensing restrictions. */
/* 5. Absolutely no warranty is expressed or implied. */
/*-----------------------------------------------------------------------*/
#include <float.h>
#include <limits.h>
#include <stdint.h>
#include "utils.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#define TUNED 1
#define VERBOSE 1
/* INSTRUCTIONS:
*
* 1) Stream requires a good bit of memory to run. Adjust the
* value of 'N' (below) to give a 'timing calibration' of
* at least 20 clock-ticks. This will provide rate estimates
* that should be good to about 5% precision.
*/
static uint64_t VectorSize = 1650163200;
# define N 2000000
# define NTIMES 10
# define OFFSET 0
/*
* 3) Compile the code with full optimization. Many compilers
* generate unreasonably bad code before the optimizer tightens
* things up. If the results are unreasonably good, on the
* other hand, the optimizer might be too smart for me!
*
* Try compiling with:
* cc -O stream_omp.c -o stream_omp
*
* This is known to work on Cray, SGI, IBM, and Sun machines.
*
*
* 4) Mail the results to mccalpin@cs.virginia.edu
* Be sure to include:
* a) computer hardware model number and software revision
* b) the compiler flags
* c) all of the output from the test case.
* Thanks!
*
*/
# define HLINE "-------------------------------------------------------------\n"
static double *a, *b, *c;
static double avgtime[4] = {0}, maxtime[4] = {0},
mintime[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX};
static char *label[4] = {"Copy: ", "Scale: ",
"Add: ", "Triad: "};
static double bytes[4] = {
2 * sizeof(double),
2 * sizeof(double),
3 * sizeof(double),
3 * sizeof(double)
};
#define mysecond GetTime
#ifdef TUNED
extern void tuned_STREAM_Copy(void);
extern void tuned_STREAM_Scale(double scalar);
extern void tuned_STREAM_Add(void);
extern void tuned_STREAM_Triad(double scalar);
#endif
static void
checkSTREAMresults (FILE *outFile, int doIO, int *failure)
{
double aj,bj,cj,scalar;
double asum,bsum,csum;
double epsilon;
uint64_t j,k;
/* reproduce initialization */
aj = 1.0;
bj = 2.0;
cj = 0.0;
/* a[] is modified during timing check */
aj = 2.0E0 * aj;
/* now execute timing loop */
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
cj = aj;
bj = scalar*cj;
cj = aj+bj;
aj = bj+scalar*cj;
}
#if 0
if (doIO) {
fprintf (stderr, "aj: %f\n", aj); for (j=0; j<VectorSize; j++) {if (a[j] != aj) fprintf (outFile, "bad at %d = %f\n", j, a[j]); }
fprintf (stderr, "bj: %f\n", bj); for (j=0; j<VectorSize; j++) {if (b[j] != bj) fprintf (outFile, "bad at %d = %f\n", j, b[j]); }
fprintf (stderr, "cj: %f\n", cj); for (j=0; j<VectorSize; j++) {if (c[j] != cj) fprintf (outFile, "bad at %d = %f\n", j, c[j]); }
}
#endif
// ----- START FIX OF STREAM VALIDATION - OLD METHOD IS ALL WRONG - emailed Piotr Luczek about it and have his concurrence
#if 0
aj = aj * (double) VectorSize;
bj = bj * (double) VectorSize;
cj = cj * (double) VectorSize;
#endif
int abad = 0, bbad = 0, cbad = 0;
asum = 0.0;
bsum = 0.0;
csum = 0.0;
for (j=0; j<VectorSize; j++) {
abad += (aj != a[j]);
bbad += (bj != b[j]);
cbad += (cj != c[j]);
}
asum = (abad == 0) ? aj : 0;
bsum = (bbad == 0) ? bj : 0;
csum = (cbad == 0) ? cj : 0;
// END FIX OF STREAM VALIDATION - OLD VALIDATION CAN NOW TAKE OVER
#ifdef VERBOSE
if (doIO) {
fprintf( outFile, "Results Comparison: \n");
fprintf( outFile, " Expected : %f %f %f \n",aj,bj,cj);
fprintf( outFile, " Observed : %f %f %f \n",asum,bsum,csum);
}
#endif
epsilon = 1.e-8;
*failure = 1;
if (fabs(aj-asum)/asum > epsilon) {
if (doIO) {
fprintf( outFile, "Failed Validation on array a[]\n");
fprintf( outFile, " Expected : %f \n",aj);
fprintf( outFile, " Observed : %f \n",asum);
}
}
else if (fabs(bj-bsum)/bsum > epsilon) {
if (doIO) {
fprintf( outFile, "Failed Validation on array b[]\n");
fprintf( outFile, " Expected : %f \n",bj);
fprintf( outFile, " Observed : %f \n",bsum);
}
}
else if (fabs(cj-csum)/csum > epsilon) {
if (doIO) {
fprintf( outFile, "Failed Validation on array c[]\n");
fprintf( outFile, " Expected : %f \n",cj);
fprintf( outFile, " Observed : %f \n",csum);
}
}
else {
*failure = 0;
if (doIO) fprintf( outFile, "Solution Validates\n");
}
}
# define M 20
static int
checktick()
{
int i, minDelta, Delta;
double t1, t2, timesfound[M];
/* Collect a sequence of M unique time values from the system. */
for (i = 0; i < M; i++) {
t1 = mysecond();
while( ((t2=mysecond()) - t1) < 1.0E-6 )
;
timesfound[i] = t1 = t2;
}
/*
* Determine the minimum difference between these M values.
* This result will be our estimate (in microseconds) for the
* clock granularity.
*/
minDelta = 1000000;
for (i = 1; i < M; i++) {
Delta = (int)( 1.0E6 * (timesfound[i]-timesfound[i-1]));
minDelta = Mmin(minDelta, Mmax(Delta,0));
}
return(minDelta);
}
#undef M
int
HPCC_Stream(HPCC_Params *params, int doIO, double *copyGBs, double *scaleGBs, double *addGBs,
double *triadGBs, int *failure) {
int quantum;
int BytesPerWord;
register int j, k;
double scalar, t, times[4][NTIMES];
FILE *outFile;
double GiBs = 1073741824.0, curGBs;
if (doIO) {
// outFile = fopen( params->outFname, "w+" );
outFile = stdout;
if (! outFile) {
outFile = stderr;
fprintf( outFile, "Cannot open output file.\n" );
return 1;
}
}
// VectorSize = HPCC_LocalVectorSize( params, 3, sizeof(double), 0 ); /* Need 3 vectors */
// HARDCODED VectorSize
// params->StreamVectorSize = VectorSize;
a = HPCC_XMALLOC( double, VectorSize );
b = HPCC_XMALLOC( double, VectorSize );
c = HPCC_XMALLOC( double, VectorSize );
if (!a || !b || !c) {
if (c) HPCC_free(c);
if (b) HPCC_free(b);
if (a) HPCC_free(a);
if (doIO) {
fprintf( outFile, "Failed to allocate memory (%lu).\n", VectorSize );
fflush( outFile );
fclose( outFile );
}
return 1;
}
/* --- SETUP --- determine precision and check timing --- */
if (doIO) {
fprintf (outFile, "Generated on %s\n", params->nowASCII);
fprintf( outFile, HLINE);
BytesPerWord = sizeof(double);
fprintf( outFile, "This system uses %d bytes per DOUBLE PRECISION word.\n",
BytesPerWord);
fprintf( outFile, HLINE);
fprintf( outFile, "Array size = %lu, Offset = %d\n" , VectorSize, OFFSET);
fprintf( outFile, "Total memory required = %.4f GiB.\n",
(3.0 * BytesPerWord) * ( (double) VectorSize / GiBs));
fprintf( outFile, "Each test is run %d times, but only\n", NTIMES);
fprintf( outFile, "the *best* time for each is used.\n");
fflush ( outFile);
}
#ifdef _OPENMP
if (doIO) fprintf( outFile, HLINE);
#pragma omp parallel private(k)
{
#pragma omp single nowait
{
k = omp_get_num_threads();
if (doIO) fprintf( outFile, "Number of Threads requested = %i\n",k);
params->StreamThreads = k;
}
}
#endif
/* Get initial value for system clock. */
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j=0; j<VectorSize; j++) {
a[j] = 1.0;
b[j] = 2.0;
c[j] = 0.0;
}
if (doIO) fprintf( outFile, HLINE);
if ( (quantum = checktick()) >= 1) {
if (doIO) fprintf( outFile, "Your clock granularity/precision appears to be "
"%d microseconds.\n", quantum);
} else {
if (doIO) fprintf( outFile, "Your clock granularity appears to be "
"less than one microsecond.\n");
}
t = mysecond();
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j = 0; j < VectorSize; j++)
a[j] = 2.0E0 * a[j];
t = 1.0E6 * (mysecond() - t);
if (doIO) {
fprintf( outFile, "Each test below will take on the order"
" of %d microseconds.\n", (int) t );
fprintf( outFile, " (= %d clock ticks)\n", (int) (t/quantum) );
fprintf( outFile, "Increase the size of the arrays if this shows that\n");
fprintf( outFile, "you are not getting at least 20 clock ticks per test.\n");
fprintf( outFile, HLINE);
fprintf( outFile, "WARNING -- The above is only a rough guideline.\n");
fprintf( outFile, "For best results, please be sure you know the\n");
fprintf( outFile, "precision of your system timer.\n");
fprintf( outFile, HLINE);
}
/* --- MAIN LOOP --- repeat test cases NTIMES times --- */
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
times[0][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Copy();
#else
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j=0; j<VectorSize; j++)
c[j] = a[j];
#endif
times[0][k] = mysecond() - times[0][k];
times[1][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Scale(scalar);
#else
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j=0; j<VectorSize; j++)
b[j] = scalar*c[j];
#endif
times[1][k] = mysecond() - times[1][k];
times[2][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Add();
#else
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j=0; j<VectorSize; j++)
c[j] = a[j]+b[j];
#endif
times[2][k] = mysecond() - times[2][k];
times[3][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Triad(scalar);
#else
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j=0; j<VectorSize; j++)
a[j] = b[j]+scalar*c[j];
#endif
times[3][k] = mysecond() - times[3][k];
}
/* --- SUMMARY --- */
for (k=1; k<NTIMES; k++) /* note -- skip first iteration */
{
for (j=0; j<4; j++)
{
avgtime[j] = avgtime[j] + times[j][k];
mintime[j] = Mmin(mintime[j], times[j][k]);
maxtime[j] = Mmax(maxtime[j], times[j][k]);
}
}
if (doIO)
fprintf( outFile, "Function Rate (GB/s) Avg time Min time Max time\n");
for (j=0; j<4; j++) {
avgtime[j] /= (double)(NTIMES - 1); /* note -- skip first iteration */
/* make sure no division by zero */
curGBs = (mintime[j] > 0.0 ? 1.0 / mintime[j] : -1.0);
curGBs *= 1e-9 * bytes[j] * VectorSize;
if (doIO)
fprintf( outFile, "%s%11.4f %11.4f %11.4f %11.4f\n", label[j],
curGBs,
avgtime[j],
mintime[j],
maxtime[j]);
switch (j) {
case 0: *copyGBs = curGBs; break;
case 1: *scaleGBs = curGBs; break;
case 2: *addGBs = curGBs; break;
case 3: *triadGBs = curGBs; break;
}
}
if (doIO) fprintf( outFile, HLINE);
/* --- Check Results --- */
checkSTREAMresults( outFile, doIO, failure );
if (doIO) fprintf( outFile, HLINE);
HPCC_free(c);
HPCC_free(b);
HPCC_free(a);
if (doIO) {
fflush( outFile );
fclose( outFile );
}
return 0;
}
void tuned_STREAM_Copy()
{
uint64_t j;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j=0; j<VectorSize; j++)
c[j] = a[j];
}
void tuned_STREAM_Scale(double scalar)
{
uint64_t j;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j=0; j<VectorSize; j++)
b[j] = scalar*c[j];
}
void tuned_STREAM_Add()
{
uint64_t j;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j=0; j<VectorSize; j++)
c[j] = a[j]+b[j];
}
void tuned_STREAM_Triad(double scalar)
{
uint64_t j;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (j=0; j<VectorSize; j++)
{
a[j] = b[j]+scalar*c[j];
}
}
int
main () {
HPCC_Params *params = initialize();
double copyGBs, scaleGBs, addGBs, triadGBs;
int failure;
HPCC_Stream (params, 1, ©GBs, &scaleGBs, &addGBs, &triadGBs, &failure);
return 0;
}
|
IF97_Region1bw.c |
// Copyright Martin Lord 2014-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/** IAPWS-IF97 Region 1 Equations
* VALIDITY 273.15 K <= T <= 623.15 K Psat <= p <= 100 MPa
* Exception: Backwards equations not valid in metastable (superheated liquid) region
*/
#include "IF97_common.h" //PSTAR TSTAR sqr
#include "IF97_Region1.h"
#include <math.h> // pow
//**********************************************************
//********* REGION 1 BACKWARDS EQUATIONS********************
//returns temperature (K) in region 1 for a given pressure and enthalpy
// Checked OK
double if97_r1_t_ph (double p_MPa , double h_kJperKg ){
// see Table 6
const typIF97Coeffs_IJn BW_COEFFS_R1_TPH[] = {
{0, 0, 0.0} //0 i starts at 1, so 0th i is not used
,{0, 0, -0.23872489924521E3} //1
,{0, 1, 0.40421188637945E3}
,{0, 2, 0.11349746881718E3}
,{0, 6, -0.58457616048039E1}
,{0, 22, -0.15285482413140E-3}
,{0, 32, -0.10866707695377E-5}
,{1, 0, -0.13391744872602E2}
,{1, 1, 0.43211039183559E2}
,{1, 2, -0.54010067170506E2}
,{1, 3, 0.30535892203916E2}
,{1, 4, -0.65964749423638E1}
,{1, 10, 0.93965400878363E-2}
,{1, 32, 0.11573647505340E-6}
,{2, 10, -0.25858641282073E-4}
,{2, 32, -0.40644363084799E-8}
,{3, 10, 0.66456186191635E-7}
,{3, 32, 0.80670734103027E-10}
,{4, 32, -0.93477771213947E-12}
,{5, 32, 0.58265442020601E-14}
,{6, 32, -0.15020185953503E-16} //20
};
const int MAX_BW_COEFFS_R1_TPH = 20;
const double PSTAR_R1_TPH = 1.0 ; // MPa
const double TSTAR_R1_TPH = 1.0 ;
const double HSTAR_R1_TPH = 2500.0 ; // kJ / kg
double if97pi = p_MPa / PSTAR_R1_TPH;
double if97eta = h_kJperKg / HSTAR_R1_TPH;
int i;
double dblHSum =0.0;
#pragma omp parallel for reduction(+:dblHSum) //handle loop multithreaded
for (i=1; i <= MAX_BW_COEFFS_R1_TPH; i++) {
dblHSum += BW_COEFFS_R1_TPH[i].ni * pow(if97pi, BW_COEFFS_R1_TPH[i].Ii) * pow( ( if97eta +1), BW_COEFFS_R1_TPH[i].Ji);
}
return TSTAR_R1_TPH * dblHSum;
}
//returns temperature (K) in region 1 for a given pressure and entropy
//
double if97_r1_t_ps (double p_MPa , double s_kJperKgK ){
// see Table 8
const typIF97Coeffs_IJn BW_COEFFS_R1_TPH[] = {
{0, 0, 0.0} //0 i starts at 1, so 0th i is not used
,{0, 0, 174.78268058307} //1
,{0, 1, 34.806930892873}
,{0, 2, 6.5292584978455}
,{0, 3, 0.33039981775489}
,{0, 11, -1.9281382923196E-07}
,{0, 31, -2.4909197244573E-23}
,{1, 0, -0.26107636489332}
,{1, 1, 0.22592965981586}
,{1, 2, -0.06425646339523}
,{1, 3, 0.00788762892705}
,{1, 12, 3.5672110607366E-10}
,{1, 31, 1.7332496994895E-24}
,{2, 0, 0.00056608900655}
,{2, 1, -0.0003263548314}
,{2, 2, 4.4778286690632E-05}
,{2, 9, -5.1322156908507E-10}
,{2, 31, -4.2522657042207E-26}
,{3, 10, 2.6400441360689E-13}
,{3, 32, 7.8124600459723E-29}
,{4, 32, -3.0732199903668E-31} //20
};
const int MAX_BW_COEFFS_R1_TPS = 20;
const double PSTAR_R1_TPS = 1.0 ; // MPa
const double TSTAR_R1_TPS = 1.0; // K
const double SSTAR_R1_TPS = 1.0 ; // kJ / kgK
double if97pi = p_MPa / PSTAR_R1_TPS;
double if97sigma = s_kJperKgK / SSTAR_R1_TPS;
int i;
double dblHSum =0.0;
#pragma omp parallel for reduction(+:dblHSum) //handle loop multithreaded
for (i=1; i <= MAX_BW_COEFFS_R1_TPS; i++) {
dblHSum += BW_COEFFS_R1_TPH[i].ni * pow(if97pi, BW_COEFFS_R1_TPH[i].Ii) * pow( ( if97sigma + 2), BW_COEFFS_R1_TPH[i].Ji);
}
return TSTAR_R1_TPS * dblHSum;
}
|
fvmpor.h | #ifndef FVMPOR_H
#define FVMPOR_H
//#define USE_PRINT
#ifdef USE_PRINT
#define PRINT(fid,v) fid << #v << std::endl; \
for(int kkkk=0; kkkk<v.dim(); kkkk++ )\
fid << v[kkkk] << " ";\
fid << std::endl;
#else
#define PRINT(fid,v) ;
#endif
#include "definitions.h"
#include "shape.h"
#include <cublas.h>
#include <lin/impl/rebind.h>
#include <lin/lin.h>
#include <fvm/fvm.h>
#include <fvm/mesh.h>
//#include <fvm/solver.h>
#include <fvm/solver_compact.h>
#include <fvm/physics_base.h>
#include <util/intvector.h>
#include <util/interpolation.h>
#include <util/dimvector.h>
#include <util/timer.h>
#include <mkl_spblas.h>
#include <mkl_service.h>
#include <omp.h>
#include <vector>
#include <memory>
#include <map>
#include <iostream>
namespace fvmpor {
template <typename T>
struct CoordTraits_{
static bool is_device() {return false;};
};
template <>
struct CoordTraits_<lin::gpu::Coordinator<int> >{
static bool is_device() {return true;};
};
enum SpatialWeightType {weightUpwind, weightAveraging, weightVanLeer};
using lin::all;
template <typename CoordHost, typename CoordDevice>
class VarSatPhysicsImpl{
public:
typedef typename lin::rebind<CoordHost, double>::type CoordHostDouble;
typedef typename lin::rebind<CoordHost, int>::type CoordHostInt;
typedef typename lin::rebind<CoordDevice, double>::type CoordDeviceDouble;
typedef typename lin::rebind<CoordDevice, int>::type CoordDeviceInt;
typedef lin::Vector<double, CoordHostDouble> TVec;
typedef lin::Vector<int, CoordHostInt> TIndexVec;
typedef lin::Vector<double, CoordDeviceDouble> TVecDevice;
typedef lin::Vector<int, CoordDeviceInt> TIndexVecDevice;
typedef util::InterpolationMatrix<CoordDevice> InterpolationMatrix;
typedef util::DimVector<TVecDevice> DimVector;
protected:
typedef mesh::Point Point;
// computation during a timestep
void process_faces_lim( const mesh::Mesh &m );
void process_faces_shape( const mesh::Mesh &m );
void process_volumes_psk( const mesh::Mesh &m );
void process_derivative_coefficients( const mesh::Mesh &m );
void process_fluxes( double t, const mesh::Mesh &m );
void process_spatial_weights(const mesh::Mesh& m);
// physical zones
const PhysicalZone& physical_zone( int ) const;
int physical_zones() const;
// boundary conditions
int boundary_conditions() const { return boundary_conditions_h_.size(); };
const BoundaryCondition& boundary_condition_h( int ) const;
const Constants& constants() const { return constants_; };
////////////////////////////////
// routines for setting up
///////////////////////////////
void set_physical_zones();
void set_boundary_conditions();
void initialise_vectors( const mesh::Mesh &m );
void set_initial_conditions( double &t, const mesh::Mesh& m );
void set_constants();
void initialise_shape_functions(const mesh::Mesh& m);
// physics specific
void saturation( TVecDevice& h, const PhysicalZone &props, TVecDevice &Sw, TVecDevice &dSw, TVecDevice &krw );
// communicator for global communication of doubles on the nodes
mpi::Communicator<double> node_comm_;
// physical definitions
int dimension;
std::vector<PhysicalZone> physical_zones_;
std::map<int,BoundaryCondition> boundary_conditions_h_;
Constants constants_;
// tags whether a node is dirichlet
TIndexVec is_dirichlet_h_vec_; // HOST
TIndexVecDevice dirichlet_nodes_; // DEVICE
TVecDevice h_dirichlet_; // DEVICE
// spatial weighting
int CV_flux_comm_tag;
SpatialWeightType spatial_weighting;
TIndexVecDevice CV_up; // DEVICE
TVecDevice CV_flux; // DEVICE
TIndexVecDevice edge_up; // DEVICE
TIndexVecDevice edge_down; // DEVICE
TVecDevice edge_flux; // DEVICE
// derived quantities
std::vector<TVecDevice> head_scv; // DEVICE
std::vector<TVecDevice> phi_scv; // DEVICE
std::vector<TVecDevice> dphi_scv; // DEVICE
//std::vector<TVecDevice> Se_scv; // DEVICE
std::vector<TVecDevice> Sw_scv; // DEVICE
std::vector<TVecDevice> theta_scv; // DEVICE
std::vector<TVecDevice> dSw_scv; // DEVICE
std::vector<TVecDevice> krw_scv; // DEVICE
std::vector<TIndexVecDevice> index_scv; // DEVICE
std::vector<TVecDevice> weight_scv; // DEVICE
std::map<int, int> zones_map_;
// spatial weighting for CV faces
std::vector<TIndexVecDevice> n_front_; // DEVICE
std::vector<TIndexVecDevice> n_back_; // DEVICE
std::vector<TIndexVecDevice> p_front_; // DEVICE
std::vector<TIndexVecDevice> q_front_; // DEVICE
std::vector<TIndexVecDevice> p_back_; // DEVICE
std::vector<TIndexVecDevice> q_back_; // DEVICE
TVecDevice edge_weight_front_; // DEVICE
TVecDevice edge_weight_back_; // DEVICE
TIndexVecDevice edge_node_front_; // DEVICE
TIndexVecDevice edge_node_back_; // DEVICE
// stores list of nodes on seepage faces
//TIndexVec seepage_nodes;
//int seepage_tag; // unique tag for the seepage BC
// for interpolation from nodes to CV faces
InterpolationMatrix shape_matrix;
InterpolationMatrix shape_gradient_matrixX;
InterpolationMatrix shape_gradient_matrixY;
InterpolationMatrix shape_gradient_matrixZ;
InterpolationMatrix flux_lim_matrix;
InterpolationMatrix cvflux_matrix;
InterpolationMatrix dirichlet_matrix;
TVecDevice h_vec; // head at the nodes // DEVICE
TVecDevice hp_vec_; // head derivative at the nodes // DEVICE
TVecDevice M_vec_; // M at the nodes // DEVICE
TVecDevice Mp_vec_; // M derivative at the nodes // DEVICE
//TVecDevice res_tmp;
DimVector grad_h_faces_; // head gradient at CV faces // DEVICE
TVecDevice h_faces; // head at CV faces // DEVICE
TVecDevice M_flux_faces; // mass flux at CV faces // DEVICE
TVecDevice qdotn_faces; // volumetric fluid flux at CV faces // DEVICE
// storing derived quantities averaged for each control volume
TVecDevice rho_vec, Sw_vec, dSw_vec, theta_vec; // DEVICE
TVecDevice phi_vec, dphi_vec; // DEVICE
// storing derived quantities at cv faces (using c and h values at faces)
TVecDevice rho_faces; // DEVICE
// storing upwinded/flux limitted values at cv faces
TVecDevice rho_faces_lim, krw_faces_lim; // DEVICE
// storing coefficients for derivative terms
TVecDevice ahh_vec; // DEVICE
// storing values at faces
DimVector K_faces_; // DEVICE
DimVector norm_faces_; // DEVICE
DimVector qsat_faces_; // DEVICE HOST
};
template <typename value_type, typename CoordHost, typename CoordDevice>
class VarSatPhysics :
public fvm::PhysicsBase< VarSatPhysics<value_type, CoordHost, CoordDevice>,
value_type>,
public VarSatPhysicsImpl<CoordHost,CoordDevice>
{
typedef fvm::PhysicsBase<VarSatPhysics, value_type> base;
typedef VarSatPhysicsImpl<CoordHost,CoordDevice> impl;
int num_calls;
friend class Preconditioner;
typename impl::TVecDevice res_tmp;
typename impl::TVec res_tmp_host;
public:
typedef typename base::iterator iterator;
typedef typename base::const_iterator const_iterator;
typedef typename base::Callback Callback;
//VarSatPhysics(const mesh::Mesh &m) : num_calls(0), res_tmp(TVec(value_type::variables*m.local_nodes())) {};
VarSatPhysics() : num_calls(0) {};
int calls() const { return num_calls; }
/////////////////////////////////
// GLOBAL
/////////////////////////////////
value_type flux(double t, const mesh::CVFace& cvf, const_iterator sol) const;
value_type boundary_flux(double t, const mesh::CVFace& cvf, const_iterator sol) const;
double compute_mass(const mesh::Mesh& m, const_iterator u);
double mass_flux_per_time(const mesh::Mesh& m);
/////////////////////////////////
// VARIABLE-SPECIFIC
/////////////////////////////////
void initialise( double& t, const mesh::Mesh& m, iterator u,
iterator udash, iterator temp, Callback);
void preprocess_evaluation( double t, const mesh::Mesh& m,
const_iterator u, const_iterator udash);
void preprocess_timestep( double t, const mesh::Mesh& m,
const_iterator sol, const_iterator deriv);
value_type lhs( double t, const mesh::Volume& volume,
const_iterator u, const_iterator udash) const;
void residual_evaluation( double t, const mesh::Mesh& m,
const_iterator sol, const_iterator deriv, iterator res);
value_type dirichlet(double t, const mesh::Node& n) const;
};
// **************************************************************************
// * IMPLEMENTATION *
// **************************************************************************
using mesh::Point;
template <typename TVec>
void density(TVec& h, TVec& rho, const Constants& constants)
{
double beta = constants.beta();
double rho_0 = constants.rho_0();
double g = constants.g();
if( beta ){
rho = h;
rho *= rho_0*rho_0*g*beta;
rho += rho_0;
}else{
rho(all) = rho_0;
}
}
template <typename TVec>
void porosity( TVec& h,
TVec& phi,
TVec& dphi,
const PhysicalZone& props,
const Constants& constants)
{
double g = constants.g();
double rho_0 = constants.rho_0();
double phi_0 = props.phi;
double alpha = props.alpha;
// porosity
if(alpha==0.){
phi(all) = phi_0;
dphi.zero();
}
else{
double factor = (phi_0-1.)*rho_0*g*alpha;
phi(all) = 1.;
phi(all) += factor * h;
}
}
template <typename CoordHost, typename CoordDevice>
void VarSatPhysicsImpl<CoordHost,CoordDevice>::saturation(
TVecDevice& h,
const PhysicalZone &props,
TVecDevice &Sw,
TVecDevice &dSw,
TVecDevice &krw )
{
double alphaVG = props.alphaVG;
double nVG = props.nVG;
double mVG = props.mVG;
double S_r = props.S_r;
double phi = props.phi;
if( CoordTraits_<CoordDeviceInt>::is_device() ){
const double *h_ptr = h.data();
double *dSw_ptr = dSw.data();
double *Sw_ptr = Sw.data();
double *krw_ptr = krw.data();
lin::gpu::saturation( h_ptr, Sw_ptr, dSw_ptr, krw_ptr,
h.dim(), alphaVG, nVG, mVG, S_r, phi);
}
else{
// if a = (alpha*|h|)^n, and b = 1+a
// set dSw = a
dSw(all) = -alphaVG*h;
dSw.pow(nVG);
// Sw = 1/b
Sw(all) = dSw+1.;
krw(all) = -1.;
krw /= Sw;
// dSw /= b
dSw /= Sw;
// Sw = 1/(b^m)
// this is the final value for Sw
Sw.pow(-mVG);
// find dSw
dSw *= Sw;
dSw /= h;
dSw *= -(1-S_r)*(nVG-1);
// find krw
krw += 1.;
krw.pow(mVG);
krw -= 1.;
krw.pow(2);
krw(all) *= sqrt(Sw);
Sw *= (1-S_r);
Sw += S_r;
// now override values for saturated h
int n=h.dim();
for(int i=0; i<n; i++){
if(h.at(i)>=0.){
dSw.at(i) = 0.;
Sw.at(i) = 1.;
krw.at(i) = 1.;
}
}
}
}
template <typename CoordHost, typename CoordDevice>
void VarSatPhysicsImpl<CoordHost,CoordDevice>::initialise_vectors( const mesh::Mesh &m ){
std::ofstream fid;
dimension = m.dim();
std::cout << "mesh has " << m.nodes() << " nodes " << m.elements() << " elements and " << m.cvfaces() << " CV faces" << std::endl;
std::cout << "with faces internal " << m.interior_cvfaces() << std::endl;
node_comm_.set_pattern( "NP_double", m.node_pattern() );
//sort out omp thread affinity
// if we are expected to use a GPU ensure that the CUBLAS
// library has been initialised
// This also ensures that the device is setup correctly
if(CoordTraits_<CoordDeviceInt>::is_device()){
fid.open("initialiseGPU.txt");
std::cout << "intialising cublas" << std::endl;
int num_devices = lin::gpu::num_devices();
int num_processes = m.mpicomm()->size();
int this_process = m.mpicomm()->rank();
assert(num_processes<=num_devices);
lin::gpu::set_device(this_process);
std::string device_name = lin::gpu::get_device_name();
*(m.mpicomm()) << "===============================" << std::endl
<< "using GPU device " << this_process << " (" << device_name << ")" << std::endl
<< "===============================" << std::endl;
assert( cublasInit() == CUBLAS_STATUS_SUCCESS );
}
else
fid.open("initialiseCPU.txt");
// set physical properties
set_constants();
set_physical_zones();
set_boundary_conditions();
// initialise space for storing p-s-k values
int N = m.nodes();
Sw_vec = TVecDevice(N);
dSw_vec = TVecDevice(N);
rho_vec = TVecDevice(N);
theta_vec = TVecDevice(N);
phi_vec = TVecDevice(N);
dphi_vec = TVecDevice(N);
rho_faces_lim = TVecDevice(m.interior_cvfaces());
krw_faces_lim = TVecDevice(m.interior_cvfaces());
rho_faces = TVecDevice(m.interior_cvfaces());
// spatial weightings
CV_up = TIndexVec(m.local_nodes());
CV_flux = TVec(m.nodes());
CV_flux_comm_tag = node_comm_.vec_add(CV_flux.data());
edge_up = TIndexVecDevice(m.edges());
edge_down = TIndexVecDevice(m.edges());
edge_flux = TVecDevice(m.edges());
M_flux_faces = TVecDevice(m.cvfaces());
qdotn_faces = TVecDevice(m.cvfaces());
// initialise space for derivative coefficients
int NL = m.local_nodes();
ahh_vec = TVecDevice( NL );
// tag dirichlet nodes
is_dirichlet_h_vec_ = TIndexVec(m.local_nodes());
int num_dirichlet = 0;
for( int i=0; i<m.local_nodes(); i++ ){
const mesh::Node& n = m.node(i);
// look for dirichlet tags attached to the node
for( int j=0; j<n.boundaries(); j++ ){
int tag = n.boundary(j);
if( boundary_condition_h(tag).is_dirichlet() ){
is_dirichlet_h_vec_[i] = tag;
num_dirichlet++;
}
}
}
PRINT(fid, is_dirichlet_h_vec_);
// make a list of the dirichlet nodes
TIndexVec dirichlet_nodes(num_dirichlet);
int count=0;
for(int i=0; i<m.local_nodes(); i++)
if(is_dirichlet_h_vec_[i])
dirichlet_nodes[count++] = i;
// copy to device
dirichlet_nodes_ = dirichlet_nodes;
// store the prescribed head values
// currently this only works for time-invariant dirichlet values
TVec h_dirichlet(num_dirichlet);
for(int n=0; n<num_dirichlet; n++){
double t=0.;
int i = dirichlet_nodes[n];
const BoundaryCondition& bc = boundary_condition_h(is_dirichlet_h_vec_[i]);
// fixed dirichlet
if( bc.type()==1 ){
h_dirichlet[n] = bc.value(t);
}
else{
double el = dimension == 2 ? m.node(i).point().y : m.node(i).point().z;
if(bc.type()==4)
h_dirichlet[n] = bc.hydrostatic(t, el);
else{
h_dirichlet[n] = bc.hydrostatic_shore(t, el);
}
}
}
// copy to device
h_dirichlet_ = h_dirichlet;
// initialise vectors used in calculating derived quantities such as saturation
// allocate room for each of the arrays
std::set<int> zones;
for(int i=0; i<m.elements(); i++)
zones.insert(m.element(i).physical_tag());
int num_zones = zones.size();
int indx=0;
for( std::set<int>::iterator it=zones.begin(); it!=zones.end(); it++)
zones_map_[*it] = indx++;
// temp var
std::vector< std::vector<double> > weight_scv_tmp;
std::vector< std::vector<int> > index_scv_tmp;
weight_scv_tmp.resize( num_zones );
index_scv_tmp.resize( num_zones );
std::vector<std::map<int,int> > nodes_idx;
nodes_idx.resize(num_zones);
// compile index and weight information mapping node information to scv information
for(int i=0; i<m.nodes(); i++){
const mesh::Volume& cv = m.volume(i);
double cv_vol = cv.vol();
std::vector<double> weights(num_zones);
std::vector<int> counts(num_zones);
for(int j=0; j<cv.scvs(); j++){
int tag = zones_map_[cv.scv(j).element().physical_tag()];
assert(tag<num_zones);
weights[tag] += cv.scv(j).vol() / cv_vol;
counts[tag]++;
}
for(int j=0; j<num_zones; j++){
if(counts[j]){
weight_scv_tmp[j].push_back(weights[j]);
index_scv_tmp[j].push_back(i);
nodes_idx[j][i] = index_scv_tmp[j].size()-1;
}
}
}
weight_scv.resize( num_zones );
index_scv.resize( num_zones );
for(int i=0; i<num_zones; i++){
TVec w_tmp(weight_scv_tmp[i].begin(), weight_scv_tmp[i].end());
TIndexVec i_tmp(index_scv_tmp[i].begin(), index_scv_tmp[i].end());
weight_scv[i] = w_tmp;
index_scv[i] = i_tmp;
}
// OUTPUT
for(int i=0; i<num_zones; i++){
PRINT(fid, weight_scv[i]);
PRINT(fid, index_scv[i]);
}
// allocate room for head values mapped onto SCVs
head_scv.resize( num_zones );
phi_scv.resize( num_zones );
dphi_scv.resize( num_zones );
//Se_scv.resize( num_zones );
Sw_scv.resize( num_zones );
theta_scv.resize( num_zones );
dSw_scv.resize( num_zones );
krw_scv.resize( num_zones );
for(int i=0; i<num_zones; i++){
head_scv[i] = TVecDevice( index_scv[i].size() );
phi_scv[i] = TVecDevice( index_scv[i].size() );
dphi_scv[i] = TVecDevice( index_scv[i].size() );
Sw_scv[i] = TVecDevice( index_scv[i].size() );
theta_scv[i] = TVecDevice( index_scv[i].size() );
dSw_scv[i] = TVecDevice( index_scv[i].size() );
krw_scv[i] = TVecDevice( index_scv[i].size() );
}
// this will hold global (face, edge) pairs of each mapped node value in each zone
std::vector<std::multimap<int, std::pair<int, int> > > faceEdge_map_front;
std::vector<std::multimap<int, std::pair<int, int> > > faceEdge_map_back;
faceEdge_map_front.resize(num_zones);
faceEdge_map_back.resize(num_zones);
for( int i=0; i<m.edges(); i++ ){
const std::vector<int>& edge_cvfaces = m.edge_cvface(i);
int fid = m.edge(i).front().id();
int bid = m.edge(i).back().id();
for(int j=0; j<edge_cvfaces.size(); j++){
int f = edge_cvfaces[j];
int z = zones_map_[m.cvface(f).element().physical_tag()];
int n = nodes_idx[z][fid];
faceEdge_map_front[z].insert(
std::pair<int, std::pair<int, int> >( n, std::pair<int, int>(f, i))
);
n = nodes_idx[z][bid];
faceEdge_map_back[z].insert(
std::pair<int, std::pair<int, int> >( n, std::pair<int, int>(f, i))
);
}
}
// should also reserve memory for the vectors
n_front_.resize(num_zones);
p_front_.resize(num_zones);
q_front_.resize(num_zones);
n_back_.resize(num_zones);
p_back_.resize(num_zones);
q_back_.resize(num_zones);
typedef std::multimap<int, std::pair<int, int> >::iterator idxTypeIt;
for(int z=0; z<num_zones; z++){
std::vector<int> n_front;
std::vector<int> p_front;
std::vector<int> q_front;
std::vector<int> n_back;
std::vector<int> p_back;
std::vector<int> q_back;
int len = head_scv[z].dim();
for(int i=0; i<len; i++){
std::pair<idxTypeIt, idxTypeIt> rng = faceEdge_map_front[z].equal_range(i);
for( idxTypeIt it=rng.first; it!=rng.second; ++it ){
n_front.push_back(i); // local node id
q_front.push_back(it->second.first); // global face index
p_front.push_back(it->second.second); // global edge index
}
rng = faceEdge_map_back[z].equal_range(i);
for( idxTypeIt it=rng.first; it!=rng.second; ++it ){
n_back.push_back(i); // local node id
q_back.push_back(it->second.first); // global face index
p_back.push_back(it->second.second); // global edge index
}
}
n_front_[z] = TIndexVec(n_front.begin(), n_front.end());
p_front_[z] = TIndexVec(p_front.begin(), p_front.end());
q_front_[z] = TIndexVec(q_front.begin(), q_front.end());
n_back_[z] = TIndexVec(n_back.begin(), n_back.end());
p_back_[z] = TIndexVec(p_back.begin(), p_back.end());
q_back_[z] = TIndexVec(q_back.begin(), q_back.end());
}
// OUTPUT
for(int i=0; i<num_zones; i++){
PRINT(fid,n_front_[i]);
PRINT(fid,n_back_[i]);
PRINT(fid,p_front_[i]);
PRINT(fid,p_back_[i]);
PRINT(fid,q_front_[i]);
PRINT(fid,q_back_[i]);
}
edge_weight_front_ = TVecDevice(m.edges(), 0.5);
edge_weight_back_ = TVecDevice(m.edges(), 0.5);
TIndexVec edge_node_front(m.edges());
TIndexVec edge_node_back(m.edges());
for( int i=0; i<m.edges(); i++){
edge_node_front[i] = m.edge(i).front().id();
edge_node_back[i] = m.edge(i).back().id();
}
// copy onto device
edge_node_front_ = edge_node_front;
edge_node_back_ = edge_node_back;
// OUTPUT
PRINT(fid,edge_node_front_);
PRINT(fid,edge_node_back_);
// initialise the shape functions
initialise_shape_functions(m);
// initialise flux vecs
qsat_faces_.set(m.interior_cvfaces(), m.dim());
norm_faces_.set(m.interior_cvfaces(), m.dim());
TVec X(m.interior_cvfaces());
TVec Y(m.interior_cvfaces());
TVec Z(m.interior_cvfaces());
for( int i=0; i<m.interior_cvfaces(); i++ ){
Point nrm = m.cvface(i).normal();
X[i] = nrm.x;
Y[i] = nrm.y;
if( m.dim()==3 )
Z[i] = nrm.z;
}
norm_faces_.x() = X;
norm_faces_.y() = Y;
if(m.dim()==3)
norm_faces_.z() = Z;
K_faces_.set(m.interior_cvfaces(), m.dim());
for( int i=0; i<m.interior_cvfaces(); i++ ){
int tag = m.cvface(i).element().physical_tag();
X[i] = -physical_zone(tag).K_xx;
Y[i] = -physical_zone(tag).K_yy;
if( m.dim()==3 )
Z[i] = -physical_zone(tag).K_zz;
}
K_faces_.x() = X;
K_faces_.y() = Y;
if(m.dim()==3)
K_faces_.z() = Z;
}
template <typename CoordHost, typename CoordDevice>
void VarSatPhysicsImpl<CoordHost,CoordDevice>::process_faces_shape( const mesh::Mesh &m )
{
//density(h_faces, rho_faces, constants());
rho_faces(all) = constants().rho_0();
}
template <typename CoordHost, typename CoordDevice>
void VarSatPhysicsImpl<CoordHost,CoordDevice>::process_faces_lim( const mesh::Mesh &m )
{
if(CoordTraits_<CoordDeviceInt>::is_device()){
lin::gpu::collect_edges(
rho_vec.data(), rho_faces_lim.data(), m.edges(),
edge_weight_front_.data(), edge_weight_back_.data(),
edge_node_front_.data(), edge_node_back_.data(),
flux_lim_matrix.row_ptrs().data(), flux_lim_matrix.col_indexes().data() );
}
else{
const int *ia = flux_lim_matrix.row_ptrs().data();
const int *ja = flux_lim_matrix.col_indexes().data();
double *rho_face_ptr = rho_faces_lim.data();
double rho_edge;
int e;
#pragma omp parallel for schedule(static) shared(rho_face_ptr, ja, ia) private(e, rho_edge)
for( e=0; e<m.edges(); e++ ){
rho_edge =
rho_vec.at(edge_node_back_[e])*edge_weight_back_.at(e)
+ rho_vec.at(edge_node_front_[e])*edge_weight_front_.at(e);
for( int j=ia[e]; j<ia[e+1]; j++)
rho_face_ptr[ja[j]] = rho_edge;
}
}
}
template <typename CoordHost, typename CoordDevice>
void VarSatPhysicsImpl<CoordHost,CoordDevice>::process_fluxes( double t, const mesh::Mesh &m )
{
int ifaces=m.interior_cvfaces();
// initialise the flux to zero
qdotn_faces.zero();
// compute the vector quantity q at each internal CV face
qsat_faces_.x().at(all) = grad_h_faces_.x();
qsat_faces_.x() *= K_faces_.x();
qsat_faces_.y().at(all) = grad_h_faces_.y();
if( m.dim()==2 ){
qsat_faces_.y() += 1.;
}else{
qsat_faces_.z().at(all) = grad_h_faces_.z();
qsat_faces_.z() += 1.;
qsat_faces_.z() *= K_faces_.z();
}
qsat_faces_.y() *= K_faces_.y();
qdotn_faces.at(0,ifaces-1) = mul(norm_faces_.x(), qsat_faces_.x());
qdotn_faces.at(0,ifaces-1) += mul(norm_faces_.y(), qsat_faces_.y());
if( m.dim()==3 ){
qdotn_faces.at(0,ifaces-1) += mul(norm_faces_.z(), qsat_faces_.z());
}
qdotn_faces.at(0,ifaces-1) *= krw_faces_lim;
M_flux_faces.at(0,ifaces-1) = mul(rho_faces_lim, qdotn_faces);
// loop over boundary faces and find fluid flux where
// explicitly given by BCs
// temp host vector for computing the boundary fluxes
int faces_bnd = m.cvfaces()-m.interior_cvfaces();
TVec qdotn_faces_bnd(faces_bnd);
for( int i=0; i<faces_bnd; i++)
{
const mesh::CVFace& cvf = m.cvface(i+m.interior_cvfaces());
int boundary_tag = cvf.boundary();
const BoundaryCondition& BCh = boundary_condition_h( boundary_tag );
switch( BCh.type() ){
// prescribed flux
case 3:
qdotn_faces_bnd.at(i) = BCh.value(t) * cvf.area();
break;
// prescribed directional flux
case 6:
qdotn_faces_bnd.at(i) = BCh.flux( t, cvf.normal() ) * cvf.area();
break;
// seepage
case 7:
qdotn_faces_bnd.at(i) = BCh.value(t) * cvf.area();
break;
// seepage/hydrostatic shoreline
case 8:
qdotn_faces_bnd.at(i) = 0. * cvf.area();
break;
default:
break;
}
}
qdotn_faces.at(ifaces,m.cvfaces()-1) = qdotn_faces_bnd;
// find mass flux at boundary faces : scale by density
M_flux_faces.at(m.interior_cvfaces(), lin::end) =
constants().rho_0() *
qdotn_faces.at(m.interior_cvfaces(), lin::end);
}
template <typename CoordHost, typename CoordDevice>
void VarSatPhysicsImpl<CoordHost,CoordDevice>::process_spatial_weights(const mesh::Mesh& m){
// determine the flux over each edge
flux_lim_matrix.matvec( qdotn_faces.at(0,m.interior_cvfaces()-1), edge_flux );
switch( spatial_weighting ){
case weightAveraging :
assert(false);
break;
////////////////////////////////////////////////////////
// the upwinding case is simple
////////////////////////////////////////////////////////
case weightUpwind :
if(CoordTraits_<CoordDeviceInt>::is_device()){
lin::gpu::set_weights_upwind(
edge_flux.data(),
edge_weight_front_.data(),
edge_weight_back_.data(),
m.edges()
);
}
else{
for(int i=0; i<m.edges(); i++){
if( edge_flux.at(i)<0. ){
edge_weight_front_.at(i) = 1.;
edge_weight_back_.at(i) = 0.;
}
else{
edge_weight_front_.at(i) = 0.;
edge_weight_back_.at(i) = 1.;
}
}
}
break;
////////////////////////////////////////////////////////
// the flux limitting case takes a bit more work
////////////////////////////////////////////////////////
case weightVanLeer :
for(int i=0; i<m.edges(); i++){
if( edge_flux.at(i)>0. ){
edge_up[i] = m.edge(i).back().id();
edge_down[i] = m.edge(i).front().id();
}
else{
edge_up[i] = m.edge(i).front().id();
edge_down[i] = m.edge(i).back().id();
}
}
// find the up node for each CV
for(int i=0; i<m.local_nodes(); i++){
CV_flux.at(i) = 0.;
CV_up[i] = -1;
}
// set the flux into each boundary node to be that from over the boundary
for(int i=m.interior_cvfaces(); i<m.cvfaces(); i++){
int n=m.cvface(i).back().id();
CV_flux.at(n) -= qdotn_faces.at(i);
}
// now find max flux into each CV
for(int i=0; i<m.edges(); i++){
if( edge_node_front_[i]<m.local_nodes() || edge_node_back_[i]<m.local_nodes() ){
int CV = edge_down[i];
if( CV<m.local_nodes() ){
double fl = fabs(edge_flux.at(i));
if( fl>CV_flux[CV] ){
CV_flux[CV] = fl;
CV_up[CV] = edge_up[i];
}
}
}
}
// verify that each CV was assigned an upwind point
for(int i=0; i<m.local_nodes(); i++){
if(CV_up[i]==-1){
CV_up[i] = i;
}
}
*node_comm_.mpicomm() << "VarSatPhysicsImpl::process_spatial_weights : communicating 2up fluxes values accross subdomain boundaries" << std::endl;
node_comm_.send(CV_flux_comm_tag);
node_comm_.recv(CV_flux_comm_tag);
// find r and sigma for each edge
for(int i=0; i<m.edges(); i++){
if( edge_node_front_[i]<m.local_nodes() || edge_node_back_[i]<m.local_nodes() ){
double qup = fabs(edge_flux.at(i));
double q2up = CV_flux.at(edge_up[i]);
double r = q2up / qup;
double sigma;
if( qup==0. )
sigma = 1.;
else if(r>1.e10)
sigma = 2.;
else
sigma = (r+fabs(r)) / (1.+fabs(r));
if( edge_flux.at(i)>0. ){
edge_weight_back_.at(i) = sigma/2.;
edge_weight_front_.at(i) = 1.-sigma/2.;
}
else{
edge_weight_back_.at(i) = 1.-sigma/2.;
edge_weight_front_.at(i) = sigma/2.;
}
}
}
}
}
template <typename CoordHost, typename CoordDevice>
void VarSatPhysicsImpl<CoordHost,CoordDevice>::process_volumes_psk( const mesh::Mesh &m )
{
double beta = constants().beta();
double rho_0 = constants().rho_0();
double g = constants().g();
// zero out vectors of CV-averaged derived quantities
phi_vec.zero();
dphi_vec.zero();
Sw_vec.zero();
dSw_vec.zero();
theta_vec.zero();
// for each zone calucluate the scv-weighted derived quantities and add them
// to the appropriate CV-averaged vectors
double T=0.;
for( std::map<int, int>::iterator it=zones_map_.begin();
it!=zones_map_.end();
it++)
{
int zone = (*it).second;
int indx = (*it).first;
int n = index_scv.size();
const PhysicalZone& props = physical_zone(indx);
// get head data for this zone type
head_scv[zone].at(all) = h_vec.at(index_scv[zone]);
// find porosity and scale by weights
porosity(head_scv[zone], phi_scv[zone], dphi_scv[zone], props, constants());
// determine the saturation, rel. permeability and dSw/dh
saturation( head_scv[zone], props, Sw_scv[zone], dSw_scv[zone], krw_scv[zone] );
// moisture content
theta_scv[zone].at(all) = mul(Sw_scv[zone], phi_scv[zone]);
// copy into global vector
phi_vec.at(index_scv[zone]) += mul(phi_scv[zone], weight_scv[zone]);
dphi_vec.at(index_scv[zone]) += mul(dphi_scv[zone], weight_scv[zone]);
Sw_vec.at(index_scv[zone]) += mul(Sw_scv[zone], weight_scv[zone]);
dSw_vec.at(index_scv[zone]) += mul(dSw_scv[zone], weight_scv[zone]);
theta_vec.at(index_scv[zone]) += mul(theta_scv[zone], weight_scv[zone]);
krw_faces_lim.at(q_front_[zone]) = mul(
krw_scv[zone].at(n_front_[zone]),
edge_weight_front_.at(p_front_[zone]) );
krw_faces_lim.at(q_back_[zone]) += mul(
krw_scv[zone].at(n_back_[zone]),
edge_weight_back_.at(p_back_[zone]) );
}
// find the CV-averaged density
density(h_vec, rho_vec, constants());
}
template <typename CoordHost, typename CoordDevice>
void VarSatPhysicsImpl<CoordHost,CoordDevice>::process_derivative_coefficients( const mesh::Mesh &m )
{
double rho_0 = constants().rho_0();
double g = constants().g();
double beta = constants().beta();
double factor = rho_0*rho_0*g*beta;
/*
for( int i=0; i<ahh_vec.dim(); i++ )
ahh_vec.at(i) = rho_vec.at(i)*phi_vec.at(i)*dSw_vec.at(i) + rho_vec.at(i)*Sw_vec.at(i)*dphi_vec.at(i) + factor*phi_vec.at(i)*Sw_vec.at(i);
*/
ahh_vec(all) = mul(phi_vec, dSw_vec);
ahh_vec(all) *= rho_0;
}
template <typename CoordHost, typename CoordDevice>
void VarSatPhysicsImpl<CoordHost,CoordDevice>::initialise_shape_functions(const mesh::Mesh& m)
{
// matrices with weights for computing shape functions
TIndexVec ia, ja;
TVec shape_val, shape_dx, shape_dy, shape_dz;
// Allocate row begin array
int ia_length = m.interior_cvfaces() + 1;
ia = TIndexVec(ia_length);
// Fill row begin array
ia[0] = 0;
for (int i = 0; i < m.interior_cvfaces(); ++i) {
ia[i+1] = ia[i] + m.cvface(i).element().nodes();
}
// Allocate matrix arrays
int ja_length = ia[ia_length-1];
ja = TIndexVec(ja_length);
shape_val = TVec(ja_length);
shape_dx = TVec(ja_length);
shape_dy = TVec(ja_length);
shape_dz = TVec(ja_length);
// Allocate node value arrays
h_vec = TVec(m.nodes());
M_vec_ = TVec(m.nodes());
hp_vec_ = TVec(m.nodes());
Mp_vec_ = TVec(m.nodes());
// Allocate CVFace centroid arrays
h_faces = TVec(m.interior_cvfaces());
grad_h_faces_.set(m.interior_cvfaces(), m.dim());
// Fill other arrays;
for (int i = 0; i < m.elements(); ++i) {
const mesh::Element& e = m.element(i);
// Sort the node ids, to get the index vector
std::vector< std::pair<int, int> > index_vector(e.nodes());
for (int k = 0; k < e.nodes(); ++k) {
index_vector[k] = std::make_pair(e.node(k).id(), k);
}
std::sort(index_vector.begin(), index_vector.end());
shape::Shape my_shape(e);
for (int j = 0; j < e.edges(); ++j) {
int cvf_id = e.cvface(j).id();
// Record ja indices
const mesh::CVFace& cvf = e.cvface(j);
for (int k = 0, p = ia[cvf_id]; p < ia[cvf_id+1]; ++k, ++p) {
ja[p] = index_vector[k].first;
}
// Get shape functions and gradients
std::vector<double> shape_functions = my_shape.shape_functions(j);
std::vector<mesh::Point> shape_gradients = my_shape.shape_gradients(j);
// Now load them into the matrices
for (int k = 0, p = ia[cvf_id]; p < ia[cvf_id+1]; ++k, ++p) {
shape_val[p] = shape_functions[index_vector[k].second];
shape_dx[p] = shape_gradients[index_vector[k].second].x;
shape_dy[p] = shape_gradients[index_vector[k].second].y;
shape_dz[p] = shape_gradients[index_vector[k].second].z;
}
}
}
shape_matrix = InterpolationMatrix(ia, ja, shape_val);
shape_gradient_matrixX = InterpolationMatrix(ia, ja, shape_dx);
shape_gradient_matrixY = InterpolationMatrix(ia, ja, shape_dy);
if (dimension == 3)
shape_gradient_matrixZ = InterpolationMatrix(ia, ja, shape_dz);
//////////////////////////////////////////////////////////
// MATRIX FOR FLUX LIMITTING
// num_edges X num_cvfaces
// sums the fluxes at each face associated with an edge
// which gives the total flux between the control volumes
// that share the edge
//////////////////////////////////////////////////////////
TIndexVec ia_fl, ja_fl;
TVec weights_fl;
// allocate space for row begin indices
ia_length = m.edges()+1;
ia_fl = TIndexVec(ia_length);
ia_fl[0] = 0;
for (int i = 0; i < m.edges(); ++i) {
ia_fl[i+1] = ia_fl[i] + m.edge_cvface(i).size();
}
// allocate space for column indices
ja_length = ia_fl[ia_length-1];
ja_fl = TIndexVec(ja_length);
// allocate space for weights
//weights_fl.resize(ja_length);
weights_fl = TVec(ja_length, 0.);
for(int i=0; i<m.edges(); i++){
const std::vector<int>& faces = m.edge_cvface(i);
// determine the total surface area of the faces attached to edge i
double total_area = 0.;
for(int j=0; j<faces.size(); j++)
total_area += m.cvface(faces[j]).area();
// now determine the scaled weights
int pos = ia_fl[i];
for(int j=0; j<faces.size(); j++){
int face = faces[j];
//weights_fl[pos] = m.cvface(face).area()/total_area;
weights_fl.at(pos) = 1./total_area;
ja_fl[pos] = face;
pos++;
}
}
flux_lim_matrix = InterpolationMatrix(ia_fl, ja_fl, weights_fl);
//////////////////////////////////////////////////////////
// MATRIX FOR CALCULATING FLUX OVER A CV SURFACE
// num_nodes X num_cvfaces
// sums the flux over each CV face that defines the surface
// of the control volume around each node
//////////////////////////////////////////////////////////
TIndexVec ia_cl, ja_cl;
TVec weights_cl;
int N=m.local_nodes();
ia_length = N+1;
ia_cl = TIndexVec(ia_length);
ia_cl[0] = 0;
TIndexVec face_counts(N,0);
std::vector<int> col_indexes;
std::vector<double> weights_tmp;
for (int i = 0; i < N; ++i) {
const mesh::Volume& v = m.volume(i);
double w = 1./v.vol();
std::vector<int> node_faces;
// make a list of the cv faces that form the
// surface of the control volume around node i
for(int j=0; j<v.scvs(); j++){
const mesh::SCV& s = v.scv(j);
for(int k=0; k<s.cvfaces(); k++)
node_faces.push_back(s.cvface(k).id());
}
// sort the faces in ascending order
std::sort(node_faces.begin(),node_faces.end());
// add them to the column index
for(int j=0; j<node_faces.size(); j++)
col_indexes.push_back(node_faces[j]);
// update the row pointer
ia_cl[i+1] = ia_cl[i]+node_faces.size();
// choose the weight for each face
for(int j=0; j<node_faces.size(); j++){
// note that the order of evaluation is very important here
// because if a cv face lies on the boundary it
// has no front node
if(i==m.cvface(node_faces[j]).back().id())
weights_tmp.push_back(-w);
else
weights_tmp.push_back(w);
}
}
// assign the column index and weights
ja_cl.assign(col_indexes.begin(), col_indexes.end());
weights_cl.assign(weights_tmp.begin(), weights_tmp.end());
cvflux_matrix = InterpolationMatrix(ia_cl, ja_cl, weights_cl);
//cvflux_matrix.write_to_file(std::string("../../../../cvflux.m"), util::file_format_matlab);
}
// get a copy of a set of physical zone properties
template <typename CoordHost, typename CoordDevice>
const PhysicalZone& VarSatPhysicsImpl<CoordHost,CoordDevice>::physical_zone( int zone ) const
{
if(!(zone>=0 && zone<physical_zones_.size()))
assert(zone>=0 && zone<physical_zones_.size());
return physical_zones_[zone];
}
// get the number of physical zones
template <typename CoordHost, typename CoordDevice>
int VarSatPhysicsImpl<CoordHost,CoordDevice>::physical_zones( void ) const
{
return physical_zones_.size();
}
template <typename CoordHost, typename CoordDevice>
const BoundaryCondition& VarSatPhysicsImpl<CoordHost,CoordDevice>::boundary_condition_h( int tag ) const{
std::map<int,BoundaryCondition>::const_iterator it = boundary_conditions_h_.find(tag);
assert( it!=boundary_conditions_h_.end());
return it->second;
}
} // end namespace fvmpor
#endif
|
LMSolver.h | #pragma once
#include <eigen\Core>
#include <eigen\Dense>
#include <eigen\Svd>
#include <eigen\Sparse>
/**
* Levenberg-Marquardt Method for dense fixed-size equations
* min_x { f(x)^2 }, with f_(m,1) and x_(n,1)
* */
template<int M, int N>
class CSmallLMSolver
{
public:
typedef double real;
typedef Eigen::Matrix<real,M,1> VecM;
typedef Eigen::Matrix<real,N,1> VecN;
typedef Eigen::Matrix<real,M,N> MatMN;
typedef Eigen::Matrix<real,N,M> MatNM;
typedef Eigen::Matrix<real,N,N> MatNN;
#define CSmallLMSolver_Max(a,b) (a)>(b) ? (a) : (b);
public:
real Optimize(VecN& xStart, int nMaxIter, bool showInfo = false)
{
const static real eps_1 = real(1e-12);
const static real eps_2 = real(1e-12);
const static real tau = real(1e-3);
MatMN Jac;
MatNM JacT;
MatNN JacTJac;
VecM f; //f(x)
VecN g; //g=-J'*f
VecN h; //(J'J + mu * I) h = g
VecN xnew, x;
VecM fnew; //f(xnew)
Eigen::LDLT<MatNN> solver;
//initial settings
x = xStart;
CalcJacobiFunc(x, Jac); //J
JacT = Jac.transpose();
CalcEnergyFunc(x, f); //f
g = JacT * (-f); //g
if(g.norm() <= eps_1)
return true;
JacTJac = JacT*Jac;
solver.compute(JacTJac);
h = solver.solve(g); //J'Jh = g
//find the diag of J'J
real v=real(2), mu=real(0);
for(int i=0; i<JacTJac.rows(); i++)
mu = CSmallLMSolver_Max(mu, JacTJac(i,i));
mu *= tau;
for(int iter=0; iter < nMaxIter; iter++)
{
//+mu*I
for(int i=0; i<JacTJac.rows(); i++)
JacTJac(i,i) += mu;
//solve
solver.compute(JacTJac);
h = solver.solve(g);
//-mu*I
for(int i=0; i<JacTJac.rows(); i++)
JacTJac(i,i) -= mu;
if(h.norm() <= eps_2 * (x.norm() + eps_2))
break;
xnew = x + h;
CalcEnergyFunc(xnew, fnew); //fnew
//dL = L(0) - L(h)
real dL = h.dot(mu*h+g);
real dF = f.dot(f) - fnew.dot(fnew);
real rho = dF/dL;
if(rho > 0)
{
x = xnew; //x
f = fnew; //f
CalcJacobiFunc(x, Jac); //J
JacT = Jac.transpose();
g = JacT * (-f); //g
if(g.norm() <= eps_1)
break;
JacTJac = JacT * Jac;
mu *= CSmallLMSolver_Max(real(1./3.), real(1-pow(2*rho-1,3)));
v = 2;
}
else
{
mu *= v;
v *= 2;
}
if (showInfo)
printf("iter: %d, energy: %f, dif: %f\n", iter, sqrt(f.dot(f)), h.norm() / x.norm());
}//end for iter
xStart = x;
return f.dot(f);
}
protected:
virtual void CalcEnergyFunc(const VecN& x, VecM& fx)=0;
//default: calc jacobi matrix numerically with forward diff
virtual void CalcJacobiFunc(VecN& x, MatMN& jac)
{
const static real delta = real(1e-8);
VecM fx, fxp;
CalcEnergyFunc(x, fx);
for(int j=0; j<N; j++)
{
real d=real(1e-4)*x[j]; // force evaluation
d=fabs(d);
if(d<delta) d=delta;
x[j] += d;
CalcEnergyFunc(x, fxp);
x[j] -= d;
d = real(1.0)/d;
for(int i=0; i<M; i++)
{
jac(i,j) = (fxp[i]-fx[i])*d;
}
}//end for j
}
};
template<int M, int N>
class CSmallNewtonSolver : public CSmallLMSolver<M,N>
{
public:
real Optimize(VecN& xStart, int nMaxIter, bool showInfo = false)
{
MatMN jac(M, N);
MatMN JacTJac(N, N);
VecM fx(M), fx1(M), h(N), g(N);
Eigen::LDLT<MatMN> solver;
//Gauss-Newton Optimization
for (int iter = 0; iter<nMaxIter; iter++)
{
CalcJacobiFunc(xStart, jac); //J
JacTJac = jac.transpose() * jac;
CalcEnergyFunc(xStart, fx); //f
//solve: J'J h = - J' f(x)
g = jac.transpose() * (-fx);
solver.compute(JacTJac);
h = solver.solve(g);
real normv = xStart.norm();
for (real alpha = 1; alpha > 1e-15; alpha *= 0.5)
{
VecN x = xStart + h;
CalcEnergyFunc(x, fx1); //f
if (fx1.dot(fx1) > fx.dot(fx))
h = h * 0.5;
else
{
xStart = x;
break;
}
}
real normh = h.norm();
if (showInfo)
printf("Gauss-Newton: %d -- %f, energy: %f\n", iter, normh / normv, sqrt(fx.dot(fx)));
if (normh < (normv + real(1e-6)) * real(1e-6))
break;
}
return fx.dot(fx);
}
};
/**
* Levenberg-Marquardt Method for dense fix-variable equations
* min_x { f(x)^2 }, with f_(m,1) and x_(n,1)
* */
template<int N>
class CFixVarLMSolver
{
public:
typedef double real;
typedef Eigen::Matrix<real,-1,1> VecM;
typedef Eigen::Matrix<real,N,1> VecN;
typedef Eigen::Matrix<real,-1,N> MatMN;
typedef Eigen::Matrix<real,N,-1> MatNM;
typedef Eigen::Matrix<real,N,N> MatNN;
#define CSmallLMSolver_Max(a,b) (a)>(b) ? (a) : (b);
public:
real Optimize(VecN& xStart, int nMaxIter)
{
const static real eps_1 = real(1e-12);
const static real eps_2 = real(1e-12);
const static real tau = real(1e-3);
MatMN Jac(M,N);
MatNM JacT(N,M);
MatNN JacTJac;
VecM f(M); //f(x)
VecN g; //g=-J'*f
VecN h; //(J'J + mu * I) h = g
VecN xnew, x;
VecM fnew(M); //f(xnew)
Eigen::LDLT<MatNN> solver;
//initial settings
x = xStart;
CalcJacobiFunc(x, Jac); //J
JacT = Jac.transpose();
CalcEnergyFunc(x, f); //f
g = JacT * (-f); //g
if(g.norm() <= eps_1)
return true;
JacTJac = JacT*Jac;
solver.compute(JacTJac);
h = solver.solve(g); //J'Jh = g
//find the diag of J'J
real v=real(2), mu=real(0);
for(int i=0; i<JacTJac.rows(); i++)
mu = CSmallLMSolver_Max(mu, JacTJac(i,i));
mu *= tau;
for(int iter=0; iter < nMaxIter; iter++)
{
//+mu*I
for(int i=0; i<JacTJac.rows(); i++)
JacTJac(i,i) += mu;
//solve
solver.compute(JacTJac);
h = solver.solve(g);
//-mu*I
for(int i=0; i<JacTJac.rows(); i++)
JacTJac(i,i) -= mu;
if(h.norm() <= eps_2 * (x.norm() + eps_2))
break;
xnew = x + h;
CalcEnergyFunc(xnew, fnew); //fnew
//dL = L(0) - L(h)
real dL = h.dot(mu*h+g);
real dF = f.dot(f) - fnew.dot(fnew);
real rho = dF/dL;
if(rho > 0)
{
x = xnew; //x
f = fnew; //f
CalcJacobiFunc(x, Jac); //J
JacT = Jac.transpose();
g = JacT * (-f); //g
if(g.norm() <= eps_1)
break;
JacTJac = JacT * Jac;
mu *= CSmallLMSolver_Max(real(1./3.), real(1-pow(2*rho-1,3)));
v = 2;
}
else
{
mu *= v;
v *= 2;
}
}//end for iter
xStart = x;
//return the final energy
return ldp::sqr( f.norm() );
}
protected:
virtual void CalcEnergyFunc(const VecN& x, VecM& fx)=0;
//default: calc jacobi matrix numerically with forward diff
virtual void CalcJacobiFunc(VecN& x, MatMN& jac)
{
const static real delta = real(1e-8);
VecM fx(M), fxp(M);
CalcEnergyFunc(x, fx);
for(int j=0; j<N; j++)
{
real d=real(1e-4)*x[j]; // force evaluation
d=fabs(d);
if(d<delta) d=delta;
x[j] += d;
CalcEnergyFunc(x, fxp);
x[j] -= d;
d = real(1.0)/d;
for(int i=0; i<M; i++)
{
jac(i,j) = (fxp[i]-fx[i])*d;
}
}//end for j
}
protected:
int M;
};
/**
* Levenberg-Marquardt Method for dense equations
* min_x { f(x)^2 }, with f_(m,1) and x_(n,1)
* */
class CDenseLMSolver
{
public:
typedef double real;
typedef Eigen::Matrix<real,-1,1> DVec;
typedef Eigen::Matrix<real,-1,-1> DMat;
#define CSmallLMSolver_Max(a,b) (a)>(b) ? (a) : (b);
public:
CDenseLMSolver()
{
useBound = false;
}
real Optimize(DVec& xStart, int nMaxIter, bool isInfoShow=false)
{
const static real eps_1 = real(1e-12);
const static real eps_2 = real(1e-12);
const static real tau = real(1e-3);
DMat Jac(M,N);
DMat JacT(N,M);
DMat JacTJac(N,N);
DVec f(M); //f(x)
DVec g(N); //g=-J'*f
DVec h(N); //(J'J + mu * I) h = g
DVec xnew(N), x(N);
DVec fnew(M); //f(xnew)
Eigen::LDLT<DMat> solver;
//initial settings
x = xStart;
CalcJacobiFunc(x, Jac); //J
JacT = Jac.transpose();
real f_energy = CalcEnergyFunc(x, f); //f
g = JacT * (-f); //g
if(g.norm() <= eps_1)
return true;
JacTJac = JacT*Jac;
solver.compute(JacTJac);
h = solver.solve(g); //J'Jh = g
//find the diag of J'J
real v=real(2), mu=real(0);
for(int i=0; i<JacTJac.rows(); i++)
mu = CSmallLMSolver_Max(mu, JacTJac(i,i));
mu *= tau;
int iter = 0;
for(iter=0; iter < nMaxIter; iter++)
{
//+mu*I
for(int i=0; i<JacTJac.rows(); i++)
JacTJac(i,i) += mu;
//solve
solver.compute(JacTJac);
h = solver.solve(g);
//-mu*I
for(int i=0; i<JacTJac.rows(); i++)
JacTJac(i,i) -= mu;
if(h.norm() <= eps_2 * (x.norm() + eps_2))
break;
xnew = x + h;
if (useBound)
{
xnew = xnew.cwiseMin(x_upper);
xnew = xnew.cwiseMax(x_lower);
h = xnew - h;
}
real fnew_energy = CalcEnergyFunc(xnew, fnew); //fnew
//dL = L(0) - L(h)
real dL = h.dot(mu*h+g);
real dF = f_energy - fnew_energy;
//real dF = f.dot(f) - fnew.dot(fnew);
real rho = dF/dL;
if(rho > 0)
{
x = xnew; //x
f = fnew; //f
f_energy = fnew_energy;
CalcJacobiFunc(x, Jac); //J
JacT = Jac.transpose();
g = JacT * (-f); //g
if(g.norm() <= eps_1)
break;
JacTJac = JacT * Jac;
mu *= CSmallLMSolver_Max(real(1./3.), real(1-pow(2*rho-1,3)));
v = 2;
}
else
{
mu *= v;
v *= 2;
}
if (isInfoShow && iter % 10 == 0)
printf("iter: %d, energy: %f, dif: %f\n", iter, sqrt(f.dot(f)), h.norm()/x.norm());
}//end for iter
if (isInfoShow)
printf("iter: %d, energy: %f, dif: %f\n", iter, sqrt(f.dot(f)), h.norm() / x.norm());
xStart = x;
return f_energy;
}
void SetBound(DVec& xMin, DVec& xMax)
{
x_lower = xMin;
x_upper = xMax;
useBound = true;
}
protected:
virtual real CalcEnergyFunc(const DVec& x, DVec& fx)=0;
//default: calc jacobi matrix numerically with forward diff
virtual void CalcJacobiFunc(DVec& x, DMat& jac)
{
const static real delta = real(1e-8);
DVec fx(M), fxp(M);
CalcEnergyFunc(x, fx);
for(int j=0; j<N; j++)
{
real d=real(1e-4)*x[j]; // force evaluation
d=fabs(d);
if(d<delta) d=delta;
x[j] += d;
CalcEnergyFunc(x, fxp);
x[j] -= d;
d = real(1.0)/d;
for(int i=0; i<M; i++)
{
jac(i,j) = (fxp[i]-fx[i])*d;
}
}//end for j
}
protected:
int M;
int N;
bool useBound;
DVec x_lower, x_upper;
};
class CSparseLMSolver
{
public:
typedef double real;
typedef Eigen::Matrix<real,-1,1> Vec;
typedef Eigen::SparseMatrix<real, Eigen::ColMajor> SpMat;
#define CSmallLMSolver_Max(a,b) (a)>(b) ? (a) : (b);
public:
real Optimize(Vec& xStart, int nMaxIter, bool showInfo=true)
{
const static real eps_1 = real(1e-12);
const static real eps_2 = real(1e-12);
const static real tau = real(1e-3);
//define jacobi structure
DefineJacobiStructure(m_jacobi, m_jacobiT);
SpMat JacTJac;
Vec f(m_jacobi.rows()); //f(x)
Vec g(m_jacobi.cols()); //g=-J'*f
Vec h(m_jacobi.cols()); //(J'J + mu * I) h = g
Eigen::VectorXi diagPos(m_jacobi.cols());
Vec diagKept(m_jacobi.cols());
Vec xnew(xStart.size());
Vec fnew(m_jacobi.rows()); //f(xnew)
//define structure of J'J
JacTJac = m_jacobiT * m_jacobiT.transpose();
Eigen::SimplicialCholesky<SpMat> solver(JacTJac);
//initial settings
CalcJacobiFunc(xStart,m_jacobi, m_jacobiT); //J
CalcEnergyFunc(xStart, f); //f
g = m_jacobiT * (-f); //g
if(g.norm() <= eps_1)
return f.dot(f);
FastAtAGivenStructure(m_jacobi, m_jacobiT, JacTJac);
//JacTJac = m_jacobiT * m_jacobiT.transpose();
solver.factorize(JacTJac);
h = solver.solve(g); //J'Jh = g
//find the diag of J'J
real v=real(2), mu=real(0);
Eigen::Diagonal<SpMat> diag(JacTJac);
for(int i=0; i<diag.size(); i++)
mu = CSmallLMSolver_Max(mu, diag[i]);
mu *= tau;
for(int iter=0; iter < nMaxIter; iter++)
{
//+mu*I
diag += Vec(diag.size()).setConstant(mu);
//solve
solver.factorize(JacTJac);
h = solver.solve(g);
//-mu*I
diag -= Vec(diag.size()).setConstant(mu);
if(h.norm() <= eps_2 * (xStart.norm() + eps_2))
break;
xnew = xStart + h;
CalcEnergyFunc(xnew, fnew); //fnew
//dL = L(0) - L(h)
real dL = h.dot(mu*h+g);
real dF = f.dot(f) - fnew.dot(fnew);
real rho = dF/dL;
if(rho > 0)
{
xStart = xnew; //x
f = fnew; //f
CalcJacobiFunc(xStart,m_jacobi, m_jacobiT); //J
g = m_jacobiT * (-f); //g
if(g.norm() <= eps_1)
break;
FastAtAGivenStructure(m_jacobi, m_jacobiT, JacTJac);
//JacTJac = m_jacobiT * m_jacobiT.transpose();
mu *= CSmallLMSolver_Max(real(1./3.), real(1-pow(2*rho-1,3)));
v = 2;
}
else
{
mu *= v;
v *= 2;
}
if((iter+1)%10==0 && showInfo)
printf("L-M:%d dif: %ef energy: %ef mu:%ef\n", iter, h.norm()/(eps_2+xStart.norm()), rho, mu);
}//end for iter
return f.dot(f);
}
protected:
//define the structure of jac and jacT
virtual void DefineJacobiStructure(SpMat& jac, SpMat& jacT)=0;
virtual void CalcEnergyFunc(const Vec& x, Vec& fx)=0;
//default: calc jacobi matrix numerically with forward diff
//Note that structure of both jac and jacT should be given
//children classes should fill both jac and jacT
virtual void CalcJacobiFunc(Vec& pTest, SpMat& jac, SpMat& jacT)
{
Vec p = pTest;
const int nobs = jac.rows();
const int nvars = jac.cols();
register int i, j, jj, k;
register real d;
int ii, m, *jcol, *varlist, *coldone, forw;
int *vidxs, *ridxs;
real *tmpd;
real delta;
/* retrieve problem-specific information passed in *dat */
Vec hx(nobs), hxx(nobs);
forw=1;
delta=real(1e-8);
CalcEnergyFunc(p, hx);//hx = f(p)
jcol=(int *)malloc(nobs*sizeof(int)); /* keeps track of measurements influenced by the set of variables currently in "varlist" below */
for(i=0; i<nobs; ++i) jcol[i]=-1;
vidxs=(int *)malloc(2*nobs*sizeof(int));
ridxs=vidxs+nobs;
varlist=(int *)malloc(nvars*sizeof(int)); /* stores indices of J's columns which are computed with the same "func" call */
coldone=(int *)malloc(nvars*sizeof(int)); /* keeps track of J's columns which have been already computed */
memset(coldone, 0, nvars*sizeof(int)); /* initialize to zero */
tmpd=(real *)malloc(nvars*sizeof(real));
for(j=0; j<nvars; ++j)
{
real scl;
if(coldone[j]) continue; /* column j already computed */
//for(i=0; i<nobs; ++i) jcol[i]=-1;
k=FindColIndices(jac, j, vidxs, ridxs);
for(i=0; i<k; ++i) jcol[ridxs[i]]=j;
varlist[0]=j; m=1; coldone[j]=1;
for(jj=j+1; jj<nvars; ++jj)
{
if(coldone[jj]) continue; /* column jj already computed */
k=FindColIndices(jac, jj, vidxs, ridxs);
for(i=0; i<k; ++i)
if(jcol[ridxs[i]]!=-1) goto nextjj;
if(k==0) { coldone[jj]=1; continue; } /* all zeros column, ignore */
/* column jj does not clash with previously considered ones, mark it */
for(i=0; i<k; ++i) jcol[ridxs[i]]=jj;
varlist[m++]=jj; coldone[jj]=1;
nextjj:
continue;
}
for(k=0; k<m; ++k)
{
/* determine d=max(SPLM_DELTA_SCALE*|p[varlist[k]]|, delta), see HZ */
d=real(1e-4)*p[varlist[k]]; // force evaluation
d=fabs(d);
if(d<delta) d=delta;
tmpd[varlist[k]]=d;
p[varlist[k]]+=d;
}
CalcEnergyFunc(p, hxx);// hxx=f(p+d)
if(forw)
{
for(k=0; k<m; ++k)
p[varlist[k]]-=tmpd[varlist[k]]; /* restore */
scl=1.0;
}
else
{ // central
for(k=0; k<m; ++k)
p[varlist[k]]-=2*tmpd[varlist[k]];
CalcEnergyFunc(p, hx);// hx=f(p-d)
for(k=0; k<m; ++k)
p[varlist[k]]+=tmpd[varlist[k]]; /* restore */
scl=0.5; // 1./2.
}
for(k=0; k<m; ++k)
{
d=tmpd[varlist[k]];
d=scl/d; /* invert so that divisions can be carried out faster as multiplications */
jj=FindColIndices(jac, varlist[k], vidxs, ridxs);
for(i=0; i<jj; ++i)
{
ii=ridxs[i];
jac.valuePtr()[vidxs[i]]=(hxx[ii]-hx[ii])*d;
jcol[ii]=-1; /* restore */
}
}
}//end for jj
//calc
FastTransGivenStructure(jac, jacT);
free(tmpd);
free(coldone);
free(varlist);
free(vidxs);
free(jcol);
}
protected:
int FindColIndices(const SpMat& A, int cid, int* vidx, int* ridx)
{
int ns = A.outerIndexPtr()[cid], ne = A.outerIndexPtr()[cid+1];
int k=0;
for(int i=ns; i<ne; i++,k++)
{
ridx[k] = A.innerIndexPtr()[i];
vidx[k] = i;
}
return k;
}
void FastTransGivenStructure(const Eigen::SparseMatrix<real>& A, Eigen::SparseMatrix<real>& At)
{
Eigen::VectorXi positions(At.outerSize());
for(int i=0; i<At.outerSize(); i++)
positions[i] = At.outerIndexPtr()[i];
for (int j=0; j<A.outerSize(); ++j)
{
for (Eigen::SparseMatrix<double>::InnerIterator it(A, j); it; ++it)
{
int i = it.index();
int pos = positions[i]++;
At.valuePtr()[pos] = it.value();
}
}
}
void FastAtAGivenStructure(const Eigen::SparseMatrix<real>& A, const Eigen::SparseMatrix<real>& At, Eigen::SparseMatrix<real>& AtA)
{
const static int nThread = 1;
//omp_set_num_threads(nThread);
Eigen::VectorXd Tmps[nThread];
Eigen::VectorXi Marks[nThread];
for(int i=0; i<nThread; i++)
{
Tmps[i].resize(AtA.innerSize());
Marks[i].resize(AtA.innerSize());
Marks[i].setZero();
}
//#pragma omp parallel for
for(int j=0; j<AtA.outerSize(); j++)
{
int tid = 0;//omp_get_thread_num();
Eigen::VectorXd& Tmp = Tmps[tid];
Eigen::VectorXi& Mark = Marks[tid];
for(Eigen::SparseMatrix<double>::InnerIterator it_A(A, j); it_A; ++it_A)
{
int k = it_A.index();
double v_A = it_A.value();
for(Eigen::SparseMatrix<double>::InnerIterator it_At(At, k); it_At; ++it_At)
{
int i = it_At.index();
double v_At = it_At.value();
if(!Mark[i])
{
Mark[i] = 1;
Tmp[i] = v_A*v_At;
}
else
Tmp[i] += v_A*v_At;
}//end for it_At
}//end for it_A
for(Eigen::SparseMatrix<double>::InnerIterator it(AtA, j); it; ++it)
{
int i = it.index();
it.valueRef() = Tmp[i];
Mark[i] = 0;
}
}//end for i
}
protected:
SpMat m_jacobi;
SpMat m_jacobiT;
};
class CDenseNewtonSolver :public CDenseLMSolver
{
public:
real Optimize(DVec& xStart, int nMaxIter, bool showInfo = false)
{
DMat jac(M, N);
DMat JacTJac(N,N);
DVec fx(M), fx1(M), h(N), g(N);
Eigen::LDLT<DMat> solver;
real f_energy = 0;
//Gauss-Newton Optimization
for (int iter = 0; iter<nMaxIter; iter++)
{
CalcJacobiFunc(xStart, jac); //J
JacTJac = jac.transpose() * jac;
f_energy = CalcEnergyFunc(xStart, fx); //f
//solve: J'J h = - J' f(x)
g = jac.transpose() * (-fx);
solver.compute(JacTJac);
h = solver.solve(g);
real normv = xStart.norm();
for (real alpha = 1; alpha > 1e-15; alpha *= 0.5)
{
DVec x = xStart + h;
if (useBound)
{
x = x.cwiseMin(x_upper);
x = x.cwiseMax(x_lower);
}
real f1_energy = CalcEnergyFunc(x, fx1); //f
//if (f1_energy > f_energy)
if (fx1.dot(fx1) > fx.dot(fx))
h = h * 0.5;
else
{
xStart = x;
break;
}
}
real normh = h.norm();
if (showInfo)
printf("Gauss-Newton: %d -- %f, energy: %f\n", iter, normh / normv, sqrt(fx.dot(fx)));
if (normh < (normv + real(1e-6)) * real(1e-6))
break;
}
return f_energy;
}
};
class CSparseNewtonSolver:public CSparseLMSolver
{
public:
real Optimize(Vec& xStart, int nMaxIter, bool showInfo=true)
{
//define jacobi structure
DefineJacobiStructure(m_jacobi, m_jacobiT);
SpMat JacTJac;
Vec fx(m_jacobi.rows()), h(m_jacobi.cols()), g(m_jacobi.cols()), fx1(m_jacobi.rows());
//define structure of J'J
JacTJac = m_jacobiT * m_jacobi;
Eigen::SimplicialCholesky<SpMat> solver;
solver.analyzePattern(JacTJac.triangularView<Eigen::Lower>());
//Gauss-Newton Optimization
for(int iter=0; iter<nMaxIter; iter++)
{
CalcJacobiFunc(xStart, m_jacobi, m_jacobiT); //J
//JacTJac = m_jacobiT * m_jacobi;//J'J
FastAtAGivenStructure(m_jacobi, m_jacobiT, JacTJac);
CalcEnergyFunc(xStart, fx); //f
//solve: J'J h = - J' f(x)
g = m_jacobiT * (-fx);
solver.factorize(JacTJac.triangularView<Eigen::Lower>());
h = solver.solve(g);
real normv = xStart.norm();
double old_energy = fx.dot(fx);
for (real alpha = 1; alpha > 1e-15; alpha *= 0.5)
{
Vec x = xStart + h;
CalcEnergyFunc(x, fx1); //f
double new_energy = fx1.dot(fx1);
if (new_energy > old_energy)
h = h * 0.5;
else
{
xStart = x;
break;
}
}
real normh = h.norm();
if(showInfo)
printf("Gauss-Newton: %d -- %f\n", iter, normh/normv);
if(normh < (normv+real(1e-6)) * real(1e-6))
break;
}
return fx.dot(fx);
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.