source
stringlengths
3
92
c
stringlengths
26
2.25M
threshold.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2018 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://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 "magick/studio.h" #include "magick/property.h" #include "magick/blob.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/configure.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/effect.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/montage.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/shear.h" #include "magick/signature-private.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/xml-tree.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ static const char *MinimalThresholdMap = "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image, % const size_t width,const size_t height, % const ssize_t offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o offset: the mean offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; 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); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) (width*height); image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket channel_bias, channel_sum; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict threshold_indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); channel_bias=zero; channel_sum=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) { channel_bias.red+=r[u].red; channel_bias.green+=r[u].green; channel_bias.blue+=r[u].blue; channel_bias.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } channel_sum.red+=r[u].red; channel_sum.green+=r[u].green; channel_sum.blue+=r[u].blue; channel_sum.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } r+=image->columns+width; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean; mean=zero; r=p; channel_sum.red-=channel_bias.red; channel_sum.green-=channel_bias.green; channel_sum.blue-=channel_bias.blue; channel_sum.opacity-=channel_bias.opacity; channel_sum.index-=channel_bias.index; channel_bias=zero; for (v=0; v < (ssize_t) height; v++) { channel_bias.red+=r[0].red; channel_bias.green+=r[0].green; channel_bias.blue+=r[0].blue; channel_bias.opacity+=r[0].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0); channel_sum.red+=r[width-1].red; channel_sum.green+=r[width-1].green; channel_sum.blue+=r[width-1].blue; channel_sum.opacity+=r[width-1].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+ width-1); r+=image->columns+width; } mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset); mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset); mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset); mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex( threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoThresholdImage() automatically selects a threshold and replaces each % pixel in the image with a black pixel if the image intentsity is less than % the selected threshold otherwise white. % % The format of the AutoThresholdImage method is: % % MagickBooleanType AutoThresholdImage(Image *image, % const AutoThresholdMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-threshold. % % o method: choose from Kapur, OTSU, or Triangle. % % o exception: return any errors or warnings in this structure. % */ static double KapurThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { #define MaxIntensity 255 double *black_entropy, *cumulative_histogram, entropy, epsilon, maximum_entropy, *white_entropy; register ssize_t i, j; size_t threshold; /* Compute optimal threshold from the entopy of the histogram. */ cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*cumulative_histogram)); black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*black_entropy)); white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*white_entropy)); if ((cumulative_histogram == (double *) NULL) || (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL)) { if (white_entropy != (double *) NULL) white_entropy=(double *) RelinquishMagickMemory(white_entropy); if (black_entropy != (double *) NULL) black_entropy=(double *) RelinquishMagickMemory(black_entropy); if (cumulative_histogram != (double *) NULL) cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Entropy for black and white parts of the histogram. */ cumulative_histogram[0]=histogram[0]; for (i=1; i <= MaxIntensity; i++) cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i]; epsilon=MagickMinimumValue; for (j=0; j <= MaxIntensity; j++) { /* Black entropy. */ black_entropy[j]=0.0; if (cumulative_histogram[j] > epsilon) { entropy=0.0; for (i=0; i <= j; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/cumulative_histogram[j]* log(histogram[i]/cumulative_histogram[j]); black_entropy[j]=entropy; } /* White entropy. */ white_entropy[j]=0.0; if ((1.0-cumulative_histogram[j]) > epsilon) { entropy=0.0; for (i=j+1; i <= MaxIntensity; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/(1.0-cumulative_histogram[j])* log(histogram[i]/(1.0-cumulative_histogram[j])); white_entropy[j]=entropy; } } /* Find histogram bin with maximum entropy. */ maximum_entropy=black_entropy[0]+white_entropy[0]; threshold=0; for (j=1; j <= MaxIntensity; j++) if ((black_entropy[j]+white_entropy[j]) > maximum_entropy) { maximum_entropy=black_entropy[j]+white_entropy[j]; threshold=(size_t) j; } /* Free resources. */ white_entropy=(double *) RelinquishMagickMemory(white_entropy); black_entropy=(double *) RelinquishMagickMemory(black_entropy); cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); return(100.0*threshold/MaxIntensity); } static double OTSUThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double max_sigma, *myu, *omega, *probability, *sigma, threshold; register ssize_t i; /* Compute optimal threshold from maximization of inter-class variance. */ myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu)); omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega)); probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*probability)); sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma)); if ((myu == (double *) NULL) || (omega == (double *) NULL) || (probability == (double *) NULL) || (sigma == (double *) NULL)) { if (sigma != (double *) NULL) sigma=(double *) RelinquishMagickMemory(sigma); if (probability != (double *) NULL) probability=(double *) RelinquishMagickMemory(probability); if (omega != (double *) NULL) omega=(double *) RelinquishMagickMemory(omega); if (myu != (double *) NULL) myu=(double *) RelinquishMagickMemory(myu); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Calculate probability density. */ for (i=0; i <= (ssize_t) MaxIntensity; i++) probability[i]=histogram[i]; /* Generate probability of graylevels and mean value for separation. */ omega[0]=probability[0]; myu[0]=0.0; for (i=1; i <= (ssize_t) MaxIntensity; i++) { omega[i]=omega[i-1]+probability[i]; myu[i]=myu[i-1]+i*probability[i]; } /* Sigma maximization: inter-class variance and compute optimal threshold. */ threshold=0; max_sigma=0.0; for (i=0; i < (ssize_t) MaxIntensity; i++) { sigma[i]=0.0; if ((omega[i] != 0.0) && (omega[i] != 1.0)) sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0- omega[i])); if (sigma[i] > max_sigma) { max_sigma=sigma[i]; threshold=(double) i; } } /* Free resources. */ myu=(double *) RelinquishMagickMemory(myu); omega=(double *) RelinquishMagickMemory(omega); probability=(double *) RelinquishMagickMemory(probability); sigma=(double *) RelinquishMagickMemory(sigma); return(100.0*threshold/MaxIntensity); } static double TriangleThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double a, b, c, count, distance, inverse_ratio, max_distance, segment, x1, x2, y1, y2; register ssize_t i; ssize_t end, max, start, threshold; /* Compute optimal threshold with triangle algorithm. */ (void) exception; start=0; /* find start bin, first bin not zero count */ for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > 0.0) { start=i; break; } end=0; /* find end bin, last bin not zero count */ for (i=(ssize_t) MaxIntensity; i >= 0; i--) if (histogram[i] > 0.0) { end=i; break; } max=0; /* find max bin, bin with largest count */ count=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > count) { max=i; count=histogram[i]; } /* Compute threshold at split point. */ x1=(double) max; y1=histogram[max]; x2=(double) end; if ((max-start) >= (end-max)) x2=(double) start; y2=0.0; a=y1-y2; b=x2-x1; c=(-1.0)*(a*x1+b*y1); inverse_ratio=1.0/sqrt(a*a+b*b+c*c); threshold=0; max_distance=0.0; if (x2 == (double) start) for (i=start; i < max; i++) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment > 0.0)) { threshold=i; max_distance=distance; } } else for (i=end; i > max; i--) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment < 0.0)) { threshold=i; max_distance=distance; } } return(100.0*threshold/MaxIntensity); } MagickExport MagickBooleanType AutoThresholdImage(Image *image, const AutoThresholdMethod method,ExceptionInfo *exception) { CacheView *image_view; char property[MagickPathExtent]; double gamma, *histogram, sum, threshold; MagickBooleanType status; register ssize_t i; ssize_t y; /* Form histogram. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; (void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { double intensity = GetPixelIntensity(image,p); histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++; p++; } } image_view=DestroyCacheView(image_view); /* Normalize histogram. */ sum=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) sum+=histogram[i]; gamma=PerceptibleReciprocal(sum); for (i=0; i <= (ssize_t) MaxIntensity; i++) histogram[i]=gamma*histogram[i]; /* Discover threshold from histogram. */ switch (method) { case KapurThresholdMethod: { threshold=KapurThreshold(image,histogram,exception); break; } case OTSUThresholdMethod: default: { threshold=OTSUThreshold(image,histogram,exception); break; } case TriangleThresholdMethod: { threshold=TriangleThreshold(image,histogram,exception); break; } } histogram=(double *) RelinquishMagickMemory(histogram); if (threshold < 0.0) status=MagickFalse; if (status == MagickFalse) return(MagickFalse); /* Threshold image. */ (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold); (void) SetImageProperty(image,"auto-threshold:threshold",property); return(BilevelImage(image,QuantumRange*threshold/100.0)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImageChannel method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold) % MagickBooleanType BilevelImageChannel(Image *image, % const ChannelType channel,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o threshold: define the threshold values. % % Aside: You can get the same results as operator using LevelImageChannels() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold) { MagickBooleanType status; status=BilevelImageChannel(image,DefaultChannels,threshold); return(status); } MagickExport MagickBooleanType BilevelImageChannel(Image *image, const ChannelType channel,const double threshold) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); /* Bilevel threshold image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); if ((channel & SyncChannels) != 0) { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelIntensity(image,q) <= threshold ? 0 : QuantumRange); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold ? 0 : QuantumRange); else SetPixelAlpha(q,(MagickRealType) GetPixelAlpha(q) <= threshold ? OpaqueOpacity : TransparentOpacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BilevelImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image,const char *threshold) % MagickBooleanType BlackThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=BlackThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); GetMagickPixelPacket(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* Black threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) < threshold.red)) SetPixelRed(q,0); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) < threshold.green)) SetPixelGreen(q,0); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) < threshold.blue)) SetPixelBlue(q,0); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) < threshold.opacity)) SetPixelOpacity(q,0); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x) < threshold.index)) SetPixelIndex(indexes+x,0); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BlackThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImageChannel method is: % % MagickBooleanType ClampImage(Image *image) % MagickBooleanType ClampImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % */ MagickExport MagickBooleanType ClampImage(Image *image) { MagickBooleanType status; status=ClampImageChannel(image,DefaultChannels); return(status); } MagickExport MagickBooleanType ClampImageChannel(Image *image, const ChannelType channel) { #define ClampImageTag "Clamp/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q))); SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q))); SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q))); SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q))); q++; } return(SyncImage(image)); } /* Clamp image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q))); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampPixel((MagickRealType) GetPixelIndex( indexes+x))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ClampImageChannel) #endif proceed=SetImageProgress(image,ClampImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMapFile(const char *xml, const char *filename,const char *map_id,ExceptionInfo *exception) { const char *attribute, *content; double value; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; map = (ThresholdMap *) NULL; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(map); for (threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { attribute=GetXMLTreeAttribute(threshold, "map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold, "alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } /* The map has been found -- allocate a Threshold Map to return */ map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap)); if (map == (ThresholdMap *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; /* Assign basic attributeibutes. */ attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels, "divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } /* Allocate theshold levels array. */ content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); { char *p; register ssize_t i; /* Parse levels into integer array. */ for (i=0; i< (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() load and search one or more threshold map files for the % a map matching the given name or aliase. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; ThresholdMap *map; map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { XMLTreeInfo *thresholds,*threshold,*description; const char *map,*alias,*content; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); for( threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { map = GetXMLTreeAttribute(threshold, "map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias = GetXMLTreeAttribute(threshold, "alias"); /* alias is optional, no if test needed */ description=GetXMLTreeChild(threshold,"description"); if ( description == (XMLTreeInfo *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if ( content == (char *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() uses the ordered dithering technique of reducing color % images to monochrome using positional information to retain as much % information as possible. % % WARNING: This function is deprecated, and is now just a call to % the more more powerful OrderedPosterizeImage(); function. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image) % MagickBooleanType OrderedDitherImageChannel(Image *image, % const ChannelType channel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image) { MagickBooleanType status; status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception); return(status); } MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image, const ChannelType channel,ExceptionInfo *exception) { MagickBooleanType status; /* Call the augumented function OrderedPosterizeImage() */ status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedPosterizeImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedPosterizeImage method is: % % MagickBooleanType OrderedPosterizeImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % MagickBooleanType OrderedPosterizeImageChannel(Image *image, % const ChannelType channel,const char *threshold_map, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { MagickBooleanType status; status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map, exception); return(status); } MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image, const ChannelType channel,const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; LongPixelPacket levels; MagickBooleanType status; MagickOffsetType progress; ssize_t y; ThresholdMap *map; assert(image != (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); if (threshold_map == (const char *) NULL) return(MagickTrue); { char token[MaxTextExtent]; register const char *p; p=(char *)threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MaxTextExtent-1)) break; token[p-threshold_map] = *p; p++; } token[p-threshold_map] = '\0'; map = GetThresholdMap(token, exception); if ( map == (ThresholdMap *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } } /* Set channel levels from extra comma separated arguments Default to 2, the single value given, or individual channel values */ #if 1 { /* parse directly as a comma separated list of integers */ char *p; p = strchr((char *) threshold_map,','); if ( p != (char *) NULL && isdigit((int) ((unsigned char) *(++p))) ) levels.index = (unsigned int) strtoul(p, &p, 10); else levels.index = 2; levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0; levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0; levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0; levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0; levels.index = ((channel & IndexChannel) != 0 && (image->colorspace == CMYKColorspace)) ? levels.index : 0; /* if more than a single number, each channel has a separate value */ if ( p != (char *) NULL && *p == ',' ) { p=strchr((char *) threshold_map,','); p++; if ((channel & RedChannel) != 0) levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & GreenChannel) != 0) levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & BlueChannel) != 0) levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & OpacityChannel) != 0) levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); } } #else /* Parse level values as a geometry */ /* This difficult! * How to map GeometryInfo structure elements into * LongPixelPacket structure elements, but according to channel? * Note the channels list may skip elements!!!! * EG -channel BA -ordered-dither map,2,3 * will need to map g.rho -> l.blue, and g.sigma -> l.opacity * A simpler way is needed, probably converting geometry to a temporary * array, then using channel to advance the index into ssize_t pixel packet. */ #endif #if 0 printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n", levels.red, levels.green, levels.blue, levels.opacity, levels.index); #endif { /* Do the posterized ordered dithering of the image */ ssize_t d; /* d = number of psuedo-level divisions added between color levels */ d = map->divisor-1; /* reduce levels to levels - 1 */ levels.red = levels.red ? levels.red-1 : 0; levels.green = levels.green ? levels.green-1 : 0; levels.blue = levels.blue ? levels.blue-1 : 0; levels.opacity = levels.opacity ? levels.opacity-1 : 0; levels.index = levels.index ? levels.index-1 : 0; if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t threshold, t, l; /* Figure out the dither threshold for this pixel This must be a integer from 1 to map->divisor-1 */ threshold = map->levels[(x%map->width) +map->width*(y%map->height)]; /* Dither each channel in the image as appropriate Notes on the integer Math... total number of divisions = (levels-1)*(divisor-1)+1) t1 = this colors psuedo_level = q->red * total_divisions / (QuantumRange+1) l = posterization level 0..levels t = dither threshold level 0..divisor-1 NB: 0 only on last Each color_level is of size QuantumRange / (levels-1) NB: All input levels and divisor are already had 1 subtracted Opacity is inverted so 'off' represents transparent. */ if (levels.red) { t = (ssize_t) (QuantumScale*GetPixelRed(q)*(levels.red*d+1)); l = t/d; t = t-l*d; SetPixelRed(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red))); } if (levels.green) { t = (ssize_t) (QuantumScale*GetPixelGreen(q)* (levels.green*d+1)); l = t/d; t = t-l*d; SetPixelGreen(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green))); } if (levels.blue) { t = (ssize_t) (QuantumScale*GetPixelBlue(q)* (levels.blue*d+1)); l = t/d; t = t-l*d; SetPixelBlue(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue))); } if (levels.opacity) { t = (ssize_t) ((1.0-QuantumScale*GetPixelOpacity(q))* (levels.opacity*d+1)); l = t/d; t = t-l*d; SetPixelOpacity(q,ClampToQuantum((MagickRealType) ((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/ levels.opacity))); } if (levels.index) { t = (ssize_t) (QuantumScale*GetPixelIndex(indexes+x)* (levels.index*d+1)); l = t/d; t = t-l*d; SetPixelIndex(indexes+x,ClampToQuantum((MagickRealType) ((l+ (t>=threshold))*(MagickRealType) QuantumRange/levels.index))); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OrderedPosterizeImageChannel) #endif proceed=SetImageProgress(image,DitherImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImageChannel method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon) % MagickBooleanType PerceptibleImageChannel(Image *image, % const ChannelType channel,const double epsilon) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon) { MagickBooleanType status; status=PerceptibleImageChannel(image,DefaultChannels,epsilon); return(status); } MagickExport MagickBooleanType PerceptibleImageChannel(Image *image, const ChannelType channel,const double epsilon) { #define PerceptibleImageTag "Perceptible/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon)); SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); q++; } return(SyncImage(image)); } /* Perceptible image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,PerceptibleThreshold(GetPixelIndex(indexes+x), epsilon)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_PerceptibleImageChannel) #endif proceed=SetImageProgress(image,PerceptibleImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImageChannel(Image *image, % const char *thresholds,ExceptionInfo *exception) % MagickBooleanType RandomThresholdImageChannel(Image *image, % const ChannelType channel,const char *thresholds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o thresholds: a geometry string containing low,high thresholds. If the % string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4 % is performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { MagickBooleanType status; status=RandomThresholdImageChannel(image,DefaultChannels,thresholds, exception); return(status); } MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickStatusType flags; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickRealType min_threshold, max_threshold; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (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); if (thresholds == (const char *) NULL) return(MagickTrue); GetMagickPixelPacket(image,&threshold); min_threshold=0.0; max_threshold=(MagickRealType) QuantumRange; flags=ParseGeometry(thresholds,&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(thresholds,'%') != (char *) NULL) { max_threshold*=(MagickRealType) (0.01*QuantumRange); min_threshold*=(MagickRealType) (0.01*QuantumRange); } else if (((max_threshold == min_threshold) || (max_threshold == 1)) && (min_threshold <= 8)) { /* Backward Compatibility -- ordered-dither -- IM v 6.2.9-6. */ status=OrderedPosterizeImageChannel(image,channel,thresholds,exception); return(status); } /* Random threshold image. */ status=MagickTrue; progress=0; if (channel == CompositeChannels) { if (AcquireImageColormap(image,2) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { IndexPacket index; MagickRealType intensity; intensity=GetPixelIntensity(image,q); if (intensity < min_threshold) threshold.index=min_threshold; else if (intensity > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType)(QuantumRange* GetPseudoRandomValue(random_info[id])); index=(IndexPacket) (intensity <= threshold.index ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RandomThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { if ((MagickRealType) GetPixelRed(q) < min_threshold) threshold.red=min_threshold; else if ((MagickRealType) GetPixelRed(q) > max_threshold) threshold.red=max_threshold; else threshold.red=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & GreenChannel) != 0) { if ((MagickRealType) GetPixelGreen(q) < min_threshold) threshold.green=min_threshold; else if ((MagickRealType) GetPixelGreen(q) > max_threshold) threshold.green=max_threshold; else threshold.green=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & BlueChannel) != 0) { if ((MagickRealType) GetPixelBlue(q) < min_threshold) threshold.blue=min_threshold; else if ((MagickRealType) GetPixelBlue(q) > max_threshold) threshold.blue=max_threshold; else threshold.blue=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & OpacityChannel) != 0) { if ((MagickRealType) GetPixelOpacity(q) < min_threshold) threshold.opacity=min_threshold; else if ((MagickRealType) GetPixelOpacity(q) > max_threshold) threshold.opacity=max_threshold; else threshold.opacity=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((MagickRealType) GetPixelIndex(indexes+x) < min_threshold) threshold.index=min_threshold; else if ((MagickRealType) GetPixelIndex(indexes+x) > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold.red ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold.green ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold.blue ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold.opacity ? 0 : QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold.index ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RandomThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold) % MagickBooleanType WhiteThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=WhiteThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); flags=ParseGeometry(thresholds,&geometry_info); GetMagickPixelPacket(image,&threshold); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) > threshold.red)) SetPixelRed(q,QuantumRange); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) > threshold.green)) SetPixelGreen(q,QuantumRange); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) > threshold.blue)) SetPixelBlue(q,QuantumRange); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) > threshold.opacity)) SetPixelOpacity(q,QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x)) > threshold.index) SetPixelIndex(indexes+x,QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_WhiteThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
image-view.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % IIIII M M AAA GGGG EEEEE % % I MM MM A A G E % % I M M M AAAAA G GG EEE % % I M M A A G G E % % IIIII M M A A GGGG EEEEE % % % % V V IIIII EEEEE W W % % V V I E W W % % V V I EEE W W W % % V V I E WW WW % % V IIIII EEEEE W W % % % % % % MagickCore Image View Methods % % % % Software Design % % John Cristy % % March 2003 % % % % % % Copyright 1999-2013 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 "magick/studio.h" #include "magick/MagickCore.h" #include "magick/exception-private.h" #include "magick/monitor-private.h" #include "magick/thread-private.h" /* Typedef declarations. */ struct _ImageView { char *description; RectangleInfo extent; Image *image; CacheView *view; size_t number_threads; ExceptionInfo *exception; MagickBooleanType debug; size_t signature; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageView() makes a copy of the specified image view. % % The format of the CloneImageView method is: % % ImageView *CloneImageView(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport ImageView *CloneImageView(const ImageView *image_view) { ImageView *clone_view; assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); clone_view=(ImageView *) AcquireMagickMemory(sizeof(*clone_view)); if (clone_view == (ImageView *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(clone_view,0,sizeof(*clone_view)); clone_view->description=ConstantString(image_view->description); clone_view->extent=image_view->extent; clone_view->view=CloneCacheView(image_view->view); clone_view->number_threads=image_view->number_threads; clone_view->exception=AcquireExceptionInfo(); InheritException(clone_view->exception,image_view->exception); clone_view->debug=image_view->debug; clone_view->signature=MagickSignature; return(clone_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageView() deallocates memory associated with a image view. % % The format of the DestroyImageView method is: % % ImageView *DestroyImageView(ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport ImageView *DestroyImageView(ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); if (image_view->description != (char *) NULL) image_view->description=DestroyString(image_view->description); image_view->view=DestroyCacheView(image_view->view); image_view->exception=DestroyExceptionInfo(image_view->exception); image_view->signature=(~MagickSignature); image_view=(ImageView *) RelinquishMagickMemory(image_view); return(image_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D u p l e x T r a n s f e r I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DuplexTransferImageViewIterator() iterates over three image views in % parallel and calls your transfer method for each scanline of the view. The % source and duplex pixel extent is not confined to the image canvas-- that is % you can include negative offsets or widths or heights that exceed the image % dimension. However, the destination image view is confined to the image % canvas-- that is no negative offsets or widths or heights that exceed the % image dimension are permitted. % % The callback signature is: % % MagickBooleanType DuplexTransferImageViewMethod(const ImageView *source, % const ImageView *duplex,ImageView *destination,const ssize_t y, % const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the DuplexTransferImageViewIterator method is: % % MagickBooleanType DuplexTransferImageViewIterator(ImageView *source, % ImageView *duplex,ImageView *destination, % DuplexTransferImageViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o duplex: the duplex image view. % % o destination: the destination image view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType DuplexTransferImageViewIterator( ImageView *source,ImageView *duplex,ImageView *destination, DuplexTransferImageViewMethod transfer,void *context) { ExceptionInfo *exception; Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickSignature); if (transfer == (DuplexTransferImageViewMethod) NULL) return(MagickFalse); source_image=source->image; destination_image=destination->image; if (SetImageStorageClass(destination_image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; exception=destination->exception; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=(size_t) (source->extent.height-source->extent.y); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const PixelPacket *restrict duplex_pixels, *restrict pixels; register PixelPacket *restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const PixelPacket *) NULL) { status=MagickFalse; continue; } duplex_pixels=GetCacheViewVirtualPixels(duplex->view,duplex->extent.x,y, duplex->extent.width,1,duplex->exception); if (duplex_pixels == (const PixelPacket *) NULL) { status=MagickFalse; continue; } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1,exception); if (destination_pixels == (PixelPacket *) NULL) { status=MagickFalse; continue; } if (transfer(source,duplex,destination,y,id,context) == MagickFalse) status=MagickFalse; sync=SyncCacheViewAuthenticPixels(destination->view,exception); if (sync == MagickFalse) { InheritException(destination->exception,GetCacheViewException( source->view)); status=MagickFalse; } if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_DuplexTransferImageViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w A u t h e n t i c I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewAuthenticIndexes() returns the image view authentic indexes. % % The format of the GetImageViewAuthenticPixels method is: % % IndexPacket *GetImageViewAuthenticIndexes(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport IndexPacket *GetImageViewAuthenticIndexes( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); return(GetCacheViewAuthenticIndexQueue(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewAuthenticPixels() returns the image view authentic pixels. % % The format of the GetImageViewAuthenticPixels method is: % % PixelPacket *GetImageViewAuthenticPixels(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport PixelPacket *GetImageViewAuthenticPixels( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); return(GetCacheViewAuthenticPixelQueue(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewException() returns the severity, reason, and description of any % error that occurs when utilizing a image view. % % The format of the GetImageViewException method is: % % char *GetImageViewException(const PixelImage *image_view, % ExceptionType *severity) % % A description of each parameter follows: % % o image_view: the pixel image_view. % % o severity: the severity of the error is returned here. % */ MagickExport char *GetImageViewException(const ImageView *image_view, ExceptionType *severity) { char *description; assert(image_view != (const ImageView *) NULL); assert(image_view->signature == MagickSignature); assert(severity != (ExceptionType *) NULL); *severity=image_view->exception->severity; description=(char *) AcquireQuantumMemory(2UL*MaxTextExtent, sizeof(*description)); if (description == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); *description='\0'; if (image_view->exception->reason != (char *) NULL) (void) CopyMagickString(description,GetLocaleExceptionMessage( image_view->exception->severity,image_view->exception->reason), MaxTextExtent); if (image_view->exception->description != (char *) NULL) { (void) ConcatenateMagickString(description," (",MaxTextExtent); (void) ConcatenateMagickString(description,GetLocaleExceptionMessage( image_view->exception->severity,image_view->exception->description), MaxTextExtent); (void) ConcatenateMagickString(description,")",MaxTextExtent); } return(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewExtent() returns the image view extent. % % The format of the GetImageViewExtent method is: % % RectangleInfo GetImageViewExtent(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport RectangleInfo GetImageViewExtent(const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); return(image_view->extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewImage() returns the image associated with the image view. % % The format of the GetImageViewImage method is: % % MagickCore *GetImageViewImage(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport Image *GetImageViewImage(const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); return(image_view->image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewIterator() iterates over the image view in parallel and calls % your get method for each scanline of the view. The pixel extent is % not confined to the image canvas-- that is you can include negative offsets % or widths or heights that exceed the image dimension. Any updates to % the pixels in your callback are ignored. % % The callback signature is: % % MagickBooleanType GetImageViewMethod(const ImageView *source, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback get method that must be % executed by a single thread at a time. % % The format of the GetImageViewIterator method is: % % MagickBooleanType GetImageViewIterator(ImageView *source, % GetImageViewMethod get,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o get: the get callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType GetImageViewIterator(ImageView *source, GetImageViewMethod get,void *context) { Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickSignature); if (get == (GetImageViewMethod) NULL) return(MagickFalse); source_image=source->image; status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=(size_t) (source->extent.height-source->extent.y); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); register const PixelPacket *pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const PixelPacket *) NULL) { status=MagickFalse; continue; } if (get(source,y,id,context) == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetImageViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w V i r t u a l I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewVirtualIndexes() returns the image view virtual indexes. % % The format of the GetImageViewVirtualIndexes method is: % % const IndexPacket *GetImageViewVirtualIndexes( % const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport const IndexPacket *GetImageViewVirtualIndexes( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); return(GetCacheViewVirtualIndexQueue(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i e w V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageViewVirtualPixels() returns the image view virtual pixels. % % The format of the GetImageViewVirtualPixels method is: % % const PixelPacket *GetImageViewVirtualPixels(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport const PixelPacket *GetImageViewVirtualPixels( const ImageView *image_view) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); return(GetCacheViewVirtualPixelQueue(image_view->view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImageView() returns MagickTrue if the the parameter is verified as a image % view object. % % The format of the IsImageView method is: % % MagickBooleanType IsImageView(const ImageView *image_view) % % A description of each parameter follows: % % o image_view: the image view. % */ MagickExport MagickBooleanType IsImageView(const ImageView *image_view) { if (image_view == (const ImageView *) NULL) return(MagickFalse); if (image_view->signature != MagickSignature) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w I m a g e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewImageView() returns a image view required for all other methods in the % Image View API. % % The format of the NewImageView method is: % % ImageView *NewImageView(MagickCore *wand) % % A description of each parameter follows: % % o wand: the wand. % */ MagickExport ImageView *NewImageView(Image *image) { ImageView *image_view; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); image_view=(ImageView *) AcquireMagickMemory(sizeof(*image_view)); if (image_view == (ImageView *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(image_view,0,sizeof(*image_view)); image_view->description=ConstantString("ImageView"); image_view->image=image; image_view->exception=AcquireExceptionInfo(); image_view->view=AcquireVirtualCacheView(image_view->image, image_view->exception); image_view->extent.width=image->columns; image_view->extent.height=image->rows; image_view->extent.x=0; image_view->extent.y=0; image_view->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); image_view->debug=IsEventLogging(); image_view->signature=MagickSignature; return(image_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w I m a g e V i e w R e g i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewImageViewRegion() returns a image view required for all other methods % in the Image View API. % % The format of the NewImageViewRegion method is: % % ImageView *NewImageViewRegion(MagickCore *wand,const ssize_t x, % const ssize_t y,const size_t width,const size_t height) % % A description of each parameter follows: % % o wand: the magick wand. % % o x,y,columns,rows: These values define the perimeter of a extent of % pixel_wands view. % */ MagickExport ImageView *NewImageViewRegion(Image *image,const ssize_t x, const ssize_t y,const size_t width,const size_t height) { ImageView *image_view; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); image_view=(ImageView *) AcquireMagickMemory(sizeof(*image_view)); if (image_view == (ImageView *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(image_view,0,sizeof(*image_view)); image_view->description=ConstantString("ImageView"); image_view->exception=AcquireExceptionInfo(); image_view->view=AcquireVirtualCacheView(image_view->image, image_view->exception); image_view->image=image; image_view->extent.width=width; image_view->extent.height=height; image_view->extent.x=x; image_view->extent.y=y; image_view->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); image_view->debug=IsEventLogging(); image_view->signature=MagickSignature; return(image_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i e w D e s c r i p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageViewDescription() associates a description with an image view. % % The format of the SetImageViewDescription method is: % % void SetImageViewDescription(ImageView *image_view, % const char *description) % % A description of each parameter follows: % % o image_view: the image view. % % o description: the image view description. % */ MagickExport void SetImageViewDescription(ImageView *image_view, const char *description) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); image_view->description=ConstantString(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageViewIterator() iterates over the image view in parallel and calls % your set method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension. The pixels are initiallly % undefined and any settings you make in the callback method are automagically % synced back to your image. % % The callback signature is: % % MagickBooleanType SetImageViewMethod(ImageView *destination, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback set method that must be % executed by a single thread at a time. % % The format of the SetImageViewIterator method is: % % MagickBooleanType SetImageViewIterator(ImageView *destination, % SetImageViewMethod set,void *context) % % A description of each parameter follows: % % o destination: the image view. % % o set: the set callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType SetImageViewIterator(ImageView *destination, SetImageViewMethod set,void *context) { ExceptionInfo *exception; Image *destination_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(destination != (ImageView *) NULL); assert(destination->signature == MagickSignature); if (set == (SetImageViewMethod) NULL) return(MagickFalse); destination_image=destination->image; if (SetImageStorageClass(destination_image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=(size_t) (destination->extent.height-destination->extent.y); #endif exception=destination->exception; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(destination_image,destination_image,height,1) #endif for (y=destination->extent.y; y < (ssize_t) destination->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register PixelPacket *restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(destination->view,destination->extent.x, y,destination->extent.width,1,exception); if (pixels == (PixelPacket *) NULL) { InheritException(destination->exception,GetCacheViewException( destination->view)); status=MagickFalse; continue; } if (set(destination,y,id,context) == MagickFalse) status=MagickFalse; sync=SyncCacheViewAuthenticPixels(destination->view,exception); if (sync == MagickFalse) { InheritException(destination->exception,GetCacheViewException( destination->view)); status=MagickFalse; } if (destination_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SetImageViewIterator) #endif proceed=SetImageProgress(destination_image,destination->description, progress++,destination->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i e w T h r e a d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageViewThreads() sets the number of threads in a thread team. % % The format of the SetImageViewDescription method is: % % void SetImageViewThreads(ImageView *image_view, % const size_t number_threads) % % A description of each parameter follows: % % o image_view: the image view. % % o number_threads: the number of threads in a thread team. % */ MagickExport void SetImageViewThreads(ImageView *image_view, const size_t number_threads) { assert(image_view != (ImageView *) NULL); assert(image_view->signature == MagickSignature); image_view->number_threads=number_threads; if (number_threads > (size_t) GetMagickResourceLimit(ThreadResource)) image_view->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f e r I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransferImageViewIterator() iterates over two image views in parallel and % calls your transfer method for each scanline of the view. The source pixel % extent is not confined to the image canvas-- that is you can include % negative offsets or widths or heights that exceed the image dimension. % However, the destination image view is confined to the image canvas-- that % is no negative offsets or widths or heights that exceed the image dimension % are permitted. % % The callback signature is: % % MagickBooleanType TransferImageViewMethod(const ImageView *source, % ImageView *destination,const ssize_t y,const int thread_id, % void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the TransferImageViewIterator method is: % % MagickBooleanType TransferImageViewIterator(ImageView *source, % ImageView *destination,TransferImageViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o destination: the destination image view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType TransferImageViewIterator(ImageView *source, ImageView *destination,TransferImageViewMethod transfer,void *context) { ExceptionInfo *exception; Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickSignature); if (transfer == (TransferImageViewMethod) NULL) return(MagickFalse); source_image=source->image; destination_image=destination->image; if (SetImageStorageClass(destination_image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; exception=destination->exception; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=(size_t) (source->extent.height-source->extent.y); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const PixelPacket *restrict pixels; register PixelPacket *restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const PixelPacket *) NULL) { status=MagickFalse; continue; } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1,exception); if (destination_pixels == (PixelPacket *) NULL) { status=MagickFalse; continue; } if (transfer(source,destination,y,id,context) == MagickFalse) status=MagickFalse; sync=SyncCacheViewAuthenticPixels(destination->view,exception); if (sync == MagickFalse) { InheritException(destination->exception,GetCacheViewException( source->view)); status=MagickFalse; } if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransferImageViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U p d a t e I m a g e V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UpdateImageViewIterator() iterates over the image view in parallel and calls % your update method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension are permitted. Updates to pixels % in your callback are automagically synced back to the image. % % The callback signature is: % % MagickBooleanType UpdateImageViewMethod(ImageView *source, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback update method that must be % executed by a single thread at a time. % % The format of the UpdateImageViewIterator method is: % % MagickBooleanType UpdateImageViewIterator(ImageView *source, % UpdateImageViewMethod update,void *context) % % A description of each parameter follows: % % o source: the source image view. % % o update: the update callback method. % % o context: the user defined context. % */ MagickExport MagickBooleanType UpdateImageViewIterator(ImageView *source, UpdateImageViewMethod update,void *context) { ExceptionInfo *exception; Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (ImageView *) NULL); assert(source->signature == MagickSignature); if (update == (UpdateImageViewMethod) NULL) return(MagickFalse); source_image=source->image; if (SetImageStorageClass(source_image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; exception=source->exception; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=(size_t) (source->extent.height-source->extent.y); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); register PixelPacket *restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(source->view,source->extent.x,y, source->extent.width,1,exception); if (pixels == (PixelPacket *) NULL) { InheritException(source->exception,GetCacheViewException(source->view)); status=MagickFalse; continue; } if (update(source,y,id,context) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(source->view,exception) == MagickFalse) { InheritException(source->exception,GetCacheViewException(source->view)); status=MagickFalse; } if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_UpdateImageViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); }
convolution_sgemm_packnto1.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. static void im2col_sgemm_packnto1_rvv(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { const int packn = csrr_vlenb() / 4; const word_type vl = vsetvl_e32m1(packn); // Mat bottom_im2col(size, maxk, inch, 4u * packn, packn, 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; const float* bias = _bias; Mat tmp; if (size >= 8) tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 4u * packn, packn, opt.workspace_allocator); else if (size >= 4) tmp.create(4 * maxk, inch, size / 4 + (size % 4) / 2 + size % 2, 4u * packn, packn, opt.workspace_allocator); else if (size >= 2) tmp.create(2 * maxk, inch, size / 2 + size % 2, 4u * packn, packn, opt.workspace_allocator); else tmp.create(maxk, inch, size, 4u * packn, packn, opt.workspace_allocator); { int remain_size_start = 0; int nn_size = size >> 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; float* tmpptr = tmp.channel(i / 8); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * packn; for (int k = 0; k < maxk; k++) { #if RVV_SPEC_0_7 for (int l = 0; l < packn; l++) { tmpptr[0] = img0[l]; tmpptr[1] = img0[l + packn]; tmpptr[2] = img0[l + packn * 2]; tmpptr[3] = img0[l + packn * 3]; tmpptr[4] = img0[l + packn * 4]; tmpptr[5] = img0[l + packn * 5]; tmpptr[6] = img0[l + packn * 6]; tmpptr[7] = img0[l + packn * 7]; tmpptr += 8; } img0 += size * packn; #else vfloat32m1_t _val0 = vle32_v_f32m1(img0, vl); vfloat32m1_t _val1 = vle32_v_f32m1(img0 + packn, vl); vfloat32m1_t _val2 = vle32_v_f32m1(img0 + packn * 2, vl); vfloat32m1_t _val3 = vle32_v_f32m1(img0 + packn * 3, vl); vfloat32m1_t _val4 = vle32_v_f32m1(img0 + packn * 4, vl); vfloat32m1_t _val5 = vle32_v_f32m1(img0 + packn * 5, vl); vfloat32m1_t _val6 = vle32_v_f32m1(img0 + packn * 6, vl); vfloat32m1_t _val7 = vle32_v_f32m1(img0 + packn * 7, vl); vsseg8e32_v_f32m1x8(tmpptr, vcreate_f32m1x8(_val0, _val1, _val2, _val3, _val4, _val5, _val6, _val7), vl); img0 += size * packn; tmpptr += packn * 8; #endif } } } remain_size_start += nn_size << 3; nn_size = (size - remain_size_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 4; float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * packn; for (int k = 0; k < maxk; k++) { #if RVV_SPEC_0_7 for (int l = 0; l < packn; l++) { tmpptr[0] = img0[l]; tmpptr[1] = img0[l + packn]; tmpptr[2] = img0[l + packn * 2]; tmpptr[3] = img0[l + packn * 3]; tmpptr += 4; } img0 += size * packn; #else vfloat32m1_t _val0 = vle32_v_f32m1(img0, vl); vfloat32m1_t _val1 = vle32_v_f32m1(img0 + packn, vl); vfloat32m1_t _val2 = vle32_v_f32m1(img0 + packn * 2, vl); vfloat32m1_t _val3 = vle32_v_f32m1(img0 + packn * 3, vl); vsseg4e32_v_f32m1x4(tmpptr, vcreate_f32m1x4(_val0, _val1, _val2, _val3), vl); img0 += size * packn; tmpptr += packn * 4; #endif } } } remain_size_start += nn_size << 2; nn_size = (size - remain_size_start) >> 1; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 2; float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * packn; for (int k = 0; k < maxk; k++) { #if RVV_SPEC_0_7 for (int l = 0; l < packn; l++) { tmpptr[0] = img0[l]; tmpptr[1] = img0[l + packn]; tmpptr += 2; } img0 += size * packn; #else vfloat32m1_t _val0 = vle32_v_f32m1(img0, vl); vfloat32m1_t _val1 = vle32_v_f32m1(img0 + packn, vl); vsseg2e32_v_f32m1x2(tmpptr, vcreate_f32m1x2(_val0, _val1), vl); img0 += size * packn; tmpptr += packn * 2; #endif } } } remain_size_start += nn_size << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * packn; for (int k = 0; k < maxk; k++) { vfloat32m1_t _val = vle32_v_f32m1(img0, vl); vse32_v_f32m1(tmpptr, _val, vl); img0 += size * packn; tmpptr += packn; } } } } int nn_outch = outch / packn; int remain_outch_start = nn_outch * packn; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * packn; float* outptr0 = top_blob.channel(p); const float zeros[packn] = {0.f}; const float* biasptr = bias ? bias + p : zeros; int i = 0; for (; i + 7 < size; i += 8) { const float* tmpptr = tmp.channel(i / 8); const float* kptr0 = kernel.channel(p / packn); int nn = inch * maxk * packn; // inch always > 0 vfloat32m1_t _sum0 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum1 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum2 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum3 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum4 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum5 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum6 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum7 = vle32_v_f32m1(biasptr, vl); for (int j = 0; j < nn; j++) { float val0 = *tmpptr++; float val1 = *tmpptr++; float val2 = *tmpptr++; float val3 = *tmpptr++; float val4 = *tmpptr++; float val5 = *tmpptr++; float val6 = *tmpptr++; float val7 = *tmpptr++; vfloat32m1_t _w0 = vle32_v_f32m1(kptr0, vl); _sum0 = vfmacc_vf_f32m1(_sum0, val0, _w0, vl); _sum1 = vfmacc_vf_f32m1(_sum1, val1, _w0, vl); _sum2 = vfmacc_vf_f32m1(_sum2, val2, _w0, vl); _sum3 = vfmacc_vf_f32m1(_sum3, val3, _w0, vl); _sum4 = vfmacc_vf_f32m1(_sum4, val4, _w0, vl); _sum5 = vfmacc_vf_f32m1(_sum5, val5, _w0, vl); _sum6 = vfmacc_vf_f32m1(_sum6, val6, _w0, vl); _sum7 = vfmacc_vf_f32m1(_sum7, val7, _w0, vl); kptr0 += packn; } #if RVV_SPEC_0_7 vsse32_v_f32m1(outptr0, top_blob.cstep * sizeof(float), _sum0, vl); vsse32_v_f32m1(outptr0 + 1, top_blob.cstep * sizeof(float), _sum1, vl); vsse32_v_f32m1(outptr0 + 2, top_blob.cstep * sizeof(float), _sum2, vl); vsse32_v_f32m1(outptr0 + 3, top_blob.cstep * sizeof(float), _sum3, vl); vsse32_v_f32m1(outptr0 + 4, top_blob.cstep * sizeof(float), _sum4, vl); vsse32_v_f32m1(outptr0 + 5, top_blob.cstep * sizeof(float), _sum5, vl); vsse32_v_f32m1(outptr0 + 6, top_blob.cstep * sizeof(float), _sum6, vl); vsse32_v_f32m1(outptr0 + 7, top_blob.cstep * sizeof(float), _sum7, vl); #else vssseg8e32_v_f32m1x8(outptr0, top_blob.cstep * sizeof(float), vcreate_f32m1x8(_sum0, _sum1, _sum2, _sum3, _sum4, _sum5, _sum6, _sum7), vl); #endif outptr0 += 8; } for (; i + 3 < size; i += 4) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); const float* kptr0 = kernel.channel(p / packn); int nn = inch * maxk * packn; // inch always > 0 vfloat32m1_t _sum0 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum1 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum2 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum3 = vle32_v_f32m1(biasptr, vl); for (int j = 0; j < nn; j++) { float val0 = *tmpptr++; float val1 = *tmpptr++; float val2 = *tmpptr++; float val3 = *tmpptr++; vfloat32m1_t _w0 = vle32_v_f32m1(kptr0, vl); _sum0 = vfmacc_vf_f32m1(_sum0, val0, _w0, vl); _sum1 = vfmacc_vf_f32m1(_sum1, val1, _w0, vl); _sum2 = vfmacc_vf_f32m1(_sum2, val2, _w0, vl); _sum3 = vfmacc_vf_f32m1(_sum3, val3, _w0, vl); kptr0 += packn; } #if RVV_SPEC_0_7 vsse32_v_f32m1(outptr0, top_blob.cstep * sizeof(float), _sum0, vl); vsse32_v_f32m1(outptr0 + 1, top_blob.cstep * sizeof(float), _sum1, vl); vsse32_v_f32m1(outptr0 + 2, top_blob.cstep * sizeof(float), _sum2, vl); vsse32_v_f32m1(outptr0 + 3, top_blob.cstep * sizeof(float), _sum3, vl); #else vssseg4e32_v_f32m1x4(outptr0, top_blob.cstep * sizeof(float), vcreate_f32m1x4(_sum0, _sum1, _sum2, _sum3), vl); #endif outptr0 += 4; } for (; i + 1 < size; i += 2) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2); const float* kptr0 = kernel.channel(p / packn); int nn = inch * maxk * packn; // inch always > 0 vfloat32m1_t _sum0 = vle32_v_f32m1(biasptr, vl); vfloat32m1_t _sum1 = vle32_v_f32m1(biasptr, vl); for (int j = 0; j < nn; j++) { float val0 = *tmpptr++; float val1 = *tmpptr++; vfloat32m1_t _w0 = vle32_v_f32m1(kptr0, vl); _sum0 = vfmacc_vf_f32m1(_sum0, val0, _w0, vl); _sum1 = vfmacc_vf_f32m1(_sum1, val1, _w0, vl); kptr0 += packn; } #if RVV_SPEC_0_7 vsse32_v_f32m1(outptr0, top_blob.cstep * sizeof(float), _sum0, vl); vsse32_v_f32m1(outptr0 + 1, top_blob.cstep * sizeof(float), _sum1, vl); #else vssseg2e32_v_f32m1x2(outptr0, top_blob.cstep * sizeof(float), vcreate_f32m1x2(_sum0, _sum1), vl); #endif outptr0 += 2; } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2); const float* kptr0 = kernel.channel(p / packn); int nn = inch * maxk * packn; // inch always > 0 vfloat32m1_t _sum = vle32_v_f32m1(biasptr, vl); for (int j = 0; j < nn; j++) { float val = *tmpptr++; vfloat32m1_t _w0 = vle32_v_f32m1(kptr0, vl); _sum = vfmacc_vf_f32m1(_sum, val, _w0, vl); kptr0 += packn; } vsse32_v_f32m1(outptr0, top_blob.cstep * sizeof(float), _sum, vl); outptr0 += 1; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* outptr0 = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; int i = 0; for (; i + 7 < size; i += 8) { const float* tmpptr = tmp.channel(i / 8); const float* kptr0 = kernel.channel(p / packn + p % packn); int nn = inch * maxk; // inch always > 0 float sum0 = bias0; float sum1 = bias0; float sum2 = bias0; float sum3 = bias0; float sum4 = bias0; float sum5 = bias0; float sum6 = bias0; float sum7 = bias0; vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum1 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum2 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum3 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum4 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum5 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum6 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum7 = vfmv_v_f_f32m1(0.f, vl); for (int j = 0; j < nn; j++) { vfloat32m1x8_t _val01 = vlseg8e32_v_f32m1x8(tmpptr, vl); vfloat32m1_t _w0 = vle32_v_f32m1(kptr0, vl); _sum0 = vfmacc_vv_f32m1(_sum0, vget_f32m1x8_f32m1(_val01, 0), _w0, vl); _sum1 = vfmacc_vv_f32m1(_sum1, vget_f32m1x8_f32m1(_val01, 1), _w0, vl); _sum2 = vfmacc_vv_f32m1(_sum2, vget_f32m1x8_f32m1(_val01, 2), _w0, vl); _sum3 = vfmacc_vv_f32m1(_sum3, vget_f32m1x8_f32m1(_val01, 3), _w0, vl); _sum4 = vfmacc_vv_f32m1(_sum4, vget_f32m1x8_f32m1(_val01, 4), _w0, vl); _sum5 = vfmacc_vv_f32m1(_sum5, vget_f32m1x8_f32m1(_val01, 5), _w0, vl); _sum6 = vfmacc_vv_f32m1(_sum6, vget_f32m1x8_f32m1(_val01, 6), _w0, vl); _sum7 = vfmacc_vv_f32m1(_sum7, vget_f32m1x8_f32m1(_val01, 7), _w0, vl); tmpptr += packn * 8; kptr0 += packn; } #ifdef RVV_SPEC_0_7 // TODO std::vector<float> ss0(packn); std::vector<float> ss1(packn); std::vector<float> ss2(packn); std::vector<float> ss3(packn); std::vector<float> ss4(packn); std::vector<float> ss5(packn); std::vector<float> ss6(packn); std::vector<float> ss7(packn); vse32_v_f32m1((float*)ss0.data(), _sum0, vl); vse32_v_f32m1((float*)ss1.data(), _sum1, vl); vse32_v_f32m1((float*)ss2.data(), _sum2, vl); vse32_v_f32m1((float*)ss3.data(), _sum3, vl); vse32_v_f32m1((float*)ss4.data(), _sum4, vl); vse32_v_f32m1((float*)ss5.data(), _sum5, vl); vse32_v_f32m1((float*)ss6.data(), _sum6, vl); vse32_v_f32m1((float*)ss7.data(), _sum7, vl); for (int i = 0; i < packn; i++) { sum0 += ss0[i]; sum1 += ss1[i]; sum2 += ss2[i]; sum3 += ss3[i]; sum4 += ss4[i]; sum5 += ss5[i]; sum6 += ss6[i]; sum7 += ss7[i]; } #else sum0 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum0, vfmv_s_f_f32m1(vfloat32m1_t(), sum0, vl), vl)); sum1 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum1, vfmv_s_f_f32m1(vfloat32m1_t(), sum1, vl), vl)); sum2 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum2, vfmv_s_f_f32m1(vfloat32m1_t(), sum2, vl), vl)); sum3 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum3, vfmv_s_f_f32m1(vfloat32m1_t(), sum3, vl), vl)); sum4 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum4, vfmv_s_f_f32m1(vfloat32m1_t(), sum4, vl), vl)); sum5 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum5, vfmv_s_f_f32m1(vfloat32m1_t(), sum5, vl), vl)); sum6 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum6, vfmv_s_f_f32m1(vfloat32m1_t(), sum6, vl), vl)); sum7 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum7, vfmv_s_f_f32m1(vfloat32m1_t(), sum7, vl), vl)); #endif outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0[4] = sum4; outptr0[5] = sum5; outptr0[6] = sum6; outptr0[7] = sum7; outptr0 += 8; } for (; i + 3 < size; i += 4) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); const float* kptr0 = kernel.channel(p / packn + p % packn); int nn = inch * maxk; // inch always > 0 float sum0 = bias0; float sum1 = bias0; float sum2 = bias0; float sum3 = bias0; vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum1 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum2 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum3 = vfmv_v_f_f32m1(0.f, vl); for (int j = 0; j < nn; j++) { vfloat32m1x4_t _val01 = vlseg4e32_v_f32m1x4(tmpptr, vl); vfloat32m1_t _w0 = vle32_v_f32m1(kptr0, vl); _sum0 = vfmacc_vv_f32m1(_sum0, vget_f32m1x4_f32m1(_val01, 0), _w0, vl); _sum1 = vfmacc_vv_f32m1(_sum1, vget_f32m1x4_f32m1(_val01, 1), _w0, vl); _sum2 = vfmacc_vv_f32m1(_sum2, vget_f32m1x4_f32m1(_val01, 2), _w0, vl); _sum3 = vfmacc_vv_f32m1(_sum3, vget_f32m1x4_f32m1(_val01, 3), _w0, vl); tmpptr += packn * 4; kptr0 += packn; } #ifdef RVV_SPEC_0_7 // TODO std::vector<float> ss0(packn); std::vector<float> ss1(packn); std::vector<float> ss2(packn); std::vector<float> ss3(packn); vse32_v_f32m1((float*)ss0.data(), _sum0, vl); vse32_v_f32m1((float*)ss1.data(), _sum1, vl); vse32_v_f32m1((float*)ss2.data(), _sum2, vl); vse32_v_f32m1((float*)ss3.data(), _sum3, vl); for (int i = 0; i < packn; i++) { sum0 += ss0[i]; sum1 += ss1[i]; sum2 += ss2[i]; sum3 += ss3[i]; } #else sum0 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum0, vfmv_s_f_f32m1(vfloat32m1_t(), sum0, vl), vl)); sum1 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum1, vfmv_s_f_f32m1(vfloat32m1_t(), sum1, vl), vl)); sum2 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum2, vfmv_s_f_f32m1(vfloat32m1_t(), sum2, vl), vl)); sum3 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum3, vfmv_s_f_f32m1(vfloat32m1_t(), sum3, vl), vl)); #endif outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0 += 4; } for (; i + 1 < size; i += 2) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2); const float* kptr0 = kernel.channel(p / packn + p % packn); int nn = inch * maxk; // inch always > 0 float sum0 = bias0; float sum1 = bias0; vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum1 = vfmv_v_f_f32m1(0.f, vl); for (int j = 0; j < nn; j++) { vfloat32m1x2_t _val01 = vlseg2e32_v_f32m1x2(tmpptr, vl); vfloat32m1_t _w0 = vle32_v_f32m1(kptr0, vl); _sum0 = vfmacc_vv_f32m1(_sum0, vget_f32m1x2_f32m1(_val01, 0), _w0, vl); _sum1 = vfmacc_vv_f32m1(_sum1, vget_f32m1x2_f32m1(_val01, 1), _w0, vl); tmpptr += packn * 2; kptr0 += packn; } #ifdef RVV_SPEC_0_7 // TODO std::vector<float> ss0(packn); std::vector<float> ss1(packn); vse32_v_f32m1((float*)ss0.data(), _sum0, vl); vse32_v_f32m1((float*)ss1.data(), _sum1, vl); for (int i = 0; i < packn; i++) { sum0 += ss0[i]; sum1 += ss1[i]; } #else sum0 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum0, vfmv_s_f_f32m1(vfloat32m1_t(), sum0, vl), vl)); sum1 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum1, vfmv_s_f_f32m1(vfloat32m1_t(), sum1, vl), vl)); #endif outptr0[0] = sum0; outptr0[1] = sum1; outptr0 += 2; } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2); const float* kptr0 = kernel.channel(p / packn + p % packn); int nn = inch * maxk; // inch always > 0 float sum0 = bias0; vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); for (int j = 0; j < nn; j++) { vfloat32m1_t _val0 = vle32_v_f32m1(tmpptr, vl); vfloat32m1_t _w0 = vle32_v_f32m1(kptr0, vl); _sum0 = vfmacc_vv_f32m1(_sum0, _val0, _w0, vl); tmpptr += packn; kptr0 += packn; } #ifdef RVV_SPEC_0_7 // TODO std::vector<float> ss0(packn); vse32_v_f32m1((float*)ss0.data(), _sum0, vl); for (int i = 0; i < packn; i++) { sum0 += ss0[i]; } #else sum0 = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m1_f32m1(vfloat32m1_t(), _sum0, vfmv_s_f_f32m1(vfloat32m1_t(), sum0, vl), vl)); #endif outptr0[0] = sum0; outptr0 += 1; } } } static void convolution_im2col_sgemm_transform_kernel_packnto1_rvv(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h) { const int packn = csrr_vlenb() / 4; const int maxk = kernel_w * kernel_h; // interleave // src = maxk-inch-outch // dst = pb-pa-maxk-inch/pa-outch/pb Mat kernel = _kernel.reshape(maxk, inch, outch); kernel_tm.create(packn * packn * maxk, inch / packn, outch / packn + outch % packn); int q = 0; for (; q + (packn - 1) < outch; q += packn) { float* g00 = kernel_tm.channel(q / packn); for (int p = 0; p + (packn - 1) < inch; p += packn) { for (int k = 0; k < maxk; k++) { for (int i = 0; i < packn; i++) { for (int j = 0; j < packn; j++) { const float* k00 = kernel.channel(q + j).row(p + i); g00[0] = k00[k]; g00++; } } } } } for (; q < outch; q++) { const Mat k0 = kernel.channel(q); float* g00 = kernel_tm.channel(q / packn + q % packn); for (int p = 0; p + (packn - 1) < inch; p += packn) { for (int k = 0; k < maxk; k++) { for (int j = 0; j < packn; j++) { const float* k00 = k0.row(p + j); g00[0] = k00[k]; g00++; } } } } } static void convolution_im2col_sgemm_packnto1_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { const int packn = csrr_vlenb() / 4; const word_type vl = vsetvl_e32m1(packn); 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, 4u * packn, packn, opt.workspace_allocator); { const int gap = (w * stride_h - outw * stride_w) * packn; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < inch; p++) { const Mat img = bottom_blob.channel(p); float* ptr = bottom_im2col.channel(p); for (int u = 0; u < kernel_h; u++) { for (int v = 0; v < kernel_w; v++) { const float* sptr = img.row(dilation_h * u) + dilation_w * v * packn; for (int i = 0; i < outh; i++) { int j = 0; for (; j < outw; j++) { vfloat32m1_t _val = vle32_v_f32m1(sptr, vl); vse32_v_f32m1(ptr, _val, vl); sptr += stride_w * packn; ptr += packn; } sptr += gap; } } } } } im2col_sgemm_packnto1_rvv(bottom_im2col, top_blob, kernel, _bias, opt); }
core_slacpy.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_zlacpy.c, normal z -> s, Fri Sep 28 17:38:19 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "plasma_internal.h" #include "core_lapack.h" /***************************************************************************//** * * @ingroup core_lacpy * * Copies all or part of a two-dimensional matrix A to another matrix B. * ******************************************************************************* * * @param[in] uplo * - PlasmaGeneral: entire A, * - PlasmaUpper: upper triangle, * - PlasmaLower: lower triangle. * * @param[in] transa * - PlasmaNoTrans: A is not transposed, * - PlasmaTrans: A is transposed, * - PlasmaConjTrans: A is conjugate transposed. * * @param[in] m * The number of rows of the matrices A and B. * m >= 0. * * @param[in] n * The number of columns of the matrices A and B. * n >= 0. * * @param[in] A * The m-by-n matrix to copy. * * @param[in] lda * The leading dimension of the array A. * lda >= max(1,m). * * @param[out] B * The m-by-n copy of the matrix A. * On exit, B = A ONLY in the locations specified by uplo. * * @param[in] ldb * The leading dimension of the array B. * ldb >= max(1,m). * ******************************************************************************/ __attribute__((weak)) void plasma_core_slacpy(plasma_enum_t uplo, plasma_enum_t transa, int m, int n, const float *A, int lda, float *B, int ldb) { if (transa == PlasmaNoTrans) { LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(uplo), m, n, A, lda, B, ldb); } else if (transa == PlasmaTrans) { switch (uplo) { case PlasmaUpper: for (int i = 0; i < imin(m, n); i++) for (int j = i; j < n; j++) B[j + i*ldb] = A[i + j*lda]; break; case PlasmaLower: for (int i = 0; i < m; i++) for (int j = 0; j <= imin(i, n); j++) B[j + i*ldb] = A[i + j*lda]; break; case PlasmaGeneral: for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) B[j + i*ldb] = A[i + j*lda]; break; } } else { switch (uplo) { case PlasmaUpper: for (int i = 0; i < imin(m, n); i++) for (int j = i; j < n; j++) B[j + i*ldb] = (A[i + j*lda]); break; case PlasmaLower: for (int i = 0; i < m; i++) for (int j = 0; j <= imin(i, n); j++) B[j + i*ldb] = (A[i + j*lda]); break; case PlasmaGeneral: for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) B[j + i*ldb] = (A[i + j*lda]); break; } } } /******************************************************************************/ void plasma_core_omp_slacpy(plasma_enum_t uplo, plasma_enum_t transa, int m, int n, const float *A, int lda, float *B, int ldb, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(in:A[0:lda*n]) \ depend(out:B[0:ldb*n]) { if (sequence->status == PlasmaSuccess) plasma_core_slacpy(uplo, transa, m, n, A, lda, B, ldb); } }
PermutationMMD.h
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2012 - 2013 Heiko Strathmann * Written (w) 2014 - 2017 Soumyajit De * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #ifndef PERMUTATION_MMD_H_ #define PERMUTATION_MMD_H_ #include <algorithm> #include <numeric> #include <shogun/lib/SGVector.h> #include <shogun/lib/SGMatrix.h> #include <shogun/mathematics/Math.h> #include <shogun/mathematics/RandomNamespace.h> #include <shogun/statistical_testing/internals/mmd/ComputeMMD.h> namespace shogun { namespace internal { namespace mmd { #ifndef DOXYGEN_SHOULD_SKIP_THIS struct PermutationMMD : ComputeMMD { PermutationMMD() : m_save_inds(false) { } template <class Kernel, class PRNG> SGVector<float32_t> operator()(const Kernel& kernel, PRNG& prng) { ASSERT(m_n_x>0 && m_n_y>0); ASSERT(m_num_null_samples>0); precompute_permutation_inds(prng); const index_t size=m_n_x+m_n_y; SGVector<float32_t> null_samples(m_num_null_samples); #pragma omp parallel for for (auto n=0; n<m_num_null_samples; ++n) { terms_t terms; for (auto j=0; j<size; ++j) { auto inverted_col=m_inverted_permuted_inds(j, n); for (auto i=j; i<size; ++i) { auto inverted_row=m_inverted_permuted_inds(i, n); if (inverted_row>=inverted_col) add_term_lower(terms, kernel(i, j), inverted_row, inverted_col); else add_term_lower(terms, kernel(i, j), inverted_col, inverted_row); } } null_samples[n]=compute(terms); SG_DEBUG("null_samples[{}] = {}!", n, null_samples[n]); } return null_samples; } template <class PRNG> SGMatrix<float32_t> operator()(const KernelManager& kernel_mgr, PRNG& prng) { ASSERT(m_n_x>0 && m_n_y>0); ASSERT(m_num_null_samples>0); precompute_permutation_inds(prng); const index_t size=m_n_x+m_n_y; SGMatrix<float32_t> null_samples(m_num_null_samples, kernel_mgr.num_kernels()); SGVector<float32_t> km(size*(size+1)/2); for (auto k=0; k<kernel_mgr.num_kernels(); ++k) { auto kernel=kernel_mgr.kernel_at(k); terms_t terms; for (auto i=0; i<size; ++i) { for (auto j=i; j<size; ++j) { auto index=i*size-i*(i+1)/2+j; km[index]=kernel->kernel(i, j); } } #pragma omp parallel for for (auto n=0; n<m_num_null_samples; ++n) { terms_t null_terms; for (auto i=0; i<size; ++i) { auto inverted_row=m_inverted_permuted_inds(i, n); auto index_base=i*size-i*(i+1)/2; for (auto j=i; j<size; ++j) { auto index=index_base+j; auto inverted_col=m_inverted_permuted_inds(j, n); if (inverted_row<=inverted_col) add_term_upper(null_terms, km[index], inverted_row, inverted_col); else add_term_upper(null_terms, km[index], inverted_col, inverted_row); } } null_samples(n, k)=compute(null_terms); } } return null_samples; } template <class Kernel, class PRNG> float64_t p_value(const Kernel& kernel, PRNG& prng) { auto statistic=ComputeMMD::operator()(kernel); auto null_samples=operator()(kernel, prng); return compute_p_value(null_samples, statistic); } template <class PRNG> SGVector<float64_t> p_value(const KernelManager& kernel_mgr, PRNG& prng) { ASSERT(m_n_x>0 && m_n_y>0); ASSERT(m_num_null_samples>0); precompute_permutation_inds(prng); const index_t size=m_n_x+m_n_y; SGVector<float32_t> null_samples(m_num_null_samples); SGVector<float64_t> result(kernel_mgr.num_kernels()); SGVector<float32_t> km(size*(size+1)/2); for (auto k=0; k<kernel_mgr.num_kernels(); ++k) { auto kernel=kernel_mgr.kernel_at(k); terms_t terms; for (auto i=0; i<size; ++i) { for (auto j=i; j<size; ++j) { auto index=i*size-i*(i+1)/2+j; km[index]=kernel->kernel(i, j); add_term_upper(terms, km[index], i, j); } } float32_t statistic=compute(terms); SG_DEBUG("Kernel({}): statistic={}", k, statistic); #pragma omp parallel for for (auto n=0; n<m_num_null_samples; ++n) { terms_t null_terms; for (auto i=0; i<size; ++i) { auto inverted_row=m_inverted_permuted_inds(i, n); auto index_base=i*size-i*(i+1)/2; for (auto j=i; j<size; ++j) { auto index=index_base+j; auto inverted_col=m_inverted_permuted_inds(j, n); if (inverted_row<=inverted_col) add_term_upper(null_terms, km[index], inverted_row, inverted_col); else add_term_upper(null_terms, km[index], inverted_col, inverted_row); } } null_samples[n]=compute(null_terms); } result[k]=compute_p_value(null_samples, statistic); SG_DEBUG("Kernel({}): p_value={}", k, result[k]); } return result; } template <class PRNG> inline void precompute_permutation_inds(PRNG& prng) { ASSERT(m_num_null_samples>0); allocate_permutation_inds(); for (auto n=0; n<m_num_null_samples; ++n) { std::iota(m_permuted_inds.data(), m_permuted_inds.data()+m_permuted_inds.size(), 0); random::shuffle(m_permuted_inds, prng); if (m_save_inds) { auto offset=n*m_permuted_inds.size(); std::copy(m_permuted_inds.data(), m_permuted_inds.data()+m_permuted_inds.size(), &m_all_inds.matrix[offset]); } for (index_t i=0; i<m_permuted_inds.size(); ++i) m_inverted_permuted_inds(m_permuted_inds[i], n)=i; } } inline float64_t compute_p_value(SGVector<float32_t>& null_samples, float32_t statistic) const { std::sort(null_samples.data(), null_samples.data()+null_samples.size()); float64_t idx=null_samples.find_position_to_insert(statistic); return 1.0-idx/null_samples.size(); } inline void allocate_permutation_inds() { const index_t size=m_n_x+m_n_y; if (m_permuted_inds.size()!=size) m_permuted_inds=SGVector<index_t>(size); if (m_inverted_permuted_inds.num_cols!=m_num_null_samples || m_inverted_permuted_inds.num_rows!=size) m_inverted_permuted_inds=SGMatrix<index_t>(size, m_num_null_samples); if (m_save_inds && (m_all_inds.num_cols!=m_num_null_samples || m_all_inds.num_rows!=size)) m_all_inds=SGMatrix<index_t>(size, m_num_null_samples); } index_t m_num_null_samples; bool m_save_inds; SGVector<index_t> m_permuted_inds; SGMatrix<index_t> m_inverted_permuted_inds; SGMatrix<index_t> m_all_inds; }; #endif // DOXYGEN_SHOULD_SKIP_THIS } } } #endif // PERMUTATION_MMD_H_
integral.c
#include <math.h> float IntegrateMyFunction(int const n, float const a, float const b) { // Running sum of the integral float I = 0.0f; // Integration interval float const dx = (b-a)/float(n); // Loop through the integration range #pragma omp parallel for for (int i = 0; i < n; i++) { // Midpoint of the integration interval float const x = a + dx*(float(i) + 0.5f); // Function value at the midpoint float const f = 1.0f/sqrtf(x); // Incrementing the running sum #pragma omp atomic I += f; } // Scale according to the integration interval I *= dx; return I; }
Renderer.h
#pragma once #include <iostream> #include <cstdint> #include "Scene.h" #include "File.h" //class RenderTarget //{ //public: // RenderTarget(uint32_t width, uint32_t height) // : width(width) // , height(height) // { // image = new Color[width * height]; // } // // ~RenderTarget() // { // delete[] image; // } // //private: // Color* image; // uint32_t width; // uint32_t height; //}; class Renderer { public: Renderer(int width, int height, int subPixelSampleNum, int superSampleNum) : width(width) , height(height) , subPixelSampleNum(subPixelSampleNum) , superSampleNum(superSampleNum) { } void SetScene(ScenePtr scene) { this->scene = scene; } void Render() { auto camera = scene->GetCamera(); const double aspectRatio = double(width) / double(height); // イメージセンサー // ワールド座標系上にスクリーンを配置 const double screenWidth = camera->GetFocalPlane() * aspectRatio; const double screenHeight = camera->GetFocalPlane(); const Vector3 screenX = camera->GetRightDirection() * screenWidth; const Vector3 screenY = camera->GetUpDirection() * screenHeight; const Vector3 screenCenter = camera->GetPosition() + camera->GetDirection() * camera->GetFocalLength(); Color *image = new Color[width * height]; std::cout << width << "x" << height << " " << subPixelSampleNum * (superSampleNum * superSampleNum) << " spp" << std::endl; #pragma omp parallel for schedule(dynamic, 1) num_threads(8) for (auto y = 0; y < height; ++y) { std::cerr << "Rendering (y = " << y << ") " << (100.0 * y / (height - 1)) << "%" << std::endl; Random random(y + 1); for (auto x = 0; x < width; ++x) { const int image_index = (height - y - 1) * width + x; Color accumlator = Color(); for (auto sy = 0; sy < superSampleNum; ++sy) { for (auto sx = 0; sx < superSampleNum; ++sx) { // 一つのサブピクセルあたり複数回サンプリングする for (int s = 0; s < subPixelSampleNum; s++) { const double ratio = (1.0 / superSampleNum); const double rx = sx * ratio + ratio / 2.0; // (サブピクセル位置) + (サブピクセル中心へのオフセット) const double ry = sy * ratio + ratio / 2.0; // -0.5は中心基準になっているため Vector3 screenPos = screenCenter + (screenX * ((x + rx) / width - 0.5)) + (screenY * ((y + ry) / height - 0.5)); Vector3 rayDir = Normalize(screenPos - camera->GetPosition()); Ray ray = Ray(camera->GetPosition(), rayDir); //Color col = radiance(ray, scene, random, 0); Color col = radiance(ray, random, 0); accumlator += (col / subPixelSampleNum / (superSampleNum * superSampleNum)); } } } image[image_index] += accumlator; } } File::Save(std::string("result"), image, width, height); delete[] image; } private: Color radiance(Ray& ray, Random& rand, uint32_t depth) { HitPoint hitpoint; if (!scene->Intersect(ray, hitpoint)) { auto& iblTexture = scene->GetIblTexture(); if (iblTexture == nullptr) return Color(); double phi = atan2(ray.direction.z, ray.direction.x); //double phi = atan2(ray.direction.x, ray.direction.z); double theta = asin(ray.direction.y); double u = 1.0 - (phi + kPI) / kPI2; double v = (theta + kPI / 2.0) / kPI; return iblTexture->value(u, v, hitpoint.normal); //float t = 0.5 * (-ray.direction.y + 1.0); //return Color(1.0, 1.0, 1.0) * (1.0 - t) + Color(0.5, 0.7, 1.0) * t; //return Color(); } const Vector3 normal = Dot(hitpoint.normal, ray.direction) < 0.0 ? hitpoint.normal : (-hitpoint.normal); // 交差位置の法線(物体からのレイの入出を考慮) HitablePtr hitObject = hitpoint.object; // 色の反射率最大のものを得る。ロシアンルーレットで使う。 // ロシアンルーレットの閾値は任意だが色の反射率等を使うとより良い。 auto& albedo = hitObject->GetMaterial()->albedo->value(hitpoint.u, hitpoint.v, hitpoint.position); double russianRouletteProb = std::max(albedo.x, std::max(albedo.y, albedo.z)); // 反射回数が一定以上になったらロシアンルーレットの確率を急上昇させる。(スタックオーバーフロー対策) if (depth > kDepthLimit) { russianRouletteProb *= pow(0.5, depth - kDepthLimit); } // ロシアンルーレットを実行し追跡を打ち切るかどうかを判断する。 // ただしDepth回の追跡は保障する。 if (depth > kDepth) { if (rand.Next() >= russianRouletteProb) { return hitObject->GetMaterial()->emission; //float t = 0.5 * (-ray.direction.y + 1.0); //return Color(1.0, 1.0, 1.0) * (1.0 - t) + Color(0.5, 0.7, 1.0) * t; } } else { russianRouletteProb = 1.0; } return hitObject->GetMaterial()->GetRadiance(ray, hitpoint, rand, depth, russianRouletteProb, [&](Vector3 dir, Color weight) { Color incomingRadiance = radiance(Ray(hitpoint.position, dir), rand, depth + 1); //Color weight = now_object->material->albedo / russianRouletteProb; return hitObject->GetMaterial()->emission + weight * incomingRadiance; }); //Color incomingRadiance = color(Ray(hitpoint.position, dir), objectList, rand, depth + 1) ; //Color weight = now_object->material->albedo / russianRouletteProb; // レンダリング方程式に対するモンテカルロ積分を考えると、outgoing_radiance = weight * incoming_radiance。 // ここで、weight = (ρ/π) * cosθ / pdf(ω) / R になる。 // ρ/πは完全拡散面のBRDFでρは反射率、cosθはレンダリング方程式におけるコサイン項、pdf(ω)はサンプリング方向についての確率密度関数。 // Rはロシアンルーレットの確率。 // 今、コサイン項に比例した確率密度関数によるサンプリングを行っているため、pdf(ω) = cosθ/π // よって、weight = ρ/ R。 //return now_object->material->emission + weight * incomingRadiance; } private: int width; int height; int subPixelSampleNum; int superSampleNum; ScenePtr scene; };
utils.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) 2015 by Contributors * \file utils.h * \brief Basic utilility functions. */ #ifndef MXNET_COMMON_UTILS_H_ #define MXNET_COMMON_UTILS_H_ #include <dmlc/logging.h> #include <dmlc/omp.h> #include <nnvm/graph.h> #include <nnvm/node.h> #include <mxnet/engine.h> #include <mxnet/ndarray.h> #include <mxnet/op_attr_types.h> #include <mxnet/graph_attr_types.h> #include <nnvm/graph_attr_types.h> #include <memory> #include <vector> #include <type_traits> #include <utility> #include <random> #include <string> #include <thread> #include <algorithm> #include <functional> #include <limits> #include "../operator/mxnet_op.h" #if MXNET_USE_MKLDNN == 1 #include "../operator/nn/mkldnn/mkldnn_base-inl.h" #endif #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) #include <windows.h> #else #include <unistd.h> #endif namespace mxnet { namespace common { #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) inline size_t current_process_id() { return ::GetCurrentProcessId(); } #else inline size_t current_process_id() { return getpid(); } #endif /*! * \brief IndPtr should be non-negative, in non-decreasing order, start with 0 * and end with value equal with size of indices. */ struct csr_indptr_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* indptr, const nnvm::dim_t end, const nnvm::dim_t idx_size) { if (indptr[i+1] < 0 || indptr[i+1] < indptr[i] || (i == 0 && indptr[i] != 0) || (i == end - 1 && indptr[end] != idx_size)) *out = kCSRIndPtrErr; } }; /*! * \brief Indices should be non-negative, less than the number of columns * and in ascending order per row. */ struct csr_idx_check { template<typename DType, typename IType, typename RType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const RType* indptr, const nnvm::dim_t ncols) { for (RType j = indptr[i]; j < indptr[i+1]; j++) { if (idx[j] >= ncols || idx[j] < 0 || (j < indptr[i+1] - 1 && idx[j] >= idx[j+1])) { *out = kCSRIdxErr; break; } } } }; /*! * \brief Indices of RSPNDArray should be non-negative, * less than the size of first dimension and in ascending order */ struct rsp_idx_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const nnvm::dim_t end, const nnvm::dim_t nrows) { if ((i < end && idx[i+1] <= idx[i]) || idx[i] < 0 || idx[i] >= nrows) *out = kRSPIdxErr; } }; template<typename xpu> void CheckFormatWrapper(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check); /*! * \brief Check the validity of CSRNDArray. * \param rctx Execution context. * \param input Input NDArray of CSRStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatCSRImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kCSRStorage) << "CheckFormatCSRImpl is for CSRNDArray"; const mxnet::TShape shape = input.shape(); const mxnet::TShape idx_shape = input.aux_shape(csr::kIdx); const mxnet::TShape indptr_shape = input.aux_shape(csr::kIndPtr); const mxnet::TShape storage_shape = input.storage_shape(); if ((shape.ndim() != 2) || (idx_shape.ndim() != 1 || indptr_shape.ndim() != 1 || storage_shape.ndim() != 1) || (indptr_shape[0] != shape[0] + 1) || (idx_shape[0] != storage_shape[0])) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kCSRShapeErr; }); return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<csr_indptr_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), indptr_shape[0] - 1, idx_shape[0]); // no need to check indices if indices are empty if (idx_shape[0] != 0) { Kernel<csr_idx_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIdx).dptr<IType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), shape[1]); } mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); }); } } /*! * \brief Check the validity of RowSparseNDArray. * \param rctx Execution context. * \param input Input NDArray of RowSparseStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatRSPImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kRowSparseStorage) << "CheckFormatRSPImpl is for RSPNDArray"; const mxnet::TShape idx_shape = input.aux_shape(rowsparse::kIdx); if (idx_shape[0] != input.storage_shape()[0]) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kRSPShapeErr; }); return; } if (idx_shape[0] == 0) { return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<rsp_idx_check, xpu>::Launch(s, idx_shape[0], val_xpu.dptr<DType>(), input.aux_data(rowsparse::kIdx).dptr<IType>(), idx_shape[0] - 1, input.shape()[0]); mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); } } template<typename xpu> void CheckFormatImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { int stype = input.storage_type(); if (stype == kCSRStorage) { CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kRowSparseStorage) { CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kDefaultStorage) { // no-op for default storage } else { LOG(FATAL) << "Unknown storage type " << stype; } } /*! \brief Pick rows specified by user input index array from a row sparse ndarray * and save them in the output sparse ndarray. */ template<typename xpu> void SparseRetainOpForwardRspWrapper(mshadow::Stream<xpu> *s, const NDArray& input_nd, const TBlob& idx_data, const OpReqType req, NDArray* output_nd); /* \brief Casts tensor storage type to the new type. */ template<typename xpu> void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output); /*! \brief returns true if all storage types in `vstorage` are the same as target `stype`. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype) { if (!vstorage.empty()) { for (const auto& i : vstorage) { if (i != stype) return false; } return true; } return false; } /*! \brief returns true if all storage types in `vstorage` are the same as target `stype1` * or `stype2'. Sets boolean if both found. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!vstorage.empty()) { uint8_t has = 0; for (const auto i : vstorage) { if (i == stype1) { has |= 1; } else if (i == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as target `stype`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() != stype) { return false; } } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as targets `stype1` or `stype2`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!ndarrays.empty()) { uint8_t has = 0; for (const auto& nd : ndarrays) { const NDArrayStorageType stype = nd.storage_type(); if (stype == stype1) { has |= 1; } else if (stype == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if storage type of any array in `ndarrays` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() == stype) { return true; } } } return false; } /*! \brief returns true if any storage type `ndstype` in `ndstypes` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<int>& ndstypes, const NDArrayStorageType stype) { if (!ndstypes.empty()) { for (const auto& ndstype : ndstypes) { if (ndstype == stype) { return true; } } } return false; } /*! \brief get string representation of dispatch_mode */ inline std::string dispatch_mode_string(const DispatchMode x) { switch (x) { case DispatchMode::kFCompute: return "fcompute"; case DispatchMode::kFComputeEx: return "fcompute_ex"; case DispatchMode::kFComputeFallback: return "fcompute_fallback"; case DispatchMode::kVariable: return "variable"; case DispatchMode::kUndefined: return "undefined"; } return "unknown"; } /*! \brief get string representation of storage_type */ inline std::string stype_string(const int x) { switch (x) { case kDefaultStorage: return "default"; case kCSRStorage: return "csr"; case kRowSparseStorage: return "row_sparse"; } return "unknown"; } /*! \brief get string representation of device type */ inline std::string dev_type_string(const int dev_type) { switch (dev_type) { case Context::kCPU: return "cpu"; case Context::kGPU: return "gpu"; case Context::kCPUPinned: return "cpu_pinned"; case Context::kCPUShared: return "cpu_shared"; } return "unknown"; } /*! \brief get string representation of the operator stypes */ inline std::string operator_stype_string(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>& in_attrs, const std::vector<int>& out_attrs) { std::ostringstream os; os << "operator = " << attrs.op->name << "\ninput storage types = ["; for (const int attr : in_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "output storage types = ["; for (const int attr : out_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "params = {"; for (auto kv : attrs.dict) { os << "\"" << kv.first << "\" : " << kv.second << ", "; } os << "}\n" << "context.dev_mask = " << dev_type_string(dev_mask); return os.str(); } /*! \brief get string representation of the operator */ inline std::string operator_string(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<NDArray>& inputs, const std::vector<OpReqType>& req, const std::vector<NDArray>& outputs) { std::string result = ""; std::vector<int> in_stypes; std::vector<int> out_stypes; in_stypes.reserve(inputs.size()); out_stypes.reserve(outputs.size()); auto xform = [](const NDArray arr) -> int { return arr.storage_type(); }; std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform); std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform); result += operator_stype_string(attrs, ctx.run_ctx.ctx.dev_mask(), in_stypes, out_stypes); return result; } /*! \brief log message once. Intended for storage fallback warning messages. */ inline void LogOnce(const std::string& message) { typedef dmlc::ThreadLocalStore<std::unordered_set<std::string>> LogStore; auto log_store = LogStore::Get(); if (log_store->find(message) == log_store->end()) { LOG(INFO) << message; log_store->insert(message); } } /*! \brief log storage fallback event */ inline void LogStorageFallback(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>* in_attrs, const std::vector<int>* out_attrs) { static bool log = dmlc::GetEnv("MXNET_STORAGE_FALLBACK_LOG_VERBOSE", true); if (!log) return; const std::string op_str = operator_stype_string(attrs, dev_mask, *in_attrs, *out_attrs); std::ostringstream os; const char* warning = "\nThe operator with default storage type will be dispatched " "for execution. You're seeing this warning message because the operator above is unable " "to process the given ndarrays with specified storage types, context and parameter. " "Temporary dense ndarrays are generated in order to execute the operator. " "This does not affect the correctness of the programme. " "You can set environment variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to " "0 to suppress this warning."; os << "\nStorage type fallback detected:\n" << op_str << warning; LogOnce(os.str()); #if MXNET_USE_MKLDNN == 1 if (!MKLDNNEnvSet()) common::LogOnce("MXNET_MKLDNN_ENABLED flag is off. " "You can re-enable by setting MXNET_MKLDNN_ENABLED=1"); if (GetMKLDNNCacheSize() != -1) common::LogOnce("MXNET_MKLDNN_CACHE_NUM is set." "Should only be set if " "your model has variable input shapes, " "as cache size may grow unbounded"); #endif } // heuristic to dermine number of threads per GPU inline int GetNumThreadsPerGPU() { // This is resource efficient option. return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2); } // heuristic to get number of matching colors. // this decides how much parallelism we can get in each GPU. inline int GetExecNumMatchColor() { // This is resource efficient option. int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1); return std::min(num_match_color, GetNumThreadsPerGPU()); } template<typename T, typename V> V ParallelAccumulate(const T* a, const int n, V start) { V sum = start; #pragma omp parallel for reduction(+:sum) for (int i = 0; i < n; ++i) { sum += a[i]; } return sum; } /*! * \brief * Helper function for ParallelSort. * DO NOT call this function directly. * Use the interface ParallelSort instead. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare& comp) { if (len < grainsize) { std::sort(first, first+len, comp); } else { std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len/2, grainsize, comp); ParallelSortHelper(first+len/2, len - len/2, grainsize, comp); thr.join(); std::inplace_merge(first, first+len/2, first+len, comp); } } /*! * \brief * Sort the elements in the range [first, last) into the ascending order defined by * the comparator comp. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) { const auto num = std::distance(first, last); size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024*16)); ParallelSortHelper(first, num, grainsize, comp); } /*! * \brief * Sort the elements in the range [first, last) into ascending order. * The elements are compared using the default < operator. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) { ParallelSort(first, last, num_threads, std::less<typename std::iterator_traits<RandomIt>::value_type>()); } /*! * \brief Random Engine */ typedef std::mt19937 RANDOM_ENGINE; /*! * \brief Helper functions. */ namespace helper { /*! * \brief Helper for non-array type `T`. */ template <class T> struct UniqueIf { /*! * \brief Type of `T`. */ using SingleObject = std::unique_ptr<T>; }; /*! * \brief Helper for an array of unknown bound `T`. */ template <class T> struct UniqueIf<T[]> { /*! * \brief Type of `T`. */ using UnknownBound = std::unique_ptr<T[]>; }; /*! * \brief Helper for an array of known bound `T`. */ template <class T, size_t kSize> struct UniqueIf<T[kSize]> { /*! * \brief Type of `T`. */ using KnownBound = void; }; } // namespace helper /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs a non-array type `T`. The arguments `args` are passed to the * constructor of `T`. The function does not participate in the overload * resolution if `T` is an array type. */ template <class T, class... Args> typename helper::UniqueIf<T>::SingleObject MakeUnique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param n The size of the array to construct. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs an array of unknown bound `T`. The function does not participate * in the overload resolution unless `T` is an array of unknown bound. */ template <class T> typename helper::UniqueIf<T>::UnknownBound MakeUnique(size_t n) { using U = typename std::remove_extent<T>::type; return std::unique_ptr<T>(new U[n]{}); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * * Constructs an arrays of known bound is disallowed. */ template <class T, class... Args> typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete; template<typename FCompType> FCompType GetFCompute(const nnvm::Op* op, const std::string& name, const Context& ctx) { static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>"); static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>"); if (ctx.dev_mask() == cpu::kDevMask) { return fcompute_cpu.get(op, nullptr); } else if (ctx.dev_mask() == gpu::kDevMask) { return fcompute_gpu.get(op, nullptr); } else { LOG(FATAL) << "Unknown device mask " << ctx.dev_mask(); return nullptr; } } /*! * \brief Return the max integer value representable in the type `T` without loss of precision. */ template <typename T> constexpr size_t MaxIntegerValue() { return std::is_integral<T>::value ? std::numeric_limits<T>::max(): size_t(2) << (std::numeric_limits<T>::digits - 1); } template <> constexpr size_t MaxIntegerValue<mshadow::half::half_t>() { return size_t(2) << 10; } MSHADOW_XINLINE int ilog2ul(size_t a) { int k = 1; while (a >>= 1) ++k; return k; } MSHADOW_XINLINE int ilog2ui(unsigned int a) { int k = 1; while (a >>= 1) ++k; return k; } /*! * \brief Return an NDArray of all zeros. */ inline NDArray InitZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype) { // NDArray with default storage if (stype == kDefaultStorage) { NDArray ret(shape, ctx, false, dtype); ret = 0; return ret; } // NDArray with non-default storage. Storage allocation is always delayed. return NDArray(stype, shape, ctx, true, dtype); } /*! * \brief Helper to add a NDArray of zeros to a std::vector. */ inline void EmplaceBackZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype, std::vector<NDArray> *vec) { // NDArray with default storage if (stype == kDefaultStorage) { vec->emplace_back(shape, ctx, false, dtype); vec->back() = 0; } else { // NDArray with non-default storage. Storage allocation is always delayed. vec->emplace_back(stype, shape, ctx, true, dtype); } } /*! * \brief parallelize copy by OpenMP. */ template<typename DType> inline void ParallelCopy(DType* dst, const DType* src, index_t size) { static index_t copy_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_COPY_SIZE", 200000); if (size >= copy_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] = src[i]; } } else { std::memcpy(dst, src, sizeof(DType) * size); } } /*! * \brief If numpy compatibility is turned off (default), the shapes passed in * by users follow the legacy shape definition: * 1. 0 ndim means the shape is completely unknown. * 2. 0 dim size means the dim size is unknown. * We need to convert those shapes to use the numpy shape definition: * 1. 0 ndim means it's a scalar tensor. * 2. -1 ndim means the shape is unknown. * 3. 0 dim size means no elements in that dimension. * 4. -1 dim size means the dimension's size is unknown. * so that operator's infer shape function can work in backend. * \param shape to be converted. * Note: It is possible that the shape to be converted is already * numpy compatible. For example, when a subgraph operator's infer * shape function is called from the infer shape pass of the whole * graph, its input/output shapes have been converted to numpy * compatible shapes. */ inline void ConvertToNumpyShape(mxnet::TShape* shape) { if (shape->ndim() == 0) { // legacy shape ndim = 0 means unknown *shape = mxnet::TShape(); // unknown shape ndim = -1 } else { for (int j = 0; j < shape->ndim(); ++j) { if ((*shape)[j] == 0) { // legacy shape dim_size = 0 means unknown (*shape)[j] = -1; // unknown dim size = -1 } } } } inline void ConvertToNumpyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToNumpyShape(&(shapes->at(i))); } } /*! * \brief This is function is used to convert shapes returned by * the infer shape functions/pass to the legacy shape definition. */ inline void ConvertToLegacyShape(mxnet::TShape* shape) { if (!mxnet::ndim_is_known(*shape)) { *shape = mxnet::TShape(0, -1); } else { for (int j = 0; j < shape->ndim(); ++j) { if (!mxnet::dim_size_is_known(*shape, j)) { (*shape)[j] = 0; } } } } inline void ConvertToLegacyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToLegacyShape(&(shapes->at(i))); } } /*! * \brief This is function can return the output names of a NodeEntry. */ static inline std::string GetOutputName(const nnvm::NodeEntry& e) { nnvm::Symbol sym; sym.outputs.push_back(e); return sym.ListOutputNames()[0]; } } // namespace common } // namespace mxnet #endif // MXNET_COMMON_UTILS_H_
GB_apply_op.c
//------------------------------------------------------------------------------ // GB_apply_op: typecast and apply a unary or binary operator to an array //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Cx = op (A) // Cx and A->x may be aliased. // This function is CSR/CSC agnostic. For positional ops, A is treated as if // it is in CSC format. The caller has already modified the op if A is in CSR // format. // Template/GB_positional_op_ijp can return GrB_OUT_OF_MEMORY. // Otherwise, this function only returns GrB_SUCCESS. #include "GB_apply.h" #include "GB_binop.h" #include "GB_ek_slice.h" #include "GB_unused.h" #ifndef GBCOMPACT #include "GB_unop__include.h" #include "GB_binop__include.h" #endif GrB_Info GB_apply_op // apply a unary operator, Cx = op (A) ( GB_void *Cx, // output array, of type op->ztype 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,Ax) else binop(Ax,y) const GrB_Matrix A, // input matrix GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (Cx != NULL) ; ASSERT (op1 != NULL || op2 != NULL) ; ASSERT_MATRIX_OK (A, "A input for GB_apply_op", GB0) ; ASSERT (GB_JUMBLED_OK (A)) ; // A can be jumbled //-------------------------------------------------------------------------- // get A //-------------------------------------------------------------------------- const GB_void *Ax = (GB_void *) A->x ; // A->x has type A->type const int8_t *Ab = A->b ; // only if A is bitmap const GrB_Type Atype = A->type ; // type of A->x const int64_t anz = GB_NNZ_HELD (A) ; // size of A->x and Cx //-------------------------------------------------------------------------- // determine the maximum number of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; //-------------------------------------------------------------------------- // apply the operator //-------------------------------------------------------------------------- GB_Opcode opcode = (op1 != NULL) ? op1->opcode : op2->opcode ; if (GB_OPCODE_IS_POSITIONAL (opcode)) { //---------------------------------------------------------------------- // built-in positional unary or binary operator //---------------------------------------------------------------------- bool is64 ; if (op1 != NULL) { ASSERT_UNARYOP_OK (op1, "positional op1 for GB_apply_op", GB0) ; is64 = (op1->ztype == GrB_INT64) ; } else // if (op2 != NULL) { ASSERT_BINARYOP_OK (op2, "positional op2 for GB_apply_op", GB0) ; is64 = (op2->ztype == GrB_INT64) ; } // get A and C const int64_t *GB_RESTRICT Ah = A->h ; const int64_t *GB_RESTRICT Ap = A->p ; const int64_t *GB_RESTRICT Ai = A->i ; int64_t anvec = A->nvec ; int64_t avlen = A->vlen ; int64_t avdim = A->vdim ; //---------------------------------------------------------------------- // determine number of threads to use //---------------------------------------------------------------------- int nthreads = GB_nthreads (anz + anvec, chunk, nthreads_max) ; int ntasks = (nthreads == 1) ? 1 : (32 * nthreads) ; //---------------------------------------------------------------------- // Cx = positional_op (A) //---------------------------------------------------------------------- int64_t offset = GB_positional_offset (opcode) ; // GB_positional_op_ijp allocates a set of tasks, which can possibly // fail if out of memory. if (is64) { int64_t *GB_RESTRICT Cx_int = (int64_t *) Cx ; switch (opcode) { case GB_POSITIONI_opcode : // z = position_i(A(i,j)) == i case GB_POSITIONI1_opcode : // z = position_i1(A(i,j)) == i+1 case GB_FIRSTI_opcode : // z = first_i(A(i,j),y) == i case GB_FIRSTI1_opcode : // z = first_i1(A(i,j),y) == i+1 case GB_SECONDI_opcode : // z = second_i(x,A(i,j)) == i case GB_SECONDI1_opcode : // z = second_i1(x,A(i,j)) == i+1 #define GB_POSITION i + offset #include "GB_positional_op_ip.c" return (GrB_SUCCESS) ; case GB_POSITIONJ_opcode : // z = position_j(A(i,j)) == j case GB_POSITIONJ1_opcode : // z = position_j1(A(i,j)) == j+1 case GB_FIRSTJ_opcode : // z = first_j(A(i,j),y) == j case GB_FIRSTJ1_opcode : // z = first_j1(A(i,j),y) == j+1 case GB_SECONDJ_opcode : // z = second_j(x,A(i,j)) == j case GB_SECONDJ1_opcode : // z = second_j1(x,A(i,j)) == j+1 #define GB_POSITION j + offset #include "GB_positional_op_ijp.c" return (GrB_SUCCESS) ; default: ; } } else { int32_t *GB_RESTRICT Cx_int = (int32_t *) Cx ; switch (opcode) { case GB_POSITIONI_opcode : // z = position_i(A(i,j)) == i case GB_POSITIONI1_opcode : // z = position_i1(A(i,j)) == i+1 case GB_FIRSTI_opcode : // z = first_i(A(i,j),y) == i case GB_FIRSTI1_opcode : // z = first_i1(A(i,j),y) == i+1 case GB_SECONDI_opcode : // z = second_i(x,A(i,j)) == i case GB_SECONDI1_opcode : // z = second_i1(x,A(i,j)) == i+1 #define GB_POSITION (int32_t) (i + offset) #include "GB_positional_op_ip.c" return (GrB_SUCCESS) ; case GB_POSITIONJ_opcode : // z = position_j(A(i,j)) == j case GB_POSITIONJ1_opcode : // z = position_j1(A(i,j)) == j+1 case GB_FIRSTJ_opcode : // z = first_j(A(i,j),y) == j case GB_FIRSTJ1_opcode : // z = first_j1(A(i,j),y) == j+1 case GB_SECONDJ_opcode : // z = second_j(x,A(i,j)) == j case GB_SECONDJ1_opcode : // z = second_j1(x,A(i,j)) == j+1 #define GB_POSITION (int32_t) (j + offset) #include "GB_positional_op_ijp.c" return (GrB_SUCCESS) ; default: ; } } } else if (op1 != NULL) { //---------------------------------------------------------------------- // unary operator //---------------------------------------------------------------------- ASSERT_UNARYOP_OK (op1, "op1 for GB_apply_op", GB0) ; // determine number of threads to use int nthreads = GB_nthreads (anz, chunk, nthreads_max) ; GrB_UnaryOp op = op1 ; #ifndef GBCOMPACT if ((Atype == op->xtype) || (opcode == GB_IDENTITY_opcode) || (opcode == GB_ONE_opcode)) { // The switch factory is used if the op is IDENTITY or ONE, or if // no typecasting is being done. The ONE operator ignores the type // of its input and just produces a 1 of op->ztype == op->xtype. // The IDENTITY operator can do arbitrary typecasting. //------------------------------------------------------------------ // define the worker for the switch factory //------------------------------------------------------------------ #define GB_unop_apply(op,zname,aname) \ GB_unop_apply_ ## op ## zname ## aname #define GB_WORKER(op,zname,ztype,aname,atype) \ { \ if (GB_unop_apply (op,zname,aname) ((ztype *) Cx, \ (const atype *) Ax, Ab, anz, nthreads) \ == GrB_SUCCESS) return (GrB_SUCCESS) ; \ } \ break ; //------------------------------------------------------------------ // launch the switch factory //------------------------------------------------------------------ #include "GB_unop_factory.c" } #endif //---------------------------------------------------------------------- // generic worker: typecast and apply a unary operator //---------------------------------------------------------------------- GB_BURBLE_N (anz, "(generic apply: %s) ", op->name) ; size_t asize = Atype->size ; size_t zsize = op->ztype->size ; size_t xsize = op->xtype->size ; GB_cast_function cast_A_to_X = GB_cast_factory (op->xtype->code, Atype->code) ; GxB_unary_function fop = op->function ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; // xwork = (xtype) Ax [p] GB_void xwork [GB_VLA(xsize)] ; cast_A_to_X (xwork, Ax +(p*asize), asize) ; // Cx [p] = fop (xwork) fop (Cx +(p*zsize), xwork) ; } } else { //---------------------------------------------------------------------- // binary operator //---------------------------------------------------------------------- ASSERT_BINARYOP_OK (op2, "standard op2 for GB_apply_op", GB0) ; ASSERT_SCALAR_OK (scalar, "scalar for GB_apply_op", GB0) ; // determine number of threads to use int nthreads = GB_nthreads (anz, chunk, nthreads_max) ; GB_Type_code xcode, ycode, zcode ; bool op_is_first = (opcode == GB_FIRST_opcode) ; bool op_is_second = (opcode == GB_SECOND_opcode) ; bool op_is_pair = (opcode == GB_PAIR_opcode) ; size_t asize = Atype->size ; size_t ssize = scalar->type->size ; size_t zsize = op2->ztype->size ; size_t xsize = op2->xtype->size ; size_t ysize = op2->ytype->size ; GB_Type_code scode = scalar->type->code ; xcode = op2->xtype->code ; ycode = op2->ytype->code ; // typecast the scalar to the operator input bool ignore_scalar = false ; size_t ssize_cast ; GB_Type_code scode_cast ; if (binop_bind1st) { ssize_cast = xsize ; scode_cast = xcode ; ignore_scalar = op_is_second || op_is_pair ; } else { ssize_cast = ysize ; scode_cast = ycode ; ignore_scalar = op_is_first || op_is_pair ; } GB_void swork [GB_VLA(ssize_cast)] ; GB_void *scalarx = (GB_void *) scalar->x ; if (scode_cast != scode && !ignore_scalar) { // typecast the scalar to the operator input, in swork GB_cast_function cast_s = GB_cast_factory (scode_cast, scode) ; cast_s (swork, scalar->x, ssize) ; scalarx = swork ; } #ifndef GBCOMPACT if (binop_bind1st) { //-------------------------------------------------------------- // z = op(scalar,Ax) //-------------------------------------------------------------- if (GB_binop_builtin ( op2->xtype, ignore_scalar, Atype, op_is_first || op_is_pair, op2, false, &opcode, &xcode, &ycode, &zcode)) { //---------------------------------------------------------- // define the worker for the switch factory //---------------------------------------------------------- #define GB_bind1st(op,xname) GB_bind1st_ ## op ## xname #define GB_BINOP_WORKER(op,xname) \ { \ if (GB_bind1st (op, xname) (Cx, scalarx, Ax, Ab, anz,\ nthreads) == GrB_SUCCESS) return (GrB_SUCCESS) ; \ } \ break ; //---------------------------------------------------------- // launch the switch factory //---------------------------------------------------------- #define GB_NO_SECOND #define GB_NO_PAIR #include "GB_binop_factory.c" } } else { //-------------------------------------------------------------- // z = op(Ax,scalar) //-------------------------------------------------------------- if (GB_binop_builtin ( Atype, op_is_second || op_is_pair, op2->ytype, ignore_scalar, op2, false, &opcode, &xcode, &ycode, &zcode)) { //---------------------------------------------------------- // define the worker for the switch factory //---------------------------------------------------------- #define GB_bind2nd(op,xname) GB_bind2nd_ ## op ## xname #undef GB_BINOP_WORKER #define GB_BINOP_WORKER(op,xname) \ { \ if (GB_bind2nd (op, xname) (Cx, Ax, scalarx, Ab, anz,\ nthreads) == GrB_SUCCESS) return (GrB_SUCCESS) ; \ } \ break ; //---------------------------------------------------------- // launch the switch factory //---------------------------------------------------------- #define GB_NO_FIRST #define GB_NO_PAIR #include "GB_binop_factory.c" } } #endif //---------------------------------------------------------------------- // generic worker: typecast and apply a binary operator //---------------------------------------------------------------------- GB_BURBLE_N (anz, "(generic apply: %s) ", op2->name) ; GB_Type_code acode = Atype->code ; GxB_binary_function fop = op2->function ; if (binop_bind1st) { // Cx = op (scalar,Ax) GB_cast_function cast_A_to_Y = GB_cast_factory (ycode, acode) ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; // ywork = (ytype) Ax [p] GB_void ywork [GB_VLA(ysize)] ; cast_A_to_Y (ywork, Ax +(p*asize), asize) ; // Cx [p] = fop (xwork, ywork) fop (Cx +(p*zsize), scalarx, ywork) ; } } else { // Cx = op (Ax,scalar) GB_cast_function cast_A_to_X = GB_cast_factory (xcode, acode) ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; // xwork = (xtype) Ax [p] GB_void xwork [GB_VLA(xsize)] ; cast_A_to_X (xwork, Ax +(p*asize), asize) ; // Cx [p] = fop (xwork, ywork) fop (Cx +(p*zsize), xwork, scalarx) ; } } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- return (GrB_SUCCESS) ; }
common.h
#ifndef LIGHTGBM_UTILS_COMMON_FUN_H_ #define LIGHTGBM_UTILS_COMMON_FUN_H_ #include <LightGBM/utils/log.h> #include <LightGBM/utils/openmp_wrapper.h> #include <cstdio> #include <string> #include <vector> #include <sstream> #include <cstdint> #include <algorithm> #include <cmath> #include <functional> #include <memory> #include <iterator> #include <type_traits> #include <iomanip> #ifdef _MSC_VER #include "intrin.h" #endif namespace LightGBM { namespace Common { inline static char tolower(char in) { if (in <= 'Z' && in >= 'A') return in - ('Z' - 'z'); return in; } inline static std::string Trim(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of(" \f\n\r\t\v") + 1); str.erase(0, str.find_first_not_of(" \f\n\r\t\v")); return str; } inline static std::string RemoveQuotationSymbol(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of("'\"") + 1); str.erase(0, str.find_first_not_of("'\"")); return str; } inline static bool StartsWith(const std::string& str, const std::string prefix) { if (str.substr(0, prefix.size()) == prefix) { return true; } else { return false; } } inline static std::vector<std::string> Split(const char* c_str, char delimiter) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == delimiter) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> SplitLines(const char* c_str) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == '\n' || str[pos] == '\r') { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } // skip the line endings while (str[pos] == '\n' || str[pos] == '\r') ++pos; // new begin i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> Split(const char* c_str, const char* delimiters) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { bool met_delimiters = false; for (int j = 0; delimiters[j] != '\0'; ++j) { if (str[pos] == delimiters[j]) { met_delimiters = true; break; } } if (met_delimiters) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } template<typename T> inline static const char* Atoi(const char* p, T* out) { int sign; T value; while (*p == ' ') { ++p; } sign = 1; if (*p == '-') { sign = -1; ++p; } else if (*p == '+') { ++p; } for (value = 0; *p >= '0' && *p <= '9'; ++p) { value = value * 10 + (*p - '0'); } *out = static_cast<T>(sign * value); while (*p == ' ') { ++p; } return p; } template<typename T> inline static double Pow(T base, int power) { if (power < 0) { return 1.0 / Pow(base, -power); } else if (power == 0) { return 1; } else if (power % 2 == 0) { return Pow(base*base, power / 2); } else if (power % 3 == 0) { return Pow(base*base*base, power / 3); } else { return base * Pow(base, power - 1); } } inline static const char* Atof(const char* p, double* out) { int frac; double sign, value, scale; *out = NAN; // Skip leading white space, if any. while (*p == ' ') { ++p; } // Get sign, if any. sign = 1.0; if (*p == '-') { sign = -1.0; ++p; } else if (*p == '+') { ++p; } // is a number if ((*p >= '0' && *p <= '9') || *p == '.' || *p == 'e' || *p == 'E') { // Get digits before decimal point or exponent, if any. for (value = 0.0; *p >= '0' && *p <= '9'; ++p) { value = value * 10.0 + (*p - '0'); } // Get digits after decimal point, if any. if (*p == '.') { double right = 0.0; int nn = 0; ++p; while (*p >= '0' && *p <= '9') { right = (*p - '0') + right * 10.0; ++nn; ++p; } value += right / Pow(10.0, nn); } // Handle exponent, if any. frac = 0; scale = 1.0; if ((*p == 'e') || (*p == 'E')) { uint32_t expon; // Get sign of exponent, if any. ++p; if (*p == '-') { frac = 1; ++p; } else if (*p == '+') { ++p; } // Get digits of exponent, if any. for (expon = 0; *p >= '0' && *p <= '9'; ++p) { expon = expon * 10 + (*p - '0'); } if (expon > 308) expon = 308; // Calculate scaling factor. while (expon >= 50) { scale *= 1E50; expon -= 50; } while (expon >= 8) { scale *= 1E8; expon -= 8; } while (expon > 0) { scale *= 10.0; expon -= 1; } } // Return signed and scaled floating point result. *out = sign * (frac ? (value / scale) : (value * scale)); } else { size_t cnt = 0; while (*(p + cnt) != '\0' && *(p + cnt) != ' ' && *(p + cnt) != '\t' && *(p + cnt) != ',' && *(p + cnt) != '\n' && *(p + cnt) != '\r' && *(p + cnt) != ':') { ++cnt; } if (cnt > 0) { std::string tmp_str(p, cnt); std::transform(tmp_str.begin(), tmp_str.end(), tmp_str.begin(), Common::tolower); if (tmp_str == std::string("na") || tmp_str == std::string("nan") || tmp_str == std::string("null")) { *out = NAN; } else if (tmp_str == std::string("inf") || tmp_str == std::string("infinity")) { *out = sign * 1e308; } else { Log::Fatal("Unknown token %s in data file", tmp_str.c_str()); } p += cnt; } } while (*p == ' ') { ++p; } return p; } inline static bool AtoiAndCheck(const char* p, int* out) { const char* after = Atoi(p, out); if (*after != '\0') { return false; } return true; } inline static bool AtofAndCheck(const char* p, double* out) { const char* after = Atof(p, out); if (*after != '\0') { return false; } return true; } inline static unsigned CountDecimalDigit32(uint32_t n) { #if defined(_MSC_VER) || defined(__GNUC__) static const uint32_t powers_of_10[] = { 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; #ifdef _MSC_VER unsigned long i = 0; _BitScanReverse(&i, n | 1); uint32_t t = (i + 1) * 1233 >> 12; #elif __GNUC__ uint32_t t = (32 - __builtin_clz(n | 1)) * 1233 >> 12; #endif return t - (n < powers_of_10[t]) + 1; #else if (n < 10) return 1; if (n < 100) return 2; if (n < 1000) return 3; if (n < 10000) return 4; if (n < 100000) return 5; if (n < 1000000) return 6; if (n < 10000000) return 7; if (n < 100000000) return 8; if (n < 1000000000) return 9; return 10; #endif } inline static void Uint32ToStr(uint32_t value, char* buffer) { const char kDigitsLut[200] = { '0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9', '1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9', '2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9', '3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9', '4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9', '5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9', '6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9', '7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9', '8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9', '9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9' }; unsigned digit = CountDecimalDigit32(value); buffer += digit; *buffer = '\0'; while (value >= 100) { const unsigned i = (value % 100) << 1; value /= 100; *--buffer = kDigitsLut[i + 1]; *--buffer = kDigitsLut[i]; } if (value < 10) { *--buffer = char(value) + '0'; } else { const unsigned i = value << 1; *--buffer = kDigitsLut[i + 1]; *--buffer = kDigitsLut[i]; } } inline static void Int32ToStr(int32_t value, char* buffer) { uint32_t u = static_cast<uint32_t>(value); if (value < 0) { *buffer++ = '-'; u = ~u + 1; } Uint32ToStr(u, buffer); } inline static void DoubleToStr(double value, char* buffer, size_t #ifdef _MSC_VER buffer_len #endif ) { #ifdef _MSC_VER sprintf_s(buffer, buffer_len, "%.17g", value); #else sprintf(buffer, "%.17g", value); #endif } inline static const char* SkipSpaceAndTab(const char* p) { while (*p == ' ' || *p == '\t') { ++p; } return p; } inline static const char* SkipReturn(const char* p) { while (*p == '\n' || *p == '\r' || *p == ' ') { ++p; } return p; } template<typename T, typename T2> inline static std::vector<T2> ArrayCast(const std::vector<T>& arr) { std::vector<T2> ret(arr.size()); for (size_t i = 0; i < arr.size(); ++i) { ret[i] = static_cast<T2>(arr[i]); } return ret; } template<typename T, bool is_float, bool is_unsign> struct __TToStringHelperFast { void operator()(T value, char* buffer, size_t ) const { Int32ToStr(value, buffer); } }; template<typename T> struct __TToStringHelperFast<T, true, false> { void operator()(T value, char* buffer, size_t #ifdef _MSC_VER buf_len #endif ) const { #ifdef _MSC_VER sprintf_s(buffer, buf_len, "%g", value); #else sprintf(buffer, "%g", value); #endif } }; template<typename T> struct __TToStringHelperFast<T, false, true> { void operator()(T value, char* buffer, size_t ) const { Uint32ToStr(value, buffer); } }; template<typename T> inline static std::string ArrayToStringFast(const std::vector<T>& arr, size_t n) { if (arr.empty() || n == 0) { return std::string(""); } __TToStringHelperFast<T, std::is_floating_point<T>::value, std::is_unsigned<T>::value> helper; const size_t buf_len = 16; std::vector<char> buffer(buf_len); std::stringstream str_buf; helper(arr[0], buffer.data(), buf_len); str_buf << buffer.data(); for (size_t i = 1; i < std::min(n, arr.size()); ++i) { helper(arr[i], buffer.data(), buf_len); str_buf << ' ' << buffer.data(); } return str_buf.str(); } inline static std::string ArrayToString(const std::vector<double>& arr, size_t n) { if (arr.empty() || n == 0) { return std::string(""); } const size_t buf_len = 32; std::vector<char> buffer(buf_len); std::stringstream str_buf; DoubleToStr(arr[0], buffer.data(), buf_len); str_buf << buffer.data(); for (size_t i = 1; i < std::min(n, arr.size()); ++i) { DoubleToStr(arr[i], buffer.data(), buf_len); str_buf << ' ' << buffer.data(); } return str_buf.str(); } template<typename T, bool is_float> struct __StringToTHelper { T operator()(const std::string& str) const { T ret = 0; Atoi(str.c_str(), &ret); return ret; } }; template<typename T> struct __StringToTHelper<T, true> { T operator()(const std::string& str) const { return static_cast<T>(std::stod(str)); } }; template<typename T> inline static std::vector<T> StringToArray(const std::string& str, char delimiter) { std::vector<std::string> strs = Split(str.c_str(), delimiter); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (auto strs_it = strs.begin(); strs_it != strs.end(); ++strs_it) { const auto& s = *strs_it; ret.push_back(helper(s)); } return ret; } template<typename T> inline static std::vector<T> StringToArray(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } std::vector<std::string> strs = Split(str.c_str(), ' '); CHECK(strs.size() == static_cast<size_t>(n)); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (auto strs_it = strs.begin(); strs_it != strs.end(); ++strs_it) { const auto& s = *strs_it; ret.push_back(helper(s)); } return ret; } template<typename T, bool is_float> struct __StringToTHelperFast { const char* operator()(const char*p, T* out) const { return Atoi(p, out); } }; template<typename T> struct __StringToTHelperFast<T, true> { const char* operator()(const char*p, T* out) const { double tmp = 0.0f; auto ret = Atof(p, &tmp); *out= static_cast<T>(tmp); return ret; } }; template<typename T> inline static std::vector<T> StringToArrayFast(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } auto p_str = str.c_str(); __StringToTHelperFast<T, std::is_floating_point<T>::value> helper; std::vector<T> ret(n); for (int i = 0; i < n; ++i) { p_str = helper(p_str, &ret[i]); } return ret; } template<typename T> inline static std::string Join(const std::vector<T>& strs, const char* delimiter) { if (strs.empty()) { return std::string(""); } std::stringstream str_buf; str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[0]; for (size_t i = 1; i < strs.size(); ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } template<typename T> inline static std::string Join(const std::vector<T>& strs, size_t start, size_t end, const char* delimiter) { if (end - start <= 0) { return std::string(""); } start = std::min(start, static_cast<size_t>(strs.size()) - 1); end = std::min(end, static_cast<size_t>(strs.size())); std::stringstream str_buf; str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[start]; for (size_t i = start + 1; i < end; ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } inline static int64_t Pow2RoundUp(int64_t x) { int64_t t = 1; for (int i = 0; i < 64; ++i) { if (t >= x) { return t; } t <<= 1; } return 0; } /*! * \brief Do inplace softmax transformaton on p_rec * \param p_rec The input/output vector of the values. */ inline static void Softmax(std::vector<double>* p_rec) { std::vector<double> &rec = *p_rec; double wmax = rec[0]; for (size_t i = 1; i < rec.size(); ++i) { wmax = std::max(rec[i], wmax); } double wsum = 0.0f; for (size_t i = 0; i < rec.size(); ++i) { rec[i] = std::exp(rec[i] - wmax); wsum += rec[i]; } for (size_t i = 0; i < rec.size(); ++i) { rec[i] /= static_cast<double>(wsum); } } inline static void Softmax(const double* input, double* output, int len) { double wmax = input[0]; for (int i = 1; i < len; ++i) { wmax = std::max(input[i], wmax); } double wsum = 0.0f; for (int i = 0; i < len; ++i) { output[i] = std::exp(input[i] - wmax); wsum += output[i]; } for (int i = 0; i < len; ++i) { output[i] /= static_cast<double>(wsum); } } template<typename T> std::vector<const T*> ConstPtrInVectorWrapper(const std::vector<std::unique_ptr<T>>& input) { std::vector<const T*> ret; for (size_t i = 0; i < input.size(); ++i) { ret.push_back(input.at(i).get()); } return ret; } template <typename T1, typename T2> bool pair_order_asc(const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first < b.first; } template <typename T1, typename T2> bool pair_order_dsc(const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first > b.first; } template<typename T1, typename T2> inline static void SortForPair(std::vector<T1>& keys, std::vector<T2>& values, size_t start, bool is_reverse = false) { std::vector<std::pair<T1, T2>> arr; for (size_t i = start; i < keys.size(); ++i) { arr.emplace_back(keys[i], values[i]); } if (!is_reverse) { std::sort(arr.begin(), arr.end(), pair_order_asc); } else { std::sort(arr.begin(), arr.end(), pair_order_dsc); } for (size_t i = start; i < arr.size(); ++i) { keys[i] = arr[i].first; values[i] = arr[i].second; } } template <typename T> inline static std::vector<T*> Vector2Ptr(std::vector<std::vector<T>>& data) { std::vector<T*> ptr(data.size()); for (size_t i = 0; i < data.size(); ++i) { ptr[i] = data[i].data(); } return ptr; } template <typename T> inline static std::vector<int> VectorSize(const std::vector<std::vector<T>>& data) { std::vector<int> ret(data.size()); for (size_t i = 0; i < data.size(); ++i) { ret[i] = static_cast<int>(data[i].size()); } return ret; } inline static double AvoidInf(double x) { if (x >= 1e300) { return 1e300; } else if(x <= -1e300) { return -1e300; } else { return x; } } inline static float AvoidInf(float x) { if (x >= 1e38) { return 1e38f; } else if (x <= -1e38) { return -1e38f; } else { return x; } } template<typename _Iter> inline static typename std::iterator_traits<_Iter>::value_type* IteratorValType(_Iter) { return (0); } template<typename _RanIt, typename _Pr, typename _VTRanIt> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred, _VTRanIt*) { size_t len = _Last - _First; const size_t kMinInnerLen = 1024; int num_threads = 1; #pragma omp parallel #pragma omp master { num_threads = omp_get_num_threads(); } if (len <= kMinInnerLen || num_threads <= 1) { std::sort(_First, _Last, _Pred); return; } size_t inner_size = (len + num_threads - 1) / num_threads; inner_size = std::max(inner_size, kMinInnerLen); num_threads = static_cast<int>((len + inner_size - 1) / inner_size); #pragma omp parallel for schedule(static,1) for (int i = 0; i < num_threads; ++i) { size_t left = inner_size*i; size_t right = left + inner_size; right = std::min(right, len); if (right > left) { std::sort(_First + left, _First + right, _Pred); } } // Buffer for merge. std::vector<_VTRanIt> temp_buf(len); _RanIt buf = temp_buf.begin(); size_t s = inner_size; // Recursive merge while (s < len) { int loop_size = static_cast<int>((len + s * 2 - 1) / (s * 2)); #pragma omp parallel for schedule(static,1) for (int i = 0; i < loop_size; ++i) { size_t left = i * 2 * s; size_t mid = left + s; size_t right = mid + s; right = std::min(len, right); if (mid >= right) { continue; } std::copy(_First + left, _First + mid, buf + left); std::merge(buf + left, buf + mid, _First + mid, _First + right, _First + left, _Pred); } s *= 2; } } template<typename _RanIt, typename _Pr> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred) { return ParallelSort(_First, _Last, _Pred, IteratorValType(_First)); } template <typename T> struct fatal_msg_ftor { fatal_msg_ftor(const T *y, T ymin, T ymax, int ny, const char *callername, const int i) : y(y), ymin(ymin), ymax(ymax), ny(ny), callername(callername) {} void operator() (const int i) { std::ostringstream os; os << "[%s]: does not tolerate element [#%i = " << y[i] << "] outside [" << ymin << ", " << ymax << "]"; Log::Fatal(os.str().c_str(), callername, i); } const T *y; const T ymin; const T ymax; const T ny; const char *callername; }; // Check that all y[] are in interval [ymin, ymax] (end points included); throws error if not template <typename T> inline static void CheckElementsIntervalClosed(const T *y, T ymin, T ymax, int ny, const char *callername) { fatal_msg_ftor<T> fatal_msg(y, ymin, ymax, ny, callername); for (int i = 1; i < ny; i += 2) { if (y[i - 1] < y[i]) { if (y[i - 1] < ymin) { fatal_msg(i - 1); } else if (y[i] > ymax) { fatal_msg(i); } } else { if (y[i - 1] > ymax) { fatal_msg(i - 1); } else if (y[i] < ymin) { fatal_msg(i); } } } if (ny & 1) { // odd if (y[ny - 1] < ymin || y[ny - 1] > ymax) { fatal_msg(ny - 1); } } } // One-pass scan over array w with nw elements: find min, max and sum of elements; // this is useful for checking weight requirements. template <typename T1, typename T2> inline static void ObtainMinMaxSum(const T1 *w, int nw, T1 *mi, T1 *ma, T2 *su) { T1 minw; T1 maxw; T1 sumw; int i; if (nw & 1) { // odd minw = w[0]; maxw = w[0]; sumw = w[0]; i = 2; } else { // even if (w[0] < w[1]) { minw = w[0]; maxw = w[1]; } else { minw = w[1]; maxw = w[0]; } sumw = w[0] + w[1]; i = 3; } for (; i < nw; i += 2) { if (w[i - 1] < w[i]) { minw = std::min(minw, w[i - 1]); maxw = std::max(maxw, w[i]); } else { minw = std::min(minw, w[i]); maxw = std::max(maxw, w[i - 1]); } sumw += w[i - 1] + w[i]; } if (mi != nullptr) { *mi = minw; } if (ma != nullptr) { *ma = maxw; } if (su != nullptr) { *su = static_cast<T2>(sumw); } } template<typename T> inline static std::vector<uint32_t> ConstructBitset(const T* vals, int n) { std::vector<uint32_t> ret; for (int i = 0; i < n; ++i) { int i1 = vals[i] / 32; int i2 = vals[i] % 32; if (static_cast<int>(ret.size()) < i1 + 1) { ret.resize(i1 + 1, 0); } ret[i1] |= (1 << i2); } return ret; } template<typename T> inline static bool FindInBitset(const uint32_t* bits, int n, T pos) { int i1 = pos / 32; if (i1 >= n) { return false; } int i2 = pos % 32; return (bits[i1] >> i2) & 1; } inline static bool CheckDoubleEqualOrdered(double a, double b) { double upper = std::nextafter(a, INFINITY); return b <= upper; } inline static double GetDoubleUpperBound(double a) { return std::nextafter(a, INFINITY);; } inline static size_t GetLine(const char* str) { auto start = str; while (*str != '\0' && *str != '\n' && *str != '\r') { ++str; } return str - start; } inline static const char* SkipNewLine(const char* str) { if (*str == '\r') { ++str; } if (*str == '\n') { ++str; } return str; } template <typename T> static int Sign(T x) { return (x > T(0)) - (x < T(0)); } } // namespace Common } // namespace LightGBM #endif // LightGBM_UTILS_COMMON_FUN_H_
zgetri.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_getri * * Computes the inverse of a matrix A using the LU factorization computed * by plasma_zgetrf. * ******************************************************************************* * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in,out] pA * On entry, the LU factors computed by plasma_zgetrf. * On exit, the inverse of A, overwriting the factors. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,n). * * @param[in] ipiv * The pivot indices computed by plasma_zgetrf. * ******************************************************************************* * * @retval PLASMA_SUCCESS successful exit * @retval < 0 if -i, the i-th argument had an illegal value * @retval > 0 if i, the (i,i) element of the factor U or L is * zero, and the inverse could not be computed. * ******************************************************************************* * * @sa plasma_cgetri * @sa plasma_dgetri * @sa plasma_sgetri * ******************************************************************************/ int plasma_zgetri(int n, plasma_complex64_t *pA, int lda, int *ipiv) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if (n < 0) { plasma_error("illegal value of n"); return -1; } if (lda < imax(1, n)) { plasma_error("illegal value of lda"); return -3; } // quick return if (imax(n, 0) == 0) return PlasmaSuccess; // Set tiling parameters. int nb = plasma->nb; // Create tile matrix. plasma_desc_t A; plasma_desc_t W; int retval; retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, n, n, 0, 0, n, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, n, nb, 0, 0, n, nb, &W); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } // Create sequence. plasma_sequence_t *sequence = NULL; retval = plasma_sequence_create(&sequence); if (retval != PlasmaSuccess) { plasma_error("plasma_sequence_create() failed"); return retval; } // Initialize request. plasma_request_t request = PlasmaRequestInitializer; // Asynchronous block. #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zge2desc(pA, lda, A, sequence, &request); // Perform computation. plasma_omp_zgetri(A, ipiv, W, sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2ge(A, pA, lda, sequence, &request); } // Implicit synchronization. // Free matrices in tile layout. plasma_desc_destroy(&W); plasma_desc_destroy(&A); // Return status. int status = sequence->status; plasma_sequence_destroy(sequence); return status; } /***************************************************************************//** * * Computes the inverse of a matrix A using the LU factorization. * Non-blocking tile version of plasma_zgbsv(). * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] A * On entry, the LU factors computed by plasma_zgetrf. * On exit, the inverse of A, overwriting the factors. * * @param[in] ipiv * The pivot indices computed by plasma_zgetrf. * * @param[out] W * Workspace of dimension (n, nb) * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_zgetri * @sa plasma_omp_zgetri * @sa plasma_omp_cgetri * @sa plasma_omp_dgetri * @sa plasma_omp_sgetri * ******************************************************************************/ void plasma_omp_zgetri(plasma_desc_t A, int *ipiv, plasma_desc_t W, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(W) != PlasmaSuccess) { plasma_error("invalid W"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Quick return if (A.n == 0) return; // Invert triangular part. plasma_pztrtri(PlasmaUpper, PlasmaNonUnit, A, sequence, request); // Compute product of inverse of the upper and lower triangles. plasma_pzgetri_aux(A, W, sequence, request); // Apply pivot. #pragma omp taskwait plasma_pzgeswp(PlasmaColumnwise, A, ipiv, -1, sequence, request); }
LAGraph_bfs_pushpull.c
//------------------------------------------------------------------------------ // LAGraph_bfs_pushpull: push-pull breadth-first search //------------------------------------------------------------------------------ /* LAGraph: graph algorithms based on GraphBLAS Copyright 2020 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. */ #include "LAGraph_bfs_pushpull.h" #include "../config.h" //------------------------------------------------------------------------------ // LAGraph_bfs_pushpull: direction-optimized push/pull breadth first search, // contributed by Tim Davis, Texas A&M. // LAGraph_bfs_pushpull computes the BFS of a graph from a single given // source node. The result is a vector v where v(i)=k if node i was placed // at level k in the BFS. // Usage: // info = LAGraph_bfs_pushpull (&v, &pi, A, AT, source, max_level, vsparse) ; // GrB_Vector *v: a vector containing the result, created on output. // v(i) = k is the BFS level of node i in the graph, where a source // node has v(source)=1. v(i) is implicitly zero if it is unreachable // from the source node. That is, GrB_Vector_nvals (&nreach,v) is the // size of the reachable set of the source node, for a single-source // BFS. v may be returned as sparse, or full. If full, v(i)=0 // indicates that node i was not reached. If sparse, the pattern of v // indicates the set of nodes reached. // GrB_Vector *pi: a vector containing the BFS tree, in 1-based indexing. // pi(source) = source+1 for source node. pi(i) = p+1 if p is the // parent of i. If pi is sparse, and pi(i) is not present, then node // i has not been reached. Otherwise, if pi is full, then pi(i)=0 // indicates that node i was not reached. // GrB_Matrix A: a square matrix of any type. The values of A are not // accessed. The presence of the entry A(i,j) indicates the edge // (i,j). That is, an explicit entry A(i,j)=0 is treated as an edge. // GrB_Matrix AT: an optional matrix of any type. If NULL, the algorithm // is a conventional push-only BFS. If not NULL, AT must be the // transpose of A, and a push-pull algorithm is used (NOTE: this // assumes GraphBLAS stores its matrix in CSR form; see discussion // below). Results are undefined if AT is not NULL but not identical // to the transpose of A. // int64_t source: the source node for the BFS. // int64_t max_level: An optional limit on the levels searched for the // single-source BFS. If zero, then no limit is enforced. If > 0, // then only nodes with v(i) <= max_level will be visited. That is: // 1: just the source node, 2: the source and its neighbors, 3: the // source node, its neighbors, and their neighbors, etc. // bool vsparse: if the result v may remain very sparse, then set this // parameter to true. If v might have many entries, set it false. If // you are unsure, then set it to true. This parameter speeds up // the handling of v. If you guess wrong, there is a slight // performance penalty. The results are not affected by this // parameter, just the performance. This parameter is used only for // the single-source BFS. // single-source BFS: // Given a graph A, a source node, find all nodes reachable from the // source node. v(source)=1, v(i)=2 if edge (source,i) appears in the // graph, and so on. If node i is not reachable from source, then // implicitly v(i)=0. v is returned as a sparse vector, and v(i) is not // an entry in this vector. // This algorithm can use the push-pull strategy, which requires both A and // AT=A' to be passed in. If the graph is known to be symmetric, then the same // matrix A can be passed in for both arguments. Results are undefined if AT // is not the transpose of A. // If only A or AT is passed in, then only single strategy will be used: push // or pull, but not both. In general, push-only performs well. A pull-only // strategy is possible but it is exceedingly slow. Assuming A and AT are both // in CSR format, then (let s = source node): // LAGraph_bfs_pushpull (..., A, AT, s, ...) ; // push-pull (fastest) // LAGraph_bfs_pushpull (..., A, NULL, s, ...) ; // push-only (good) // LAGraph_bfs_pushpull (..., NULL, AT, s, ...) ; // pull-only (slow!) // If A and AT are both in CSC format, then: // LAGraph_bfs_pushpull (..., A, AT, s, ...) ; // push-pull (fastest) // LAGraph_bfs_pushpull (..., NULL, AT, s, ...) ; // push-only (good) // LAGraph_bfs_pushpull (..., A, NULL, s, ...) ; // pull-only (slow!) // Since the pull-only method is exceedingly slow, SuiteSparse:GraphBLAS // detects this case and refuses to do it. // The basic step of this algorithm computes A'*q where q is the 'queue' of // nodes in the current level. This can be done with GrB_vxm(q,A) = (q'*A)' = // A'*q, or by GrB_mxv(AT,q) = AT*q = A'*q. Both steps compute the same thing, // just in a different way. In GraphBLAS, unlike MATLAB, a GrB_Vector is // simultaneously a row and column vector, so q and q' are interchangeable. // To implement an efficient BFS using GraphBLAS, an assumption must be made in // LAGraph about how the matrix is stored, whether by row or by column (or // perhaps some other opaque data structure). The storage format has a huge // impact on the relative performance of vxm(q,A) and mxv(AT,q). // Storing A by row, if A(i,j) is the edge (i,j), means that A(i,:) is easily // accessible. In terms of the graph A, this means that the out-adjacency // list of node i can be traversed in time O(out-degree of node i). // If AT is stored by row, then AT(i,:) is the in-adjacency list of node i, // and traversing row i of AT can be done in O(in-degree of node i) time. // The CSR (Compressed Sparse Row) format is the default for // SuiteSparse:GraphBLAS, but no assumption can be made about any particular // GraphBLAS library implementation. // If A and AT are both stored by column instead, then A(i,:) is not easy to // access. Instead, A(:,i) is the easily-accessible in-adjacency of node i, // and AT(:,i) is the out-adjancency. // A push step requires the out-adjacencies of each node, where as // a pull step requires the in-adjacencies of each node. // vxm(q,A) = A'*q, with A stored by row: a push step // mxv(AT,q) = A'*q, with AT stored by row: a pull step // vxm(q,A) = A'*q, with A stored by col: a pull step // mxv(AT,q) = A'*q, with AT stored by col: a push step // The GraphBLAS data structure is opaque. An implementation may decide to // store the matrix A in both formats, internally, so that it easily traverse // both in- and out-adjacencies of each node (equivalently, A(i,:) and A(:,i) // can both be easily traversed). This would make a push-pull BFS easy to // implement using just the opaque GrB_Matrix A, but it doubles the storage. // Deciding which format to use automatically is not a simple task, // particularly since the decision must work well throughout GraphBLAS, not // just for the BFS. // MATLAB stores its sparse matrices in CSC format (Compressed Sparse Column). // As a result, the MATLAB expression x=AT*q is a push step, computed using a // saxpy-based algorithm internally, and x=A'*q is a pull step, computed using // a dot product. // SuiteSparse:GraphBLAS can store a matrix in either format, but this requires // an extension to the GraphBLAS C API (GxB_set (A, GxB_FORMAT, f)). where // f = GxB_BY_ROW (that is, CSR) or GxB_BY_COL (that is, CSC). The library // could be augmented in the future with f = Gxb_BY_BOTH. It currently does // not select the format automatically. As a result, if GxB_set is not used, // all its GrB_Matrix objects are stored by row (CSR). // SuiteSparse:GraphBLAS allows the user to query (via GxB_get) an set (via // GxB_set) the format, whether by row or by column. The hypersparsity of // A is selected automatically, with optional hints from the user application, // but a selection between hypersparsity vs standard CSR and CSC has no effect // on the push vs pull decision made here. // The push/pull and saxpy/dot connection can be described as follows. // Assume for these first two examples that MATLAB stores its matrices in CSR // format, where accessing A(i,:) is fast. // If A is stored by row, then x = vxm(q,A) = q'*A can be written in MATLAB // notation as: /* function x = vxm (q,A) % a push step: compute x = q'*A where q is a column vector x = sparse (1,n) for i = 1:n % a saxpy operation, using the ith row of A and the scalar q(i) x = x + q (i) * A (i,:) end */ // If AT is stored by row, then x = mvx(AT,q) = AT*q = A'*q becomes // a dot product: /* function x = mxv (AT,q) % a pull step: compute x = AT*q where q is a column vector for i = 1:n % a dot-product of the ith row of AT and the column vector q x (i) = AT (i,:) * q end */ // The above snippets describe how SuiteSparse:GraphBLAS computes vxm(q,A) and // mxv(AT,q) by default, where A and AT are stored by row by default. However, // they would be very slow in MATLAB, since it stores its sparse matrices in // CSC format. In that case, if A is stored by column and thus accessing // A(:,j) is efficient, then x = vxm(q,A) = q'*A becomes the dot product // instead. These two snippets assume the matrices are both in CSR for, and // thus make more efficient use of MATLAB: /* function x = vxm (q,A) % a pull step: compute x = q'*A where q is a column vector for j = 1:n % a dot product of the row vector q' and the jth column of A x (j) = q' * A (:,j) end */ // If AT is stored by column, then x = mvx(AT,q) is /* function x = mxv (AT,q) % a push step: compute x = AT*q where q is a column vector for j = 1:n % a saxpy operation, using the jth column of AT and the scalar q(i) x = x + AT (:,j) * q end */ // In MATLAB, if q is a sparse column vector and A is a sparse matrix, then // x=A*q does in fact use a saxpy-based method, internally, and x=A'*q uses a // dot product. You can view the code used internally in MATLAB for its sparse // matrix multiplication in the SuiteSparse/MATLAB_Tools/SSMULT and SFMULT // packages, at http://suitesparse.com. // This raises an interesting puzzle for LAGraph, which is intended on being a // graph library that can be run on any implementation of GraphBLAS. There are // no mechanisms in the GraphBLAS C API for LAGraph (or other external packages // or user applications) to provide hints to GraphBLAS. Likely, there are no // query mechanisms where LAGraph can ask GraphBLAS how its matrices might be // stored (LAGraphs asks, "Is A(i,:) fast? Or A(:,j)? Or both?"; the answer // from GraphBLAS is silence). The GraphBLAS data structure is opaque, and it // does not answer this query. // There are two solutions to this puzzle. The most elegant one is for // GraphBLAS to handle all this internally, and change formats as needed. It // could choose to store A in both CSR and CSC format, or use an entirely // different data structure, and it would make the decision between the push or // pull, at each step of the BFS. This is not a simple task since the API is // complex. Furthermore, the selection of the data structure for A has // implications on all other GraphBLAS operations (submatrix assignment and // extraction, for example). // However, if A were to be stored in both CSR and CSC format, inside the // opaque GraphBLAS GrB_Matrix data structure, then LAGraph_bfs_simple would // become a push-pull BFS. // The second solution is to allow the user application or library such as // LAGraph to provide hints and allow it to query the GraphBLAS library. // There are no such features in the GraphBLAS C API. // SuiteSparse:GraphBLAS takes the second approach: It adds two functions that // are extensions to the API: GxB_set changes the format (CSR or CSC), and // GxB_get can query the format. Even this this simplication, // SuiteSparse:GraphBLAS uses 24 different algorithmic variants inside GrB_mxm // (per semiring), and selects between them automatically. By default, all of // its matrices are stored in CSR format (either sparse or hypersparse, // selected automatically). So if no GxB_* extensions are used, all matrices // are in CSR format. // If a GraphBLAS library other than SuiteSparse:GraphBLAS is in use, this // particular function assumes that its input matrices are in CSR format, or at // least A(i,:) and AT(i,:) can be easily accessed. With this assumption, it // is the responsibilty of this function to select between using a push or a // pull, for each step in the BFS. // The following analysis assumes CSR format, and it assumes that dot-product // (a pull step) can terminate early via a short-circuit rule with the OR // monoid, as soon as it encounters a TRUE value. This cuts the time for the // dot-product. Not all GraphBLAS libraries may use this, but SuiteSparse: // GraphBLAS does (in version 2.3.0 and later). Early termination cannot be // done for the saxpy (push step) method. // The work done by the push method (saxpy) is very predictable. BFS uses a // complemented mask. There is no simple way to exploit a complemented mask, // and saxpy has no early termination rule. If the set of nodes in the current // level is q, the work is nnz(A(q,:)). If d = nnz(A)/n is the average degree, // this becomes d*nq where nq = length (q): // pushwork = d*nq // The work done by the pull (dot product) method is less predictable. It can // exploit the complemented mask, and so it only computes (n-nvisited) dot // products, if nvisited is the # of nodes visited so far (in all levels). // With no early-termination, the dot product will take d * log2 (nq) time, // assuming that q is large and a binary search is used internally. That is, // the dot product will scan through the d entries in A(i,:), and do a binary // search for each entry in q. To account for the higher constant of a binary // search, log2(nq) is replaced with (3*(1+log2(nq))). With early termination, // d is too high. If the nodes are randomly marked, the probability of each // node being marked is nvisited/n. The expected number of trials until // success, for a sequence of events with probabilty p, is 1/p. Thus, the // expected number of iterations in a dot product before an early termination // is 1/p = (n/nvisited+1), where +1 is added to avoid a divide by zero. // However, it cannot exceed d. Thus, the total work for the dot product // (pull) method can be estimated as: // per_dot = min (d, n / (nvisited+1)) // pullwork = (n-nvisited) * per_dot * (3 * (1 + log2 ((double) nq))) // The above expressions are valid for SuiteSparse:GraphBLAS v2.3.0 and later, // and may be reasonable for other GraphBLAS implementations. Push or pull // is selected as the one with the least work. // TODO: change the formula for v3.2.0 // The push/pull decision requires that both A and AT be passed in, but this // function can use just one or the other. If only A is passed in and AT is // NULL, then only vxm(q,A) will be used (a push step if A is CSR, or a pull // step if A is CSC). If only AT is passed in and A is NULL, then only // mxv(AT,q) will be used (a pull step if AT is CSR, or a push step if AT is // CSC). // In general, while a push-pull strategy is the fastest, a push-only BFS will // give good peformance. In particular, the time to compute AT=A' plus the // time for the push-pull BFS is typically higher than just a push-only BFS. // This why this function does not compute AT=A'. To take advantage of the // push-pull method, both A and AT must already be available, with the cost to // construct them amortized across other computations such as this one. // A pull-only strategy will be *exceeding* slow. // The input matrix A must be square. It can be non-binary, but best // performance will be obtained if it is GrB_BOOL. It can have explicit // entries equal to zero. These are safely ignored, and are treated as // non-edges. // SuiteSparse:GraphBLAS can detect the CSR vs CSC format of its inputs. // In this case, if both matrices are provided, they must be in the same // format (both GxB_BY_ROW or both GxB_BY_COL). If the matrices are in CSC // format, vxm(q,A) is the pull step and mxv(AT,q) is the push step. // If only A or AT are provided, and the result is a pull-only algorithm, // an error is returned. // References: // Carl Yang, Aydin Buluc, and John D. Owens. 2018. Implementing Push-Pull // Efficiently in GraphBLAS. In Proceedings of the 47th International // Conference on Parallel Processing (ICPP 2018). ACM, New York, NY, USA, // Article 89, 11 pages. DOI: https://doi.org/10.1145/3225058.3225122 // Scott Beamer, Krste Asanovic and David A. Patterson, // The GAP Benchmark Suite, http://arxiv.org/abs/1508.03619, 2015. // http://gap.cs.berkeley.edu/ #define LAGRAPH_FREE_ALL \ { \ GrB_free (&v) ; \ GrB_free (&t) ; \ GrB_free (&q) ; \ GrB_free (&pi) ; \ } #define LAGRAPH_ERROR(message,info) \ { \ fprintf (stderr, "LAGraph error: %s\n[%d]\nFile: %s Line: %d\n", \ message, info, __FILE__, __LINE__) ; \ LAGRAPH_FREE_ALL ; \ return (info) ; \ } #define LAGRAPH_MAX(x,y) (((x) > (y)) ? (x) : (y)) #define LAGRAPH_MIN(x,y) (((x) < (y)) ? (x) : (y)) GrB_Info LAGraph_bfs_pushpull // push-pull BFS, or push-only if AT = NULL ( GrB_Vector *v_output, // v(i) is the BFS level of node i in the graph GrB_Vector *pi_output, // pi(i) = p+1 if p is the parent of node i. // if NULL, the parent is not computed. GrB_Matrix A, // input graph, treated as if boolean in semiring GrB_Matrix AT, // transpose of A (optional; push-only if NULL) int64_t source, // starting node of the BFS int64_t max_level, // optional limit of # levels to search bool vsparse // if true, v is expected to be very sparse ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; GrB_Vector q = NULL ; // nodes visited at each level GrB_Vector v = NULL ; // result vector GrB_Vector t = NULL ; // temporary vector GrB_Vector pi = NULL ; // parent vector if(v_output == NULL || (A == NULL && AT == NULL)) { // required output argument is missing LAGRAPH_ERROR("required arguments are NULL", GrB_NULL_POINTER) ; } (*v_output) = NULL ; bool compute_tree = (pi_output != NULL) ; GrB_Descriptor desc_s = GrB_DESC_S ; GrB_Descriptor desc_sc = GrB_DESC_SC ; GrB_Descriptor desc_rc = GrB_DESC_RC ; GrB_Descriptor desc_r = GrB_DESC_R ; GrB_Index nrows, ncols, nvalA, ignore, nvals ; // A is provided. AT may or may not be provided GrB_Matrix_nrows(&nrows, A) ; GrB_Matrix_ncols(&ncols, A) ; GrB_Matrix_nvals(&nvalA, A) ; bool use_vxm_with_A = true ; // push/pull requires both A and AT bool push_pull = (A != NULL && AT != NULL) ; if(nrows != ncols) { // A must be square LAGRAPH_ERROR("A must be square", GrB_NULL_POINTER) ; } //-------------------------------------------------------------------------- // initializations //-------------------------------------------------------------------------- GrB_Index n = nrows ; int nthreads = Config_GetOMPThreadCount(); nthreads = LAGRAPH_MIN(n / 4096, nthreads) ; nthreads = LAGRAPH_MAX(nthreads, 1) ; // just traverse from the source node max_level = (max_level <= 0) ? n : LAGRAPH_MIN(n, max_level) ; // create an empty vector v GrB_Type int_type = (n > INT32_MAX) ? GrB_INT64 : GrB_INT32 ; GrB_Vector_new(&v, int_type, n) ; // make v dense if requested int64_t vlimit = LAGRAPH_MAX(256, sqrt((double) n)) ; if(!vsparse) { // v is expected to have many entries, so convert v to dense. // If the guess is wrong, v can be made dense later on. GrB_assign(v, NULL, NULL, 0, GrB_ALL, n, NULL) ; } GrB_Semiring first_semiring, second_semiring ; if(compute_tree) { // create an integer vector q, and set q(source) to source+1 GrB_Vector_new(&q, int_type, n) ; GrB_Vector_setElement(q, source + 1, source) ; if(n > INT32_MAX) { // terminates as soon as it finds any parent; nondeterministic first_semiring = GxB_ANY_FIRST_INT64 ; second_semiring = GxB_ANY_SECOND_INT64 ; } else { // terminates as soon as it finds any parent; nondeterministic first_semiring = GxB_ANY_FIRST_INT32 ; second_semiring = GxB_ANY_SECOND_INT32 ; } // create the empty parent vector GrB_Vector_new(&pi, int_type, n) ; if(!vsparse) { // make pi a dense vector of all zeros GrB_assign(pi, NULL, NULL, 0, GrB_ALL, n, NULL) ; } // pi (source) = source+1 denotes a root of the BFS tree GrB_Vector_setElement(pi, source + 1, source) ; } else { // create a boolean vector q, and set q(source) to true GrB_Vector_new(&q, GrB_BOOL, n) ; GrB_Vector_setElement(q, true, source) ; // terminates as soon as it finds any pair first_semiring = GxB_ANY_PAIR_BOOL ; second_semiring = GxB_ANY_PAIR_BOOL ; } // average node degree double d = (n == 0) ? 0 : (((double) nvalA) / (double) n) ; int64_t nvisited = 0 ; // # nodes visited so far GrB_Index nq = 1 ; // number of nodes in the current level //-------------------------------------------------------------------------- // BFS traversal and label the nodes //-------------------------------------------------------------------------- for(int64_t level = 1 ; ; level++) { //---------------------------------------------------------------------- // set v to the current level, for all nodes in q //---------------------------------------------------------------------- // v<q> = level: set v(i) = level for all nodes i in q GrB_assign(v, q, NULL, level, GrB_ALL, n, desc_s) ; //---------------------------------------------------------------------- // check if done //---------------------------------------------------------------------- nvisited += nq ; if(nq == 0 || nvisited == n || level >= max_level) break ; //---------------------------------------------------------------------- // check if v should be converted to dense //---------------------------------------------------------------------- if(vsparse && nvisited > vlimit) { // Convert v from sparse to dense to speed up the rest of the work. // If this case is triggered, it would have been faster to pass in // vsparse = false on input. // v <!v> = 0 GrB_assign(v, v, NULL, 0, GrB_ALL, n, desc_sc) ; GrB_Vector_nvals(&ignore, v) ; if(compute_tree) { // Convert pi from sparse to dense, to speed up the work. // pi<!pi> = 0 GrB_assign(pi, pi, NULL, 0, GrB_ALL, n, desc_sc) ; GrB_Vector_nvals(&ignore, pi) ; } vsparse = false ; } //---------------------------------------------------------------------- // select push vs pull //---------------------------------------------------------------------- if(push_pull) { double pushwork = d * nq ; double expected = (double) n / (double)(nvisited + 1) ; double per_dot = LAGRAPH_MIN(d, expected) ; double binarysearch = (3 * (1 + log2((double) nq))) ; double pullwork = (n - nvisited) * per_dot * binarysearch ; use_vxm_with_A = (pushwork < pullwork) ; } //---------------------------------------------------------------------- // q = next level of the BFS //---------------------------------------------------------------------- if(use_vxm_with_A) { // q'<!v> = q'*A // this is a push step if A is in CSR format; pull if CSC GrB_vxm(q, v, NULL, first_semiring, q, A, desc_rc) ; } else { // q<!v> = AT*q // this is a pull step if AT is in CSR format; push if CSC GrB_mxv(q, v, NULL, second_semiring, AT, q, desc_rc) ; } //---------------------------------------------------------------------- // move to next level //---------------------------------------------------------------------- if(compute_tree) { //------------------------------------------------------------------ // assign parents //------------------------------------------------------------------ // q(i) currently contains the parent of node i in tree (off by one // so it won't have any zero values, for valued mask). // pi<q> = q GrB_assign(pi, q, NULL, q, GrB_ALL, n, desc_s) ; //------------------------------------------------------------------ // replace q with current node numbers //------------------------------------------------------------------ // TODO this could be a unaryop // q(i) = i+1 for all entries in q. GrB_Index *qi ; if(n > INT32_MAX) { int64_t *qx ; GxB_Vector_export(&q, &int_type, &n, &nq, &qi, (void **)(&qx), NULL) ; int nth = LAGRAPH_MIN(nq / (64 * 1024), nthreads) ; nth = LAGRAPH_MAX(nth, 1) ; #pragma omp parallel for num_threads(nth) schedule(static) for(int64_t k = 0 ; k < nq ; k++) { qx [k] = qi [k] + 1 ; } GxB_Vector_import(&q, int_type, n, nq, &qi, (void **)(&qx), NULL) ; } else { int32_t *qx ; GxB_Vector_export(&q, &int_type, &n, &nq, &qi, (void **)(&qx), NULL) ; int nth = LAGRAPH_MIN(nq / (64 * 1024), nthreads) ; nth = LAGRAPH_MAX(nth, 1) ; #pragma omp parallel for num_threads(nth) schedule(static) for(int32_t k = 0 ; k < nq ; k++) { qx [k] = qi [k] + 1 ; } GxB_Vector_import(&q, int_type, n, nq, &qi, (void **)(&qx), NULL) ; } } else { //------------------------------------------------------------------ // count the nodes in the current level //------------------------------------------------------------------ GrB_Vector_nvals(&nq, q) ; } } //-------------------------------------------------------------------------- // return the parent vector, if computed //-------------------------------------------------------------------------- if(compute_tree) { (*pi_output) = pi ; pi = NULL ; } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- (*v_output) = v ; // return result v = NULL ; // set to NULL so LAGRAPH_FREE_ALL doesn't free it LAGRAPH_FREE_ALL ; // free all workspace (except for result v) return (GrB_SUCCESS) ; }
ConverterOSG.h
/* -*-c++-*- IfcQuery www.ifcquery.com * MIT License Copyright (c) 2017 Fabian Gerold 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 #include <osg/CullFace> #include <osg/Geode> #include <osg/Hint> #include <osg/LineWidth> #include <osg/Material> #include <osg/Point> #include <osgUtil/Tessellator> #include <ifcpp/model/BasicTypes.h> #include <ifcpp/model/StatusCallback.h> #include <ifcpp/IFC4/include/IfcCurtainWall.h> #include <ifcpp/IFC4/include/IfcFeatureElementSubtraction.h> #include <ifcpp/IFC4/include/IfcGloballyUniqueId.h> #include <ifcpp/IFC4/include/IfcProject.h> #include <ifcpp/IFC4/include/IfcPropertySetDefinitionSet.h> #include <ifcpp/IFC4/include/IfcRelAggregates.h> #include <ifcpp/IFC4/include/IfcSpace.h> #include <ifcpp/IFC4/include/IfcWindow.h> #include <ifcpp/geometry/GeometrySettings.h> #include <ifcpp/geometry/SceneGraphUtils.h> #include <ifcpp/geometry/AppearanceData.h> #include "GeometryInputData.h" #include "IncludeCarveHeaders.h" #include "CSG_Adapter.h" class ConverterOSG : public StatusCallback { protected: shared_ptr<GeometrySettings> m_geom_settings; std::map<std::string, osg::ref_ptr<osg::Switch> > m_map_entity_guid_to_switch; std::map<int, osg::ref_ptr<osg::Switch> > m_map_representation_id_to_switch; double m_recent_progress; osg::ref_ptr<osg::CullFace> m_cull_back_off; osg::ref_ptr<osg::StateSet> m_glass_stateset; //\brief StateSet caching and re-use std::vector<osg::ref_ptr<osg::StateSet> > m_vec_existing_statesets; bool m_enable_stateset_caching = false; #ifdef ENABLE_OPENMP Mutex m_writelock_appearance_cache; #endif public: ConverterOSG( shared_ptr<GeometrySettings>& geom_settings ) : m_geom_settings(geom_settings) { m_cull_back_off = new osg::CullFace( osg::CullFace::BACK ); m_glass_stateset = new osg::StateSet(); m_glass_stateset->setMode( GL_BLEND, osg::StateAttribute::ON ); m_glass_stateset->setRenderingHint( osg::StateSet::TRANSPARENT_BIN ); } virtual ~ConverterOSG() {} // Map: IfcProduct ID -> scenegraph switch std::map<std::string, osg::ref_ptr<osg::Switch> >& getMapEntityGUIDToSwitch() { return m_map_entity_guid_to_switch; } // Map: Representation Identifier -> scenegraph switch std::map<int, osg::ref_ptr<osg::Switch> >& getMapRepresentationToSwitch() { return m_map_representation_id_to_switch; } void clearInputCache() { m_map_entity_guid_to_switch.clear(); m_map_representation_id_to_switch.clear(); m_vec_existing_statesets.clear(); } static void drawBoundingBox( const carve::geom::aabb<3>& aabb, osg::Geometry* geom ) { osg::ref_ptr<osg::Vec3Array> vertices = dynamic_cast<osg::Vec3Array*>( geom->getVertexArray() ); if( !vertices ) { vertices = new osg::Vec3Array(); geom->setVertexArray( vertices ); } const carve::geom::vector<3>& aabb_pos = aabb.pos; const carve::geom::vector<3>& extent = aabb.extent; const double dex = extent.x; const double dey = extent.y; const double dez = extent.z; const int vert_id_offset = vertices->size(); vertices->push_back( osg::Vec3f( aabb_pos.x - dex, aabb_pos.y - dey, aabb_pos.z - dez ) ); vertices->push_back( osg::Vec3f( aabb_pos.x + dex, aabb_pos.y - dey, aabb_pos.z - dez ) ); vertices->push_back( osg::Vec3f( aabb_pos.x + dex, aabb_pos.y + dey, aabb_pos.z - dez ) ); vertices->push_back( osg::Vec3f( aabb_pos.x - dex, aabb_pos.y + dey, aabb_pos.z - dez ) ); vertices->push_back( osg::Vec3f( aabb_pos.x - dex, aabb_pos.y - dey, aabb_pos.z + dez ) ); vertices->push_back( osg::Vec3f( aabb_pos.x + dex, aabb_pos.y - dey, aabb_pos.z + dez ) ); vertices->push_back( osg::Vec3f( aabb_pos.x + dex, aabb_pos.y + dey, aabb_pos.z + dez ) ); vertices->push_back( osg::Vec3f( aabb_pos.x - dex, aabb_pos.y + dey, aabb_pos.z + dez ) ); osg::ref_ptr<osg::DrawElementsUInt> box_lines = new osg::DrawElementsUInt( GL_LINE_STRIP, 0 ); box_lines->push_back( vert_id_offset + 0 ); box_lines->push_back( vert_id_offset + 1 ); box_lines->push_back( vert_id_offset + 2 ); box_lines->push_back( vert_id_offset + 3 ); box_lines->push_back( vert_id_offset + 0 ); box_lines->push_back( vert_id_offset + 4 ); box_lines->push_back( vert_id_offset + 5 ); box_lines->push_back( vert_id_offset + 1 ); box_lines->push_back( vert_id_offset + 5 ); box_lines->push_back( vert_id_offset + 6 ); box_lines->push_back( vert_id_offset + 2 ); box_lines->push_back( vert_id_offset + 6 ); box_lines->push_back( vert_id_offset + 7 ); box_lines->push_back( vert_id_offset + 3 ); box_lines->push_back( vert_id_offset + 7 ); box_lines->push_back( vert_id_offset + 4 ); geom->addPrimitiveSet( box_lines ); osg::ref_ptr<osg::Material> mat = new osg::Material(); if( !mat ) { throw OutOfMemoryException(); } osg::Vec4f ambientColor( 1.f, 0.2f, 0.1f, 1.f ); mat->setAmbient( osg::Material::FRONT_AND_BACK, ambientColor ); mat->setDiffuse( osg::Material::FRONT_AND_BACK, ambientColor ); mat->setSpecular( osg::Material::FRONT_AND_BACK, ambientColor ); //mat->setShininess( osg::Material::FRONT_AND_BACK, shininess ); //mat->setColorMode( osg::Material::SPECULAR ); osg::StateSet* stateset = geom->getOrCreateStateSet(); if( !stateset ) { throw OutOfMemoryException(); } stateset->setAttribute( mat, osg::StateAttribute::ON ); stateset->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); } static void drawFace( const carve::mesh::Face<3>* face, osg::Geode* geode, bool add_color_array = false ) { #ifdef _DEBUG std::cout << "not triangulated" << std::endl; #endif std::vector<vec3> face_vertices; face_vertices.resize( face->nVertices() ); carve::mesh::Edge<3> *e = face->edge; const size_t num_vertices = face->nVertices(); for( size_t i = 0; i < num_vertices; ++i ) { face_vertices[i] = e->v1()->v; e = e->next; } if( num_vertices < 4 ) { std::cout << "drawFace is meant only for num vertices > 4" << std::endl; } vec3* vertex_vec; osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array( num_vertices ); if( !vertices ) { throw OutOfMemoryException(); } osg::ref_ptr<osg::DrawElementsUInt> triangles = new osg::DrawElementsUInt( osg::PrimitiveSet::POLYGON, num_vertices ); if( !triangles ) { throw OutOfMemoryException(); } for( size_t i = 0; i < num_vertices; ++i ) { vertex_vec = &face_vertices[num_vertices - i - 1]; ( *vertices )[i].set( vertex_vec->x, vertex_vec->y, vertex_vec->z ); ( *triangles )[i] = i; } osg::Vec3f poly_normal = SceneGraphUtils::computePolygonNormal( vertices ); osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array(); normals->resize( num_vertices, poly_normal ); osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); geometry->setVertexArray( vertices ); geometry->setNormalArray( normals ); normals->setBinding( osg::Array::BIND_PER_VERTEX ); geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::POLYGON, 0, vertices->size() ) ); if( add_color_array ) { osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(); colors->resize( vertices->size(), osg::Vec4f( 0.6f, 0.6f, 0.6f, 0.1f ) ); colors->setBinding( osg::Array::BIND_PER_VERTEX ); geometry->setColorArray( colors ); } if( num_vertices > 4 ) { // TODO: check if polygon is convex with Gift wrapping algorithm osg::ref_ptr<osgUtil::Tessellator> tesselator = new osgUtil::Tessellator(); tesselator->setTessellationType( osgUtil::Tessellator::TESS_TYPE_POLYGONS ); //tesselator->setWindingType( osgUtil::Tessellator::TESS_WINDING_ODD ); tesselator->retessellatePolygons( *geometry ); } geode->addDrawable( geometry ); #ifdef DEBUG_DRAW_NORMALS osg::ref_ptr<osg::Vec3Array> vertices_normals = new osg::Vec3Array(); for( size_t i = 0; i < num_vertices; ++i ) { vertex_vec = &face_vertices[num_vertices - i - 1]; vertices_normals->push_back( osg::Vec3f( vertex_vec->x, vertex_vec->y, vertex_vec->z ) ); vertices_normals->push_back( osg::Vec3f( vertex_vec->x, vertex_vec->y, vertex_vec->z ) + poly_normal ); } osg::ref_ptr<osg::Vec4Array> colors_normals = new osg::Vec4Array(); colors_normals->resize( num_vertices * 2, osg::Vec4f( 0.4f, 0.7f, 0.4f, 1.f ) ); osg::ref_ptr<osg::Geometry> geometry_normals = new osg::Geometry(); geometry_normals->setVertexArray( vertices_normals ); geometry_normals->setColorArray( colors_normals ); geometry_normals->setColorBinding( osg::Geometry::BIND_PER_VERTEX ); geometry_normals->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); geometry_normals->setNormalBinding( osg::Geometry::BIND_OFF ); geometry_normals->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINES, 0, vertices_normals->size() ) ); geode->addDrawable( geometry_normals ); #endif } //#define DEBUG_DRAW_NORMALS static void drawMeshSet( const shared_ptr<carve::mesh::MeshSet<3> >& meshset, osg::Geode* geode, double crease_angle = M_PI*0.05, bool add_color_array = false ) { if( !meshset ) { return; } osg::ref_ptr<osg::Vec3Array> vertices_tri = new osg::Vec3Array(); if( !vertices_tri ) { throw OutOfMemoryException(); } osg::ref_ptr<osg::Vec3Array> normals_tri = new osg::Vec3Array(); if( !normals_tri ) { throw OutOfMemoryException(); } osg::ref_ptr<osg::Vec3Array> vertices_quad; osg::ref_ptr<osg::Vec3Array> normals_quad; const size_t max_num_faces_per_vertex = 10000; std::map<carve::mesh::Face<3>*, double> map_face_area; std::map<carve::mesh::Face<3>*, double>::iterator it_face_area; if( crease_angle > 0 ) { for( size_t i_mesh = 0; i_mesh < meshset->meshes.size(); ++i_mesh ) { const carve::mesh::Mesh<3>* mesh = meshset->meshes[i_mesh]; const size_t num_faces = mesh->faces.size(); for( size_t i_face = 0; i_face != num_faces; ++i_face ) { carve::mesh::Face<3>* face = mesh->faces[i_face]; // compute area of projected face: std::vector<vec2> projected; face->getProjectedVertices( projected ); double face_area = carve::geom2d::signedArea( projected ); map_face_area[face] = abs( face_area ); } } } for( size_t i_mesh = 0; i_mesh < meshset->meshes.size(); ++i_mesh ) { const carve::mesh::Mesh<3>* mesh = meshset->meshes[i_mesh]; const size_t num_faces = mesh->faces.size(); for( size_t i_face = 0; i_face != num_faces; ++i_face ) { carve::mesh::Face<3>* face = mesh->faces[i_face]; const size_t n_vertices = face->nVertices(); if( n_vertices > 4 ) { drawFace( face, geode ); continue; } const vec3 face_normal = face->plane.N; if( crease_angle > 0 ) { carve::mesh::Edge<3>* e = face->edge; for( size_t jj = 0; jj < n_vertices; ++jj ) { carve::mesh::Vertex<3>* vertex = e->vert; vec3 intermediate_normal; // collect all faces at vertex // | ^ // | | // f1 e->rev | | e face // v | // <---e1------- <--------------- //-------------> ---------------> // | ^ // | | // v | carve::mesh::Edge<3>* e1 = e;// ->rev->next; carve::mesh::Face<3>* f1 = e1->face; #ifdef _DEBUG if( f1 != face ) { std::cout << "f1 != face" << std::endl; } #endif for( size_t i3 = 0; i3 < max_num_faces_per_vertex; ++i3 ) { if( !e1->rev ) { break; } if( !e1->rev->next ) { break; } vec3 f1_normal = f1->plane.N; const double cos_angle = dot( f1_normal, face_normal ); if( cos_angle > 0 ) { const double deviation = std::abs( cos_angle - 1.0 ); if( deviation < crease_angle ) { double weight = 0.0; it_face_area = map_face_area.find( f1 ); if( it_face_area != map_face_area.end() ) { weight = it_face_area->second; } intermediate_normal += weight*f1_normal; } } if( !e1->rev ) { // it's an open mesh break; } e1 = e1->rev->next; if( !e1 ) { break; } f1 = e1->face; #ifdef _DEBUG if( e1->vert != vertex ) { std::cout << "e1->vert != vertex" << std::endl; } #endif if( f1 == face ) { break; } } const double intermediate_normal_length = intermediate_normal.length(); if( intermediate_normal_length < 0.0000000001 ) { intermediate_normal = face_normal; } else { // normalize: intermediate_normal *= 1.0 / intermediate_normal_length; } const vec3& vertex_v = vertex->v; if( face->n_edges == 3 ) { vertices_tri->push_back( osg::Vec3( vertex_v.x, vertex_v.y, vertex_v.z ) ); normals_tri->push_back( osg::Vec3( intermediate_normal.x, intermediate_normal.y, intermediate_normal.z ) ); } else if( face->n_edges == 4 ) { if( !vertices_quad ) vertices_quad = new osg::Vec3Array(); vertices_quad->push_back( osg::Vec3( vertex_v.x, vertex_v.y, vertex_v.z ) ); if( !normals_quad ) normals_quad = new osg::Vec3Array(); normals_quad->push_back( osg::Vec3( intermediate_normal.x, intermediate_normal.y, intermediate_normal.z ) ); } e = e->next; } } else { carve::mesh::Edge<3>* e = face->edge; for( size_t jj = 0; jj < n_vertices; ++jj ) { carve::mesh::Vertex<3>* vertex = e->vert; const vec3& vertex_v = vertex->v; if( face->n_edges == 3 ) { vertices_tri->push_back( osg::Vec3( vertex_v.x, vertex_v.y, vertex_v.z ) ); normals_tri->push_back( osg::Vec3( face_normal.x, face_normal.y, face_normal.z ) ); } else if( face->n_edges == 4 ) { if( !vertices_quad ) vertices_quad = new osg::Vec3Array(); vertices_quad->push_back( osg::Vec3( vertex_v.x, vertex_v.y, vertex_v.z ) ); if( !normals_quad ) normals_quad = new osg::Vec3Array(); normals_quad->push_back( osg::Vec3( face_normal.x, face_normal.y, face_normal.z ) ); } e = e->next; } } } } if( vertices_tri->size() > 0 ) { osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); if( !geometry ) { throw OutOfMemoryException(); } geometry->setVertexArray( vertices_tri ); geometry->setNormalArray( normals_tri ); normals_tri->setBinding( osg::Array::BIND_PER_VERTEX ); if( add_color_array ) { osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(); if( !colors ) { throw OutOfMemoryException(); } colors->resize( vertices_tri->size(), osg::Vec4f( 0.6f, 0.6f, 0.6f, 0.1f ) ); colors->setBinding( osg::Array::BIND_PER_VERTEX ); geometry->setColorArray( colors ); } geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::TRIANGLES, 0, vertices_tri->size() ) ); if( !geometry ) { throw OutOfMemoryException(); } geode->addDrawable( geometry ); #ifdef DEBUG_DRAW_NORMALS osg::ref_ptr<osg::Vec3Array> vertices_normals = new osg::Vec3Array(); for( size_t i = 0; i < vertices_tri->size(); ++i ) { osg::Vec3f& vertex_vec = vertices_tri->at( i );// [i]; osg::Vec3f& normal_vec = normals_tri->at( i ); vertices_normals->push_back( osg::Vec3f( vertex_vec.x(), vertex_vec.y(), vertex_vec.z() ) ); vertices_normals->push_back( osg::Vec3f( vertex_vec.x(), vertex_vec.y(), vertex_vec.z() ) + normal_vec ); } osg::ref_ptr<osg::Vec4Array> colors_normals = new osg::Vec4Array(); colors_normals->resize( vertices_normals->size(), osg::Vec4f( 0.4f, 0.7f, 0.4f, 1.f ) ); osg::ref_ptr<osg::Geometry> geometry_normals = new osg::Geometry(); geometry_normals->setVertexArray( vertices_normals ); geometry_normals->setColorArray( colors_normals ); geometry_normals->setColorBinding( osg::Geometry::BIND_PER_VERTEX ); geometry_normals->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); geometry_normals->setNormalBinding( osg::Geometry::BIND_OFF ); geometry_normals->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINES, 0, vertices_normals->size() ) ); geode->addDrawable( geometry_normals ); #endif } if( vertices_quad ) { if( vertices_quad->size() > 0 ) { osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); if( !geometry ) { throw OutOfMemoryException(); } geometry->setVertexArray( vertices_quad ); if( normals_quad ) { normals_quad->setBinding( osg::Array::BIND_PER_VERTEX ); geometry->setNormalArray( normals_quad ); } if( add_color_array ) { osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(); if( !colors ) { throw OutOfMemoryException(); } colors->resize( vertices_quad->size(), osg::Vec4f( 0.6f, 0.6f, 0.6f, 0.1f ) ); colors->setBinding( osg::Array::BIND_PER_VERTEX ); geometry->setColorArray( colors ); } geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::QUADS, 0, vertices_quad->size() ) ); if( !geometry ) { throw OutOfMemoryException(); } geode->addDrawable( geometry ); } } } static void drawPolyline( const carve::input::PolylineSetData* polyline_data, osg::Geode* geode, bool add_color_array = false ) { osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(); if( !vertices ) { throw OutOfMemoryException(); } carve::line::PolylineSet* polyline_set = polyline_data->create( carve::input::opts() ); if( polyline_set->vertices.size() < 2 ) { #ifdef _DEBUG std::cout << __FUNC__ << ": polyline_set->vertices.size() < 2" << std::endl; #endif return; } for( auto it = polyline_set->lines.begin(); it != polyline_set->lines.end(); ++it ) { const carve::line::Polyline* pline = *it; size_t vertex_count = pline->vertexCount(); for( size_t vertex_i = 0; vertex_i < vertex_count; ++vertex_i ) { if( vertex_i >= polyline_set->vertices.size() ) { #ifdef _DEBUG std::cout << __FUNC__ << ": vertex_i >= polyline_set->vertices.size()" << std::endl; #endif continue; } const carve::line::Vertex* v = pline->vertex( vertex_i ); vertices->push_back( osg::Vec3d( v->v[0], v->v[1], v->v[2] ) ); } } osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); if( !geometry ) { throw OutOfMemoryException(); } geometry->setVertexArray( vertices ); geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINE_STRIP, 0, vertices->size() ) ); if( add_color_array ) { osg::Vec4f color( 0.6f, 0.6f, 0.6f, 0.1f ); osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array( vertices->size(), &color ); if( !colors ) { throw OutOfMemoryException(); } colors->setBinding( osg::Array::BIND_PER_VERTEX ); geometry->setColorArray( colors ); } geode->addDrawable( geometry ); } void computeCreaseEdgesFromMeshset( const shared_ptr<carve::mesh::MeshSet<3> >& meshset, std::vector<carve::mesh::Edge<3>* >& vec_edges_out, const double crease_angle ) { if( !meshset ) { return; } for( size_t i_mesh = 0; i_mesh < meshset->meshes.size(); ++i_mesh ) { const carve::mesh::Mesh<3>* mesh = meshset->meshes[i_mesh]; const std::vector<carve::mesh::Edge<3>* >& vec_closed_edges = mesh->closed_edges; for( size_t i_edge = 0; i_edge < vec_closed_edges.size(); ++i_edge ) { carve::mesh::Edge<3>* edge = vec_closed_edges[i_edge]; if( !edge ) { continue; } carve::mesh::Edge<3>* edge_reverse = edge->rev; if( !edge_reverse ) { continue; } carve::mesh::Face<3>* face = edge->face; carve::mesh::Face<3>* face_reverse = edge_reverse->face; const carve::geom::vector<3>& f1_normal = face->plane.N; const carve::geom::vector<3>& f2_normal = face_reverse->plane.N; const double cos_angle = dot( f1_normal, f2_normal ); if( cos_angle > 0 ) { const double deviation = std::abs( cos_angle - 1.0 ); if( deviation < crease_angle ) { continue; } } // TODO: if area of face and face_reverse is equal, skip the crease edge. It could be the inside or outside of a cylinder. Check also if > 2 faces in a row have same normal angle differences vec_edges_out.push_back( edge ); } } } void renderMeshsetCreaseEdges( const shared_ptr<carve::mesh::MeshSet<3> >& meshset, osg::Geode* target_geode, const double crease_angle ) { if( !meshset ) { return; } if( !target_geode ) { return; } std::vector<carve::mesh::Edge<3>* > vec_crease_edges; computeCreaseEdgesFromMeshset( meshset, vec_crease_edges, crease_angle ); if( vec_crease_edges.size() > 0 ) { osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(); for( size_t i_edge = 0; i_edge < vec_crease_edges.size(); ++i_edge ) { const carve::mesh::Edge<3>* edge = vec_crease_edges[i_edge]; const carve::geom::vector<3>& vertex1 = edge->v1()->v; const carve::geom::vector<3>& vertex2 = edge->v2()->v; vertices->push_back( osg::Vec3d( vertex1.x, vertex1.y, vertex1.z ) ); vertices->push_back( osg::Vec3d( vertex2.x, vertex2.y, vertex2.z ) ); } osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); geometry->setName("creaseEdges"); geometry->setVertexArray( vertices ); geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINES, 0, vertices->size() ) ); geometry->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); geometry->getOrCreateStateSet()->setMode( GL_BLEND, osg::StateAttribute::ON ); geometry->getOrCreateStateSet()->setAttributeAndModes( new osg::LineWidth( 3.0f ), osg::StateAttribute::ON ); geometry->getOrCreateStateSet()->setMode( GL_LINE_SMOOTH, osg::StateAttribute::ON ); geometry->getOrCreateStateSet()->setAttributeAndModes( new osg::Hint( GL_LINE_SMOOTH_HINT, GL_NICEST ), osg::StateAttribute::ON ); geometry->getOrCreateStateSet()->setRenderBinDetails( 10, "RenderBin"); target_geode->addDrawable( geometry ); } } void applyAppearancesToGroup( const std::vector<shared_ptr<AppearanceData> >& vec_product_appearances, osg::Group* grp ) { for( size_t ii = 0; ii < vec_product_appearances.size(); ++ii ) { const shared_ptr<AppearanceData>& appearance = vec_product_appearances[ii]; if( !appearance ) { continue; } if( appearance->m_apply_to_geometry_type == AppearanceData::GEOM_TYPE_SURFACE || appearance->m_apply_to_geometry_type == AppearanceData::GEOM_TYPE_ANY ) { osg::ref_ptr<osg::StateSet> item_stateset; convertToOSGStateSet( appearance, item_stateset ); if( item_stateset ) { osg::StateSet* existing_item_stateset = grp->getStateSet(); if( existing_item_stateset ) { if( existing_item_stateset != item_stateset ) { existing_item_stateset->merge( *item_stateset ); } } else { grp->setStateSet( item_stateset ); } } } else if( appearance->m_apply_to_geometry_type == AppearanceData::GEOM_TYPE_CURVE ) { } } } osg::Matrixd convertMatrixToOSG( const carve::math::Matrix& mat_in ) { return osg::Matrixd( mat_in.m[0][0], mat_in.m[0][1], mat_in.m[0][2], mat_in.m[0][3], mat_in.m[1][0], mat_in.m[1][1], mat_in.m[1][2], mat_in.m[1][3], mat_in.m[2][0], mat_in.m[2][1], mat_in.m[2][2], mat_in.m[2][3], mat_in.m[3][0], mat_in.m[3][1], mat_in.m[3][2], mat_in.m[3][3] ); } //\brief method convertProductShapeToOSG: creates geometry objects from an IfcProduct object // caution: when using OpenMP, this method runs in parallel threads, so every write access to member variables needs a write lock void convertProductShapeToOSG( shared_ptr<ProductShapeData>& product_shape, std::map<int, osg::ref_ptr<osg::Switch> >& map_representation_switches ) { if( product_shape->m_ifc_object_definition.expired() ) { return; } shared_ptr<IfcObjectDefinition> ifc_object_def(product_shape->m_ifc_object_definition); shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>(ifc_object_def); if( !ifc_product ) { return; } std::string product_guid; if (ifc_product->m_GlobalId) { std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; product_guid = converterX.to_bytes(ifc_product->m_GlobalId->m_value); } std::stringstream strs_product_switch_name; strs_product_switch_name << product_guid << ":" << ifc_product->className() << " group"; bool draw_bounding_box = false; // create OSG objects std::vector<shared_ptr<RepresentationData> >& vec_product_representations = product_shape->m_vec_representations; for( size_t ii_representation = 0; ii_representation < vec_product_representations.size(); ++ii_representation ) { const shared_ptr<RepresentationData>& product_representation_data = vec_product_representations[ii_representation]; if( product_representation_data->m_ifc_representation.expired() ) { continue; } shared_ptr<IfcRepresentation> ifc_representation( product_representation_data->m_ifc_representation ); const int representation_id = ifc_representation->m_entity_id; osg::ref_ptr<osg::Switch> representation_switch = new osg::Switch(); #ifdef _DEBUG std::stringstream strs_representation_name; strs_representation_name << strs_product_switch_name.str().c_str() << ", representation " << ii_representation; representation_switch->setName( strs_representation_name.str().c_str() ); #endif const std::vector<shared_ptr<ItemShapeData> >& product_items = product_representation_data->m_vec_item_data; for( size_t i_item = 0; i_item < product_items.size(); ++i_item ) { const shared_ptr<ItemShapeData>& item_shape = product_items[i_item]; osg::ref_ptr<osg::MatrixTransform> item_group = new osg::MatrixTransform(); if( !item_group ) { throw OutOfMemoryException( __FUNC__ ); } #ifdef _DEBUG std::stringstream strs_item_name; strs_item_name << strs_representation_name.str().c_str() << ", item " << i_item; item_group->setName( strs_item_name.str().c_str() ); #endif // create shape for open shells for( size_t ii = 0; ii < item_shape->m_meshsets_open.size(); ++ii ) { shared_ptr<carve::mesh::MeshSet<3> >& item_meshset = item_shape->m_meshsets_open[ii]; CSG_Adapter::retriangulateMeshSet( item_meshset ); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); if( !geode ) { throw OutOfMemoryException( __FUNC__ ); } drawMeshSet( item_meshset, geode, m_geom_settings->getCoplanarFacesMaxDeltaAngle() ); if( m_geom_settings->getRenderCreaseEdges() ) { renderMeshsetCreaseEdges( item_meshset, geode, m_geom_settings->getCreaseEdgesMaxDeltaAngle() ); } // disable back face culling for open meshes geode->getOrCreateStateSet()->setAttributeAndModes( m_cull_back_off.get(), osg::StateAttribute::OFF ); item_group->addChild( geode ); if( draw_bounding_box ) { carve::geom::aabb<3> bbox = item_meshset->getAABB(); osg::ref_ptr<osg::Geometry> bbox_geom = new osg::Geometry(); drawBoundingBox( bbox, bbox_geom ); geode->addDrawable( bbox_geom ); } #ifdef _DEBUG std::stringstream strs_item_meshset_name; strs_item_meshset_name << strs_item_name.str().c_str() << ", open meshset " << ii; geode->setName( strs_item_meshset_name.str().c_str() ); #endif } // create shape for meshsets for( size_t ii = 0; ii < item_shape->m_meshsets.size(); ++ii ) { shared_ptr<carve::mesh::MeshSet<3> >& item_meshset = item_shape->m_meshsets[ii]; CSG_Adapter::retriangulateMeshSet( item_meshset ); osg::ref_ptr<osg::Geode> geode_meshset = new osg::Geode(); if( !geode_meshset ) { throw OutOfMemoryException( __FUNC__ ); } drawMeshSet( item_meshset, geode_meshset, m_geom_settings->getCoplanarFacesMaxDeltaAngle() ); item_group->addChild( geode_meshset ); if( m_geom_settings->getRenderCreaseEdges() ) { renderMeshsetCreaseEdges( item_meshset, geode_meshset, m_geom_settings->getCreaseEdgesMaxDeltaAngle() ); } if( draw_bounding_box ) { carve::geom::aabb<3> bbox = item_meshset->getAABB(); osg::ref_ptr<osg::Geometry> bbox_geom = new osg::Geometry(); drawBoundingBox( bbox, bbox_geom ); geode_meshset->addDrawable( bbox_geom ); } #ifdef _DEBUG std::stringstream strs_item_meshset_name; strs_item_meshset_name << strs_item_name.str().c_str() << ", meshset " << ii; geode_meshset->setName( strs_item_meshset_name.str().c_str() ); #endif } // create shape for points const std::vector<shared_ptr<carve::input::VertexData> >& vertex_points = item_shape->getVertexPoints(); for( size_t ii = 0; ii < vertex_points.size(); ++ii ) { const shared_ptr<carve::input::VertexData>& pointset_data = vertex_points[ii]; if( pointset_data ) { if( pointset_data->points.size() > 0 ) { osg::ref_ptr<osg::Geode> geode = new osg::Geode(); if( !geode ) { throw OutOfMemoryException( __FUNC__ ); } osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(); for( size_t i_pointset_point = 0; i_pointset_point < pointset_data->points.size(); ++i_pointset_point ) { vec3& carve_point = pointset_data->points[i_pointset_point]; vertices->push_back( osg::Vec3d( carve_point.x, carve_point.y, carve_point.z ) ); } osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); geometry->setVertexArray( vertices ); geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::POINTS, 0, vertices->size() ) ); geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); geode->getOrCreateStateSet()->setAttribute( new osg::Point( 3.0f ), osg::StateAttribute::ON ); geode->addDrawable( geometry ); geode->setCullingActive( false ); item_group->addChild( geode ); #ifdef _DEBUG std::stringstream strs_item_meshset_name; strs_item_meshset_name << strs_item_name.str().c_str() << ", vertex_point " << ii; geode->setName( strs_item_meshset_name.str().c_str() ); #endif } } } // create shape for polylines for( size_t ii = 0; ii < item_shape->m_polylines.size(); ++ii ) { shared_ptr<carve::input::PolylineSetData>& polyline_data = item_shape->m_polylines[ii]; osg::ref_ptr<osg::Geode> geode = new osg::Geode(); if( !geode ) { throw OutOfMemoryException( __FUNC__ ); } geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); drawPolyline( polyline_data.get(), geode ); item_group->addChild( geode ); #ifdef _DEBUG std::stringstream strs_item_meshset_name; strs_item_meshset_name << strs_item_name.str().c_str() << ", polylines " << ii; geode->setName( strs_item_meshset_name.str().c_str() ); #endif } if( m_geom_settings->isShowTextLiterals() ) { for( size_t ii = 0; ii < item_shape->m_vec_text_literals.size(); ++ii ) { shared_ptr<TextItemData>& text_data = item_shape->m_vec_text_literals[ii]; if( !text_data ) { continue; } carve::math::Matrix& text_pos = text_data->m_text_position; // TODO: handle rotation std::string text_str; text_str.assign( text_data->m_text.begin(), text_data->m_text.end() ); osg::Vec3 pos2( text_pos._41, text_pos._42, text_pos._43 ); osg::ref_ptr<osgText::Text> txt = new osgText::Text(); if( !txt ) { throw OutOfMemoryException( __FUNC__ ); } txt->setFont( "fonts/arial.ttf" ); txt->setColor( osg::Vec4f( 0, 0, 0, 1 ) ); txt->setCharacterSize( 0.1f ); txt->setAutoRotateToScreen( true ); txt->setPosition( pos2 ); txt->setText( text_str.c_str() ); txt->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); if( !geode ){ throw OutOfMemoryException( __FUNC__ ); } geode->addDrawable( txt ); item_group->addChild( geode ); } } // apply statesets if there are any if( item_shape->m_vec_item_appearances.size() > 0 ) { applyAppearancesToGroup( item_shape->m_vec_item_appearances, item_group ); } // If anything has been created, add it to the representation group if( item_group->getNumChildren() > 0 ) { #ifdef _DEBUG if( item_group->getNumParents() > 0 ) { std::cout << __FUNC__ << ": item_group->getNumParents() > 0" << std::endl; } #endif representation_switch->addChild( item_group ); } } // apply statesets if there are any if( product_representation_data->m_vec_representation_appearances.size() > 0 ) { applyAppearancesToGroup( product_representation_data->m_vec_representation_appearances, representation_switch ); } // If anything has been created, add it to the product group if( representation_switch->getNumChildren() > 0 ) { #ifdef _DEBUG if( representation_switch->getNumParents() > 0 ) { std::cout << __FUNC__ << ": product_representation_switch->getNumParents() > 0" << std::endl; } #endif // enable transparency for certain objects if( dynamic_pointer_cast<IfcSpace>(ifc_product) ) { representation_switch->setStateSet( m_glass_stateset ); } else if( dynamic_pointer_cast<IfcCurtainWall>(ifc_product) || dynamic_pointer_cast<IfcWindow>(ifc_product) ) { representation_switch->setStateSet( m_glass_stateset ); SceneGraphUtils::setMaterialAlpha( representation_switch, 0.6f, true ); } // check if parent building element is window if( ifc_product->m_Decomposes_inverse.size() > 0 ) { for( size_t ii_decomposes = 0; ii_decomposes < ifc_product->m_Decomposes_inverse.size(); ++ii_decomposes ) { const weak_ptr<IfcRelAggregates>& decomposes_weak = ifc_product->m_Decomposes_inverse[ii_decomposes]; if( decomposes_weak.expired() ) { continue; } shared_ptr<IfcRelAggregates> decomposes_ptr(decomposes_weak); shared_ptr<IfcObjectDefinition>& relating_object = decomposes_ptr->m_RelatingObject; if( relating_object ) { if( dynamic_pointer_cast<IfcCurtainWall>(relating_object) || dynamic_pointer_cast<IfcWindow>(relating_object) ) { representation_switch->setStateSet(m_glass_stateset); SceneGraphUtils::setMaterialAlpha(representation_switch, 0.6f, true); } } } } map_representation_switches.insert( std::make_pair( representation_id, representation_switch ) ); } } // TODO: if no color or material is given, set color 231/219/169 for walls, 140/140/140 for slabs } /*\brief method convertToOSG: Creates geometry for OpenSceneGraph from given ProductShapeData. \param[out] parent_group Group to append the geometry. **/ void convertToOSG( const std::map<std::string, shared_ptr<ProductShapeData> >& map_shape_data, osg::ref_ptr<osg::Switch> parent_group ) { progressTextCallback( L"Converting geometry to OpenGL format ..." ); progressValueCallback( 0, "scenegraph" ); m_map_entity_guid_to_switch.clear(); m_map_representation_id_to_switch.clear(); m_vec_existing_statesets.clear(); shared_ptr<ProductShapeData> ifc_project_data; std::vector<shared_ptr<ProductShapeData> > vec_products; for( auto it = map_shape_data.begin(); it != map_shape_data.end(); ++it ) { shared_ptr<ProductShapeData> shape_data = it->second; if( shape_data ) { vec_products.push_back( shape_data ); } } // create geometry for for each IfcProduct independently, spatial structure will be resolved later std::map<std::string, osg::ref_ptr<osg::Switch> >* map_entity_guid = &m_map_entity_guid_to_switch; std::map<int, osg::ref_ptr<osg::Switch> >* map_representations = &m_map_representation_id_to_switch; const int num_products = (int)vec_products.size(); #ifdef ENABLE_OPENMP Mutex writelock_map; Mutex writelock_ifc_project; Mutex writelock_message_callback; #pragma omp parallel firstprivate(num_products) shared(map_entity_guid, map_representations) { // time for one product may vary significantly, so schedule not so many #pragma omp for schedule(dynamic,40) #endif for( int i = 0; i < num_products; ++i ) { shared_ptr<ProductShapeData>& shape_data = vec_products[i]; weak_ptr<IfcObjectDefinition>& ifc_object_def_weak = shape_data->m_ifc_object_definition; if( ifc_object_def_weak.expired() ) { continue; } shared_ptr<IfcObjectDefinition> ifc_object_def(shape_data->m_ifc_object_definition); shared_ptr<IfcProject> ifc_project = dynamic_pointer_cast<IfcProject>(ifc_object_def); if (ifc_project) { #ifdef ENABLE_OPENMP ScopedLock scoped_lock(writelock_ifc_project); #endif ifc_project_data = shape_data; } shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>(ifc_object_def); if (!ifc_product) { continue; } std::stringstream thread_err; if( dynamic_pointer_cast<IfcFeatureElementSubtraction>(ifc_product) ) { // geometry will be created in method subtractOpenings continue; } if( !ifc_product->m_Representation ) { continue; } const int product_id = ifc_product->m_entity_id; std::string product_guid; std::map<int, osg::ref_ptr<osg::Switch> > map_representation_switches; try { convertProductShapeToOSG( shape_data, map_representation_switches ); } catch( OutOfMemoryException& e ) { throw e; } catch( BuildingException& e ) { thread_err << e.what(); } catch( carve::exception& e ) { thread_err << e.str(); } catch( std::exception& e ) { thread_err << e.what(); } catch( ... ) { thread_err << "undefined error, product id " << product_id; } if (ifc_product->m_GlobalId) { std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; product_guid = converterX.to_bytes(ifc_product->m_GlobalId->m_value); } if( map_representation_switches.size() > 0 ) { osg::ref_ptr<osg::Switch> product_switch = new osg::Switch(); osg::ref_ptr<osg::MatrixTransform> product_transform = new osg::MatrixTransform(); product_transform->setMatrix( convertMatrixToOSG( shape_data->getTransform() ) ); product_switch->addChild( product_transform ); std::stringstream strs_product_switch_name; strs_product_switch_name << product_guid << ":" << ifc_product->className() << " group"; product_switch->setName( strs_product_switch_name.str().c_str() ); for( auto it_map = map_representation_switches.begin(); it_map != map_representation_switches.end(); ++it_map ) { osg::ref_ptr<osg::Switch>& repres_switch = it_map->second; product_transform->addChild( repres_switch ); } // apply statesets if there are any const std::vector<shared_ptr<AppearanceData> >& vec_product_appearances = shape_data->getAppearances(); if( vec_product_appearances.size() > 0 ) { applyAppearancesToGroup( vec_product_appearances, product_switch ); } #ifdef ENABLE_OPENMP ScopedLock scoped_lock( writelock_map ); #endif map_entity_guid->insert(std::make_pair(product_guid, product_switch)); map_representations->insert( map_representation_switches.begin(), map_representation_switches.end() ); } if( thread_err.tellp() > 0 ) { #ifdef ENABLE_OPENMP ScopedLock scoped_lock( writelock_message_callback ); #endif messageCallback( thread_err.str().c_str(), StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ ); } // progress callback double progress = (double)i / (double)num_products; if( progress - m_recent_progress > 0.02 ) { #ifdef ENABLE_OPENMP if( omp_get_thread_num() == 0 ) #endif { // leave 10% of progress to openscenegraph internals progressValueCallback( progress*0.9, "scenegraph" ); m_recent_progress = progress; } } } #ifdef ENABLE_OPENMP } // implicit barrier #endif try { // now resolve spatial structure if( ifc_project_data ) { resolveProjectStructure( ifc_project_data, parent_group ); } } catch( OutOfMemoryException& e ) { throw e; } catch( BuildingException& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( std::exception& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( ... ) { messageCallback( "undefined error", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ ); } progressValueCallback( 0.9, "scenegraph" ); } void addNodes( const std::map<std::string, shared_ptr<BuildingObject> >& map_shape_data, osg::ref_ptr<osg::Switch>& target_group ) { // check if there are entities that are not in spatial structure if( !target_group ) { target_group = new osg::Switch(); } for( auto it_product_shapes = map_shape_data.begin(); it_product_shapes != map_shape_data.end(); ++it_product_shapes ) { std::string product_guid = it_product_shapes->first; auto it_find = m_map_entity_guid_to_switch.find(product_guid); if( it_find != m_map_entity_guid_to_switch.end() ) { osg::ref_ptr<osg::Switch>& sw = it_find->second; if( sw ) { target_group->addChild( sw ); } } } } void resolveProjectStructure( const shared_ptr<ProductShapeData>& product_data, osg::ref_ptr<osg::Switch> group ) { if( !product_data ) { return; } if( product_data->m_ifc_object_definition.expired() ) { return; } shared_ptr<IfcObjectDefinition> ifc_object_def(product_data->m_ifc_object_definition); if (!ifc_object_def) { return; } std::string guid; if (ifc_object_def->m_GlobalId) { std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; guid = converterX.to_bytes(ifc_object_def->m_GlobalId->m_value); } if( SceneGraphUtils::inParentList(guid, group ) ) { messageCallback( "Cycle in project structure detected", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__, ifc_object_def.get() ); return; } const std::vector<shared_ptr<ProductShapeData> >& vec_children = product_data->getChildren(); for( size_t ii = 0; ii < vec_children.size(); ++ii ) { const shared_ptr<ProductShapeData>& child_product_data = vec_children[ii]; if( !child_product_data ) { continue; } osg::ref_ptr<osg::Switch> group_subparts = new osg::Switch(); if( !child_product_data->m_ifc_object_definition.expired() ) { shared_ptr<IfcObjectDefinition> child_obj_def( child_product_data->m_ifc_object_definition ); std::stringstream group_subparts_name; group_subparts_name << "#" << child_obj_def->m_entity_id << "="; group_subparts_name << child_obj_def->className(); group_subparts->setName( group_subparts_name.str().c_str() ); } group->addChild( group_subparts ); resolveProjectStructure( child_product_data, group_subparts ); } auto it_product_map = m_map_entity_guid_to_switch.find(guid); if( it_product_map != m_map_entity_guid_to_switch.end() ) { const osg::ref_ptr<osg::Switch>& product_switch = it_product_map->second; if( product_switch ) { group->addChild( product_switch ); } } else { if( group->getNumChildren() == 0 ) { osg::ref_ptr<osg::Switch> product_switch = new osg::Switch(); group->addChild( product_switch ); std::stringstream switch_name; switch_name << guid << ":" << ifc_object_def->className(); product_switch->setName( switch_name.str().c_str() ); } } } void clearAppearanceCache() { #ifdef ENABLE_OPENMP ScopedLock lock( m_writelock_appearance_cache ); #endif m_vec_existing_statesets.clear(); } void convertToOSGStateSet( const shared_ptr<AppearanceData>& appearence, osg::ref_ptr<osg::StateSet>& target_stateset ) { if( !appearence ) { return; } const float shininess = appearence->m_shininess; const float transparency = appearence->m_transparency; const bool set_transparent = appearence->m_set_transparent; const float color_ambient_r = appearence->m_color_ambient.r(); const float color_ambient_g = appearence->m_color_ambient.g(); const float color_ambient_b = appearence->m_color_ambient.b(); const float color_ambient_a = appearence->m_color_ambient.a(); const float color_diffuse_r = appearence->m_color_diffuse.r(); const float color_diffuse_g = appearence->m_color_diffuse.g(); const float color_diffuse_b = appearence->m_color_diffuse.b(); const float color_diffuse_a = appearence->m_color_diffuse.a(); const float color_specular_r = appearence->m_color_specular.r(); const float color_specular_g = appearence->m_color_specular.g(); const float color_specular_b = appearence->m_color_specular.b(); const float color_specular_a = appearence->m_color_specular.a(); if( m_enable_stateset_caching ) { #ifdef ENABLE_OPENMP ScopedLock lock( m_writelock_appearance_cache ); #endif for( size_t i = 0; i<m_vec_existing_statesets.size(); ++i ) { const osg::ref_ptr<osg::StateSet> stateset_existing = m_vec_existing_statesets[i]; if( !stateset_existing.valid() ) { continue; } osg::ref_ptr<osg::Material> mat_existing = (osg::Material*)stateset_existing->getAttribute( osg::StateAttribute::MATERIAL ); if( !mat_existing ) { continue; } // compare osg::Vec4f color_ambient_existing = mat_existing->getAmbient( osg::Material::FRONT_AND_BACK ); if( fabs( color_ambient_existing.r() - color_ambient_r ) > 0.03 ) break; if( fabs( color_ambient_existing.g() - color_ambient_g ) > 0.03 ) break; if( fabs( color_ambient_existing.b() - color_ambient_b ) > 0.03 ) break; if( fabs( color_ambient_existing.a() - color_ambient_a ) > 0.03 ) break; osg::Vec4f color_diffuse_existing = mat_existing->getDiffuse( osg::Material::FRONT_AND_BACK ); if( fabs( color_diffuse_existing.r() - color_diffuse_r ) > 0.03 ) break; if( fabs( color_diffuse_existing.g() - color_diffuse_g ) > 0.03 ) break; if( fabs( color_diffuse_existing.b() - color_diffuse_b ) > 0.03 ) break; if( fabs( color_diffuse_existing.a() - color_diffuse_a ) > 0.03 ) break; osg::Vec4f color_specular_existing = mat_existing->getSpecular( osg::Material::FRONT_AND_BACK ); if( fabs( color_specular_existing.r() - color_specular_r ) > 0.03 ) break; if( fabs( color_specular_existing.g() - color_specular_g ) > 0.03 ) break; if( fabs( color_specular_existing.b() - color_specular_b ) > 0.03 ) break; if( fabs( color_specular_existing.a() - color_specular_a ) > 0.03 ) break; float shininess_existing = mat_existing->getShininess( osg::Material::FRONT_AND_BACK ); if( fabs( shininess_existing - shininess ) > 0.03 ) break; bool blend_on_existing = stateset_existing->getMode( GL_BLEND ) == osg::StateAttribute::ON; if( blend_on_existing != set_transparent ) break; bool transparent_bin = stateset_existing->getRenderingHint() == osg::StateSet::TRANSPARENT_BIN; if( transparent_bin != set_transparent ) break; // if we get here, appearance is same as existing state set // TODO: block this re-used stateset for merging, or prevent merged statesets from being re-used target_stateset = stateset_existing; return; } } osg::Vec4f ambientColor( color_ambient_r, color_ambient_g, color_ambient_b, transparency ); osg::Vec4f diffuseColor( color_diffuse_r, color_diffuse_g, color_diffuse_b, transparency ); osg::Vec4f specularColor( color_specular_r, color_specular_g, color_specular_b, transparency ); // TODO: material caching and re-use osg::ref_ptr<osg::Material> mat = new osg::Material(); if( !mat ){ throw OutOfMemoryException(); } mat->setAmbient( osg::Material::FRONT_AND_BACK, ambientColor ); mat->setDiffuse( osg::Material::FRONT_AND_BACK, diffuseColor ); mat->setSpecular( osg::Material::FRONT_AND_BACK, specularColor ); mat->setShininess( osg::Material::FRONT_AND_BACK, shininess ); mat->setColorMode( osg::Material::SPECULAR ); target_stateset = new osg::StateSet(); if( !target_stateset ){ throw OutOfMemoryException(); } target_stateset->setAttribute( mat, osg::StateAttribute::ON ); if( appearence->m_set_transparent ) { mat->setTransparency( osg::Material::FRONT_AND_BACK, transparency ); target_stateset->setMode( GL_BLEND, osg::StateAttribute::ON ); target_stateset->setRenderingHint( osg::StateSet::TRANSPARENT_BIN ); } if( appearence->m_specular_exponent != 0.f ) { //osg::ref_ptr<osgFX::SpecularHighlights> spec_highlights = new osgFX::SpecularHighlights(); //spec_highlights->setSpecularExponent( spec->m_value ); // todo: add to scenegraph } if( m_enable_stateset_caching ) { m_vec_existing_statesets.push_back( target_stateset ); } } };
bitshuffle_core.c
/* * Bitshuffle - Filter for improving compression of typed binary data. * * Author: Kiyoshi Masui <kiyo@physics.ubc.ca> * Website: http://www.github.com/kiyo-masui/bitshuffle * Created: 2014 * * See LICENSE file for details about copyright and rights to use. * */ #include "bitshuffle_core.h" #include "bitshuffle_internals.h" #include <stdio.h> #include <string.h> #if defined(__AVX2__) && defined (__SSE2__) #define USEAVX2 #endif #if defined(__SSE2__) || defined(NO_WARN_X86_INTRINSICS) #define USESSE2 #endif #if defined(__ARM_NEON__) || (__ARM_NEON) #ifdef __aarch64__ #define USEARMNEON #endif #endif // Conditional includes for SSE2 and AVX2. #ifdef USEAVX2 #include <immintrin.h> #elif defined USESSE2 #include <emmintrin.h> #elif defined USEARMNEON #include <arm_neon.h> #endif #if defined(_OPENMP) && defined(_MSC_VER) typedef int64_t omp_size_t; #else typedef size_t omp_size_t; #endif // Macros. #define CHECK_MULT_EIGHT(n) if (n % 8) return -80; #define MAX(X,Y) ((X) > (Y) ? (X) : (Y)) /* ---- Functions indicating compile time instruction set. ---- */ int bshuf_using_NEON(void) { #ifdef USEARMNEON return 1; #else return 0; #endif } int bshuf_using_SSE2(void) { #ifdef USESSE2 return 1; #else return 0; #endif } int bshuf_using_AVX2(void) { #ifdef USEAVX2 return 1; #else return 0; #endif } /* ---- Worker code not requiring special instruction sets. ---- * * The following code does not use any x86 specific vectorized instructions * and should compile on any machine * */ /* Transpose 8x8 bit array packed into a single quadword *x*. * *t* is workspace. */ #define TRANS_BIT_8X8(x, t) { \ t = (x ^ (x >> 7)) & 0x00AA00AA00AA00AALL; \ x = x ^ t ^ (t << 7); \ t = (x ^ (x >> 14)) & 0x0000CCCC0000CCCCLL; \ x = x ^ t ^ (t << 14); \ t = (x ^ (x >> 28)) & 0x00000000F0F0F0F0LL; \ x = x ^ t ^ (t << 28); \ } /* Transpose 8x8 bit array along the diagonal from upper right to lower left */ #define TRANS_BIT_8X8_BE(x, t) { \ t = (x ^ (x >> 9)) & 0x0055005500550055LL; \ x = x ^ t ^ (t << 9); \ t = (x ^ (x >> 18)) & 0x0000333300003333LL; \ x = x ^ t ^ (t << 18); \ t = (x ^ (x >> 36)) & 0x000000000F0F0F0FLL; \ x = x ^ t ^ (t << 36); \ } /* Transpose of an array of arbitrarily typed elements. */ #define TRANS_ELEM_TYPE(in, out, lda, ldb, type_t) { \ size_t ii, jj, kk; \ const type_t* in_type = (const type_t*) in; \ type_t* out_type = (type_t*) out; \ for(ii = 0; ii + 7 < lda; ii += 8) { \ for(jj = 0; jj < ldb; jj++) { \ for(kk = 0; kk < 8; kk++) { \ out_type[jj*lda + ii + kk] = \ in_type[ii*ldb + kk * ldb + jj]; \ } \ } \ } \ for(ii = lda - lda % 8; ii < lda; ii ++) { \ for(jj = 0; jj < ldb; jj++) { \ out_type[jj*lda + ii] = in_type[ii*ldb + jj]; \ } \ } \ } /* Memory copy with bshuf call signature. For testing and profiling. */ int64_t bshuf_copy(const void* in, void* out, const size_t size, const size_t elem_size) { const char* in_b = (const char*) in; char* out_b = (char*) out; memcpy(out_b, in_b, size * elem_size); return size * elem_size; } /* Transpose bytes within elements, starting partway through input. */ int64_t bshuf_trans_byte_elem_remainder(const void* in, void* out, const size_t size, const size_t elem_size, const size_t start) { size_t ii, jj, kk; const char* in_b = (const char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(start); if (size > start) { // ii loop separated into 2 loops so the compiler can unroll // the inner one. for (ii = start; ii + 7 < size; ii += 8) { for (jj = 0; jj < elem_size; jj++) { for (kk = 0; kk < 8; kk++) { out_b[jj * size + ii + kk] = in_b[ii * elem_size + kk * elem_size + jj]; } } } for (ii = size - size % 8; ii < size; ii ++) { for (jj = 0; jj < elem_size; jj++) { out_b[jj * size + ii] = in_b[ii * elem_size + jj]; } } } return size * elem_size; } /* Transpose bytes within elements. */ int64_t bshuf_trans_byte_elem_scal(const void* in, void* out, const size_t size, const size_t elem_size) { return bshuf_trans_byte_elem_remainder(in, out, size, elem_size, 0); } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_remainder(const void* in, void* out, const size_t size, const size_t elem_size, const size_t start_byte) { const uint64_t* in_b = (const uint64_t*) in; uint8_t* out_b = (uint8_t*) out; uint64_t x, t; size_t ii, kk; size_t nbyte = elem_size * size; size_t nbyte_bitrow = nbyte / 8; uint64_t e=1; const int little_endian = *(uint8_t *) &e == 1; const size_t bit_row_skip = little_endian ? nbyte_bitrow : -nbyte_bitrow; const int64_t bit_row_offset = little_endian ? 0 : 7 * nbyte_bitrow; CHECK_MULT_EIGHT(nbyte); CHECK_MULT_EIGHT(start_byte); for (ii = start_byte / 8; ii < nbyte_bitrow; ii ++) { x = in_b[ii]; if (little_endian) { TRANS_BIT_8X8(x, t); } else { TRANS_BIT_8X8_BE(x, t); } for (kk = 0; kk < 8; kk ++) { out_b[bit_row_offset + kk * bit_row_skip + ii] = x; x = x >> 8; } } return size * elem_size; } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_scal(const void* in, void* out, const size_t size, const size_t elem_size) { return bshuf_trans_bit_byte_remainder(in, out, size, elem_size, 0); } /* General transpose of an array, optimized for large element sizes. */ int64_t bshuf_trans_elem(const void* in, void* out, const size_t lda, const size_t ldb, const size_t elem_size) { size_t ii, jj; const char* in_b = (const char*) in; char* out_b = (char*) out; for(ii = 0; ii < lda; ii++) { for(jj = 0; jj < ldb; jj++) { memcpy(&out_b[(jj*lda + ii) * elem_size], &in_b[(ii*ldb + jj) * elem_size], elem_size); } } return lda * ldb * elem_size; } /* Transpose rows of shuffled bits (size / 8 bytes) within groups of 8. */ int64_t bshuf_trans_bitrow_eight(const void* in, void* out, const size_t size, const size_t elem_size) { size_t nbyte_bitrow = size / 8; CHECK_MULT_EIGHT(size); return bshuf_trans_elem(in, out, 8, elem_size, nbyte_bitrow); } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_scal(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; void *tmp_buf; CHECK_MULT_EIGHT(size); tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_scal(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_scal(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_scal(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, jj, kk, nbyte_row; const char *in_b; char *out_b; in_b = (const char*) in; out_b = (char*) out; nbyte_row = size / 8; CHECK_MULT_EIGHT(size); for (jj = 0; jj < elem_size; jj++) { for (ii = 0; ii < nbyte_row; ii++) { for (kk = 0; kk < 8; kk++) { out_b[ii * 8 * elem_size + jj * 8 + kk] = \ in_b[(jj * 8 + kk) * nbyte_row + ii]; } } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_scal(const void* in, void* out, \ const size_t size, const size_t elem_size) { const char *in_b; char *out_b; uint64_t x, t; size_t ii, jj, kk; size_t nbyte, out_index; uint64_t e=1; const int little_endian = *(uint8_t *) &e == 1; const size_t elem_skip = little_endian ? elem_size : -elem_size; const uint64_t elem_offset = little_endian ? 0 : 7 * elem_size; CHECK_MULT_EIGHT(size); in_b = (const char*) in; out_b = (char*) out; nbyte = elem_size * size; for (jj = 0; jj < 8 * elem_size; jj += 8) { for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { x = *((uint64_t*) &in_b[ii + jj]); if (little_endian) { TRANS_BIT_8X8(x, t); } else { TRANS_BIT_8X8_BE(x, t); } for (kk = 0; kk < 8; kk++) { out_index = ii + jj / 8 + elem_offset + kk * elem_skip; *((uint8_t*) &out_b[out_index]) = x; x = x >> 8; } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_scal(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; void *tmp_buf; CHECK_MULT_EIGHT(size); tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_scal(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_scal(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* ---- Worker code that uses Arm NEON ---- * * The following code makes use of the Arm NEON instruction set. * NEON technology is the implementation of the ARM Advanced Single * Instruction Multiple Data (SIMD) extension. * The NEON unit is the component of the processor that executes SIMD instructions. * It is also called the NEON Media Processing Engine (MPE). * */ #ifdef USEARMNEON /* Transpose bytes within elements for 16 bit elements. */ int64_t bshuf_trans_byte_elem_NEON_16(const void* in, void* out, const size_t size) { size_t ii; const char *in_b = (const char*) in; char *out_b = (char*) out; int8x16_t a0, b0, a1, b1; for (ii=0; ii + 15 < size; ii += 16) { a0 = vld1q_s8(in_b + 2*ii + 0*16); b0 = vld1q_s8(in_b + 2*ii + 1*16); a1 = vzip1q_s8(a0, b0); b1 = vzip2q_s8(a0, b0); a0 = vzip1q_s8(a1, b1); b0 = vzip2q_s8(a1, b1); a1 = vzip1q_s8(a0, b0); b1 = vzip2q_s8(a0, b0); a0 = vzip1q_s8(a1, b1); b0 = vzip2q_s8(a1, b1); vst1q_s8(out_b + 0*size + ii, a0); vst1q_s8(out_b + 1*size + ii, b0); } return bshuf_trans_byte_elem_remainder(in, out, size, 2, size - size % 16); } /* Transpose bytes within elements for 32 bit elements. */ int64_t bshuf_trans_byte_elem_NEON_32(const void* in, void* out, const size_t size) { size_t ii; const char *in_b; char *out_b; in_b = (const char*) in; out_b = (char*) out; int8x16_t a0, b0, c0, d0, a1, b1, c1, d1; int64x2_t a2, b2, c2, d2; for (ii=0; ii + 15 < size; ii += 16) { a0 = vld1q_s8(in_b + 4*ii + 0*16); b0 = vld1q_s8(in_b + 4*ii + 1*16); c0 = vld1q_s8(in_b + 4*ii + 2*16); d0 = vld1q_s8(in_b + 4*ii + 3*16); a1 = vzip1q_s8(a0, b0); b1 = vzip2q_s8(a0, b0); c1 = vzip1q_s8(c0, d0); d1 = vzip2q_s8(c0, d0); a0 = vzip1q_s8(a1, b1); b0 = vzip2q_s8(a1, b1); c0 = vzip1q_s8(c1, d1); d0 = vzip2q_s8(c1, d1); a1 = vzip1q_s8(a0, b0); b1 = vzip2q_s8(a0, b0); c1 = vzip1q_s8(c0, d0); d1 = vzip2q_s8(c0, d0); a2 = vzip1q_s64(vreinterpretq_s64_s8(a1), vreinterpretq_s64_s8(c1)); b2 = vzip2q_s64(vreinterpretq_s64_s8(a1), vreinterpretq_s64_s8(c1)); c2 = vzip1q_s64(vreinterpretq_s64_s8(b1), vreinterpretq_s64_s8(d1)); d2 = vzip2q_s64(vreinterpretq_s64_s8(b1), vreinterpretq_s64_s8(d1)); vst1q_s64((int64_t *) (out_b + 0*size + ii), a2); vst1q_s64((int64_t *) (out_b + 1*size + ii), b2); vst1q_s64((int64_t *) (out_b + 2*size + ii), c2); vst1q_s64((int64_t *) (out_b + 3*size + ii), d2); } return bshuf_trans_byte_elem_remainder(in, out, size, 4, size - size % 16); } /* Transpose bytes within elements for 64 bit elements. */ int64_t bshuf_trans_byte_elem_NEON_64(const void* in, void* out, const size_t size) { size_t ii; const char* in_b = (const char*) in; char* out_b = (char*) out; int8x16_t a0, b0, c0, d0, e0, f0, g0, h0; int8x16_t a1, b1, c1, d1, e1, f1, g1, h1; for (ii=0; ii + 15 < size; ii += 16) { a0 = vld1q_s8(in_b + 8*ii + 0*16); b0 = vld1q_s8(in_b + 8*ii + 1*16); c0 = vld1q_s8(in_b + 8*ii + 2*16); d0 = vld1q_s8(in_b + 8*ii + 3*16); e0 = vld1q_s8(in_b + 8*ii + 4*16); f0 = vld1q_s8(in_b + 8*ii + 5*16); g0 = vld1q_s8(in_b + 8*ii + 6*16); h0 = vld1q_s8(in_b + 8*ii + 7*16); a1 = vzip1q_s8 (a0, b0); b1 = vzip2q_s8 (a0, b0); c1 = vzip1q_s8 (c0, d0); d1 = vzip2q_s8 (c0, d0); e1 = vzip1q_s8 (e0, f0); f1 = vzip2q_s8 (e0, f0); g1 = vzip1q_s8 (g0, h0); h1 = vzip2q_s8 (g0, h0); a0 = vzip1q_s8 (a1, b1); b0 = vzip2q_s8 (a1, b1); c0 = vzip1q_s8 (c1, d1); d0 = vzip2q_s8 (c1, d1); e0 = vzip1q_s8 (e1, f1); f0 = vzip2q_s8 (e1, f1); g0 = vzip1q_s8 (g1, h1); h0 = vzip2q_s8 (g1, h1); a1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (a0), vreinterpretq_s32_s8 (c0)); b1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (a0), vreinterpretq_s32_s8 (c0)); c1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (b0), vreinterpretq_s32_s8 (d0)); d1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (b0), vreinterpretq_s32_s8 (d0)); e1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (e0), vreinterpretq_s32_s8 (g0)); f1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (e0), vreinterpretq_s32_s8 (g0)); g1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (f0), vreinterpretq_s32_s8 (h0)); h1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (f0), vreinterpretq_s32_s8 (h0)); a0 = (int8x16_t) vzip1q_s64 (vreinterpretq_s64_s8 (a1), vreinterpretq_s64_s8 (e1)); b0 = (int8x16_t) vzip2q_s64 (vreinterpretq_s64_s8 (a1), vreinterpretq_s64_s8 (e1)); c0 = (int8x16_t) vzip1q_s64 (vreinterpretq_s64_s8 (b1), vreinterpretq_s64_s8 (f1)); d0 = (int8x16_t) vzip2q_s64 (vreinterpretq_s64_s8 (b1), vreinterpretq_s64_s8 (f1)); e0 = (int8x16_t) vzip1q_s64 (vreinterpretq_s64_s8 (c1), vreinterpretq_s64_s8 (g1)); f0 = (int8x16_t) vzip2q_s64 (vreinterpretq_s64_s8 (c1), vreinterpretq_s64_s8 (g1)); g0 = (int8x16_t) vzip1q_s64 (vreinterpretq_s64_s8 (d1), vreinterpretq_s64_s8 (h1)); h0 = (int8x16_t) vzip2q_s64 (vreinterpretq_s64_s8 (d1), vreinterpretq_s64_s8 (h1)); vst1q_s8(out_b + 0*size + ii, a0); vst1q_s8(out_b + 1*size + ii, b0); vst1q_s8(out_b + 2*size + ii, c0); vst1q_s8(out_b + 3*size + ii, d0); vst1q_s8(out_b + 4*size + ii, e0); vst1q_s8(out_b + 5*size + ii, f0); vst1q_s8(out_b + 6*size + ii, g0); vst1q_s8(out_b + 7*size + ii, h0); } return bshuf_trans_byte_elem_remainder(in, out, size, 8, size - size % 16); } /* Transpose bytes within elements using best NEON algorithm available. */ int64_t bshuf_trans_byte_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; // Trivial cases: power of 2 bytes. switch (elem_size) { case 1: count = bshuf_copy(in, out, size, elem_size); return count; case 2: count = bshuf_trans_byte_elem_NEON_16(in, out, size); return count; case 4: count = bshuf_trans_byte_elem_NEON_32(in, out, size); return count; case 8: count = bshuf_trans_byte_elem_NEON_64(in, out, size); return count; } // Worst case: odd number of bytes. Turns out that this is faster for // (odd * 2) byte elements as well (hence % 4). if (elem_size % 4) { count = bshuf_trans_byte_elem_scal(in, out, size, elem_size); return count; } // Multiple of power of 2: transpose hierarchically. { size_t nchunk_elem; void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; if ((elem_size % 8) == 0) { nchunk_elem = elem_size / 8; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int64_t); count = bshuf_trans_byte_elem_NEON_64(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 8, nchunk_elem, size); } else if ((elem_size % 4) == 0) { nchunk_elem = elem_size / 4; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int32_t); count = bshuf_trans_byte_elem_NEON_32(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 4, nchunk_elem, size); } else { // Not used since scalar algorithm is faster. nchunk_elem = elem_size / 2; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int16_t); count = bshuf_trans_byte_elem_NEON_16(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 2, nchunk_elem, size); } free(tmp_buf); return count; } } /* Creates a mask made up of the most significant * bit of each byte of 'input' */ int32_t move_byte_mask_neon(uint8x16_t input) { return ( ((input[0] & 0x80) >> 7) | (((input[1] & 0x80) >> 7) << 1) | (((input[2] & 0x80) >> 7) << 2) | (((input[3] & 0x80) >> 7) << 3) | (((input[4] & 0x80) >> 7) << 4) | (((input[5] & 0x80) >> 7) << 5) | (((input[6] & 0x80) >> 7) << 6) | (((input[7] & 0x80) >> 7) << 7) | (((input[8] & 0x80) >> 7) << 8) | (((input[9] & 0x80) >> 7) << 9) | (((input[10] & 0x80) >> 7) << 10) | (((input[11] & 0x80) >> 7) << 11) | (((input[12] & 0x80) >> 7) << 12) | (((input[13] & 0x80) >> 7) << 13) | (((input[14] & 0x80) >> 7) << 14) | (((input[15] & 0x80) >> 7) << 15) ); } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, kk; const char* in_b = (const char*) in; char* out_b = (char*) out; uint16_t* out_ui16; int64_t count; size_t nbyte = elem_size * size; CHECK_MULT_EIGHT(nbyte); int16x8_t xmm; int32_t bt; for (ii = 0; ii + 15 < nbyte; ii += 16) { xmm = vld1q_s16((int16_t *) (in_b + ii)); for (kk = 0; kk < 8; kk++) { bt = move_byte_mask_neon((uint8x16_t) xmm); xmm = vshlq_n_s16(xmm, 1); out_ui16 = (uint16_t*) &out_b[((7 - kk) * nbyte + ii) / 8]; *out_ui16 = bt; } } count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size, nbyte - nbyte % 16); return count; } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_NEON(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_NEON(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, jj; const char* in_b = (const char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(size); size_t nrows = 8 * elem_size; size_t nbyte_row = size / 8; int8x16_t a0, b0, c0, d0, e0, f0, g0, h0; int8x16_t a1, b1, c1, d1, e1, f1, g1, h1; int64x1_t *as, *bs, *cs, *ds, *es, *fs, *gs, *hs; for (ii = 0; ii + 7 < nrows; ii += 8) { for (jj = 0; jj + 15 < nbyte_row; jj += 16) { a0 = vld1q_s8(in_b + (ii + 0)*nbyte_row + jj); b0 = vld1q_s8(in_b + (ii + 1)*nbyte_row + jj); c0 = vld1q_s8(in_b + (ii + 2)*nbyte_row + jj); d0 = vld1q_s8(in_b + (ii + 3)*nbyte_row + jj); e0 = vld1q_s8(in_b + (ii + 4)*nbyte_row + jj); f0 = vld1q_s8(in_b + (ii + 5)*nbyte_row + jj); g0 = vld1q_s8(in_b + (ii + 6)*nbyte_row + jj); h0 = vld1q_s8(in_b + (ii + 7)*nbyte_row + jj); a1 = vzip1q_s8(a0, b0); b1 = vzip1q_s8(c0, d0); c1 = vzip1q_s8(e0, f0); d1 = vzip1q_s8(g0, h0); e1 = vzip2q_s8(a0, b0); f1 = vzip2q_s8(c0, d0); g1 = vzip2q_s8(e0, f0); h1 = vzip2q_s8(g0, h0); a0 = (int8x16_t) vzip1q_s16 (vreinterpretq_s16_s8 (a1), vreinterpretq_s16_s8 (b1)); b0= (int8x16_t) vzip1q_s16 (vreinterpretq_s16_s8 (c1), vreinterpretq_s16_s8 (d1)); c0 = (int8x16_t) vzip2q_s16 (vreinterpretq_s16_s8 (a1), vreinterpretq_s16_s8 (b1)); d0 = (int8x16_t) vzip2q_s16 (vreinterpretq_s16_s8 (c1), vreinterpretq_s16_s8 (d1)); e0 = (int8x16_t) vzip1q_s16 (vreinterpretq_s16_s8 (e1), vreinterpretq_s16_s8 (f1)); f0 = (int8x16_t) vzip1q_s16 (vreinterpretq_s16_s8 (g1), vreinterpretq_s16_s8 (h1)); g0 = (int8x16_t) vzip2q_s16 (vreinterpretq_s16_s8 (e1), vreinterpretq_s16_s8 (f1)); h0 = (int8x16_t) vzip2q_s16 (vreinterpretq_s16_s8 (g1), vreinterpretq_s16_s8 (h1)); a1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (a0), vreinterpretq_s32_s8 (b0)); b1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (a0), vreinterpretq_s32_s8 (b0)); c1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (c0), vreinterpretq_s32_s8 (d0)); d1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (c0), vreinterpretq_s32_s8 (d0)); e1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (e0), vreinterpretq_s32_s8 (f0)); f1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (e0), vreinterpretq_s32_s8 (f0)); g1 = (int8x16_t) vzip1q_s32 (vreinterpretq_s32_s8 (g0), vreinterpretq_s32_s8 (h0)); h1 = (int8x16_t) vzip2q_s32 (vreinterpretq_s32_s8 (g0), vreinterpretq_s32_s8 (h0)); as = (int64x1_t *) &a1; bs = (int64x1_t *) &b1; cs = (int64x1_t *) &c1; ds = (int64x1_t *) &d1; es = (int64x1_t *) &e1; fs = (int64x1_t *) &f1; gs = (int64x1_t *) &g1; hs = (int64x1_t *) &h1; vst1_s64((int64_t *)(out_b + (jj + 0) * nrows + ii), *as); vst1_s64((int64_t *)(out_b + (jj + 1) * nrows + ii), *(as + 1)); vst1_s64((int64_t *)(out_b + (jj + 2) * nrows + ii), *bs); vst1_s64((int64_t *)(out_b + (jj + 3) * nrows + ii), *(bs + 1)); vst1_s64((int64_t *)(out_b + (jj + 4) * nrows + ii), *cs); vst1_s64((int64_t *)(out_b + (jj + 5) * nrows + ii), *(cs + 1)); vst1_s64((int64_t *)(out_b + (jj + 6) * nrows + ii), *ds); vst1_s64((int64_t *)(out_b + (jj + 7) * nrows + ii), *(ds + 1)); vst1_s64((int64_t *)(out_b + (jj + 8) * nrows + ii), *es); vst1_s64((int64_t *)(out_b + (jj + 9) * nrows + ii), *(es + 1)); vst1_s64((int64_t *)(out_b + (jj + 10) * nrows + ii), *fs); vst1_s64((int64_t *)(out_b + (jj + 11) * nrows + ii), *(fs + 1)); vst1_s64((int64_t *)(out_b + (jj + 12) * nrows + ii), *gs); vst1_s64((int64_t *)(out_b + (jj + 13) * nrows + ii), *(gs + 1)); vst1_s64((int64_t *)(out_b + (jj + 14) * nrows + ii), *hs); vst1_s64((int64_t *)(out_b + (jj + 15) * nrows + ii), *(hs + 1)); } for (jj = nbyte_row - nbyte_row % 16; jj < nbyte_row; jj ++) { out_b[jj * nrows + ii + 0] = in_b[(ii + 0)*nbyte_row + jj]; out_b[jj * nrows + ii + 1] = in_b[(ii + 1)*nbyte_row + jj]; out_b[jj * nrows + ii + 2] = in_b[(ii + 2)*nbyte_row + jj]; out_b[jj * nrows + ii + 3] = in_b[(ii + 3)*nbyte_row + jj]; out_b[jj * nrows + ii + 4] = in_b[(ii + 4)*nbyte_row + jj]; out_b[jj * nrows + ii + 5] = in_b[(ii + 5)*nbyte_row + jj]; out_b[jj * nrows + ii + 6] = in_b[(ii + 6)*nbyte_row + jj]; out_b[jj * nrows + ii + 7] = in_b[(ii + 7)*nbyte_row + jj]; } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); // With a bit of care, this could be written such that such that it is // in_buf = out_buf safe. const char* in_b = (const char*) in; uint16_t* out_ui16 = (uint16_t*) out; size_t ii, jj, kk; size_t nbyte = elem_size * size; int16x8_t xmm; int32_t bt; if (elem_size % 2) { bshuf_shuffle_bit_eightelem_scal(in, out, size, elem_size); } else { for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { for (jj = 0; jj + 15 < 8 * elem_size; jj += 16) { xmm = vld1q_s16((int16_t *) &in_b[ii + jj]); for (kk = 0; kk < 8; kk++) { bt = move_byte_mask_neon((uint8x16_t) xmm); xmm = vshlq_n_s16(xmm, 1); size_t ind = (ii + jj / 8 + (7 - kk) * elem_size); out_ui16[ind / 2] = bt; } } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_NEON(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_NEON(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } #else // #ifdef USEARMNEON int64_t bshuf_untrans_bit_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_bit_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_byte_bitrow_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_bit_byte_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_byte_elem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } int64_t bshuf_trans_byte_elem_NEON_64(const void* in, void* out, const size_t size) { return -13; } int64_t bshuf_trans_byte_elem_NEON_32(const void* in, void* out, const size_t size) { return -13; } int64_t bshuf_trans_byte_elem_NEON_16(const void* in, void* out, const size_t size) { return -13; } int64_t bshuf_shuffle_bit_eightelem_NEON(const void* in, void* out, const size_t size, const size_t elem_size) { return -13; } #endif /* ---- Worker code that uses SSE2 ---- * * The following code makes use of the SSE2 instruction set and specialized * 16 byte registers. The SSE2 instructions are present on modern x86 * processors. The first Intel processor microarchitecture supporting SSE2 was * Pentium 4 (2000). * */ #ifdef USESSE2 /* Transpose bytes within elements for 16 bit elements. */ int64_t bshuf_trans_byte_elem_SSE_16(const void* in, void* out, const size_t size) { size_t ii; const char *in_b = (const char*) in; char *out_b = (char*) out; __m128i a0, b0, a1, b1; for (ii=0; ii + 15 < size; ii += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[2*ii + 0*16]); b0 = _mm_loadu_si128((__m128i *) &in_b[2*ii + 1*16]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0); _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0); } return bshuf_trans_byte_elem_remainder(in, out, size, 2, size - size % 16); } /* Transpose bytes within elements for 32 bit elements. */ int64_t bshuf_trans_byte_elem_SSE_32(const void* in, void* out, const size_t size) { size_t ii; const char *in_b; char *out_b; in_b = (const char*) in; out_b = (char*) out; __m128i a0, b0, c0, d0, a1, b1, c1, d1; for (ii=0; ii + 15 < size; ii += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 0*16]); b0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 1*16]); c0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 2*16]); d0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 3*16]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); c1 = _mm_unpacklo_epi8(c0, d0); d1 = _mm_unpackhi_epi8(c0, d0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); c0 = _mm_unpacklo_epi8(c1, d1); d0 = _mm_unpackhi_epi8(c1, d1); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); c1 = _mm_unpacklo_epi8(c0, d0); d1 = _mm_unpackhi_epi8(c0, d0); a0 = _mm_unpacklo_epi64(a1, c1); b0 = _mm_unpackhi_epi64(a1, c1); c0 = _mm_unpacklo_epi64(b1, d1); d0 = _mm_unpackhi_epi64(b1, d1); _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0); _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0); _mm_storeu_si128((__m128i *) &out_b[2*size + ii], c0); _mm_storeu_si128((__m128i *) &out_b[3*size + ii], d0); } return bshuf_trans_byte_elem_remainder(in, out, size, 4, size - size % 16); } /* Transpose bytes within elements for 64 bit elements. */ int64_t bshuf_trans_byte_elem_SSE_64(const void* in, void* out, const size_t size) { size_t ii; const char* in_b = (const char*) in; char* out_b = (char*) out; __m128i a0, b0, c0, d0, e0, f0, g0, h0; __m128i a1, b1, c1, d1, e1, f1, g1, h1; for (ii=0; ii + 15 < size; ii += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 0*16]); b0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 1*16]); c0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 2*16]); d0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 3*16]); e0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 4*16]); f0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 5*16]); g0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 6*16]); h0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 7*16]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpackhi_epi8(a0, b0); c1 = _mm_unpacklo_epi8(c0, d0); d1 = _mm_unpackhi_epi8(c0, d0); e1 = _mm_unpacklo_epi8(e0, f0); f1 = _mm_unpackhi_epi8(e0, f0); g1 = _mm_unpacklo_epi8(g0, h0); h1 = _mm_unpackhi_epi8(g0, h0); a0 = _mm_unpacklo_epi8(a1, b1); b0 = _mm_unpackhi_epi8(a1, b1); c0 = _mm_unpacklo_epi8(c1, d1); d0 = _mm_unpackhi_epi8(c1, d1); e0 = _mm_unpacklo_epi8(e1, f1); f0 = _mm_unpackhi_epi8(e1, f1); g0 = _mm_unpacklo_epi8(g1, h1); h0 = _mm_unpackhi_epi8(g1, h1); a1 = _mm_unpacklo_epi32(a0, c0); b1 = _mm_unpackhi_epi32(a0, c0); c1 = _mm_unpacklo_epi32(b0, d0); d1 = _mm_unpackhi_epi32(b0, d0); e1 = _mm_unpacklo_epi32(e0, g0); f1 = _mm_unpackhi_epi32(e0, g0); g1 = _mm_unpacklo_epi32(f0, h0); h1 = _mm_unpackhi_epi32(f0, h0); a0 = _mm_unpacklo_epi64(a1, e1); b0 = _mm_unpackhi_epi64(a1, e1); c0 = _mm_unpacklo_epi64(b1, f1); d0 = _mm_unpackhi_epi64(b1, f1); e0 = _mm_unpacklo_epi64(c1, g1); f0 = _mm_unpackhi_epi64(c1, g1); g0 = _mm_unpacklo_epi64(d1, h1); h0 = _mm_unpackhi_epi64(d1, h1); _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0); _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0); _mm_storeu_si128((__m128i *) &out_b[2*size + ii], c0); _mm_storeu_si128((__m128i *) &out_b[3*size + ii], d0); _mm_storeu_si128((__m128i *) &out_b[4*size + ii], e0); _mm_storeu_si128((__m128i *) &out_b[5*size + ii], f0); _mm_storeu_si128((__m128i *) &out_b[6*size + ii], g0); _mm_storeu_si128((__m128i *) &out_b[7*size + ii], h0); } return bshuf_trans_byte_elem_remainder(in, out, size, 8, size - size % 16); } /* Transpose bytes within elements using best SSE algorithm available. */ int64_t bshuf_trans_byte_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; // Trivial cases: power of 2 bytes. switch (elem_size) { case 1: count = bshuf_copy(in, out, size, elem_size); return count; case 2: count = bshuf_trans_byte_elem_SSE_16(in, out, size); return count; case 4: count = bshuf_trans_byte_elem_SSE_32(in, out, size); return count; case 8: count = bshuf_trans_byte_elem_SSE_64(in, out, size); return count; } // Worst case: odd number of bytes. Turns out that this is faster for // (odd * 2) byte elements as well (hence % 4). if (elem_size % 4) { count = bshuf_trans_byte_elem_scal(in, out, size, elem_size); return count; } // Multiple of power of 2: transpose hierarchically. { size_t nchunk_elem; void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; if ((elem_size % 8) == 0) { nchunk_elem = elem_size / 8; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int64_t); count = bshuf_trans_byte_elem_SSE_64(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 8, nchunk_elem, size); } else if ((elem_size % 4) == 0) { nchunk_elem = elem_size / 4; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int32_t); count = bshuf_trans_byte_elem_SSE_32(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 4, nchunk_elem, size); } else { // Not used since scalar algorithm is faster. nchunk_elem = elem_size / 2; TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int16_t); count = bshuf_trans_byte_elem_SSE_16(out, tmp_buf, size * nchunk_elem); bshuf_trans_elem(tmp_buf, out, 2, nchunk_elem, size); } free(tmp_buf); return count; } } /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, kk; const char* in_b = (const char*) in; char* out_b = (char*) out; uint16_t* out_ui16; int64_t count; size_t nbyte = elem_size * size; CHECK_MULT_EIGHT(nbyte); __m128i xmm; int32_t bt; for (ii = 0; ii + 15 < nbyte; ii += 16) { xmm = _mm_loadu_si128((__m128i *) &in_b[ii]); for (kk = 0; kk < 8; kk++) { bt = _mm_movemask_epi8(xmm); xmm = _mm_slli_epi16(xmm, 1); out_ui16 = (uint16_t*) &out_b[((7 - kk) * nbyte + ii) / 8]; *out_ui16 = bt; } } count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size, nbyte - nbyte % 16); return count; } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_SSE(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_SSE(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, jj; const char* in_b = (const char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(size); size_t nrows = 8 * elem_size; size_t nbyte_row = size / 8; __m128i a0, b0, c0, d0, e0, f0, g0, h0; __m128i a1, b1, c1, d1, e1, f1, g1, h1; __m128 *as, *bs, *cs, *ds, *es, *fs, *gs, *hs; for (ii = 0; ii + 7 < nrows; ii += 8) { for (jj = 0; jj + 15 < nbyte_row; jj += 16) { a0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 0)*nbyte_row + jj]); b0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 1)*nbyte_row + jj]); c0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 2)*nbyte_row + jj]); d0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 3)*nbyte_row + jj]); e0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 4)*nbyte_row + jj]); f0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 5)*nbyte_row + jj]); g0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 6)*nbyte_row + jj]); h0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 7)*nbyte_row + jj]); a1 = _mm_unpacklo_epi8(a0, b0); b1 = _mm_unpacklo_epi8(c0, d0); c1 = _mm_unpacklo_epi8(e0, f0); d1 = _mm_unpacklo_epi8(g0, h0); e1 = _mm_unpackhi_epi8(a0, b0); f1 = _mm_unpackhi_epi8(c0, d0); g1 = _mm_unpackhi_epi8(e0, f0); h1 = _mm_unpackhi_epi8(g0, h0); a0 = _mm_unpacklo_epi16(a1, b1); b0 = _mm_unpacklo_epi16(c1, d1); c0 = _mm_unpackhi_epi16(a1, b1); d0 = _mm_unpackhi_epi16(c1, d1); e0 = _mm_unpacklo_epi16(e1, f1); f0 = _mm_unpacklo_epi16(g1, h1); g0 = _mm_unpackhi_epi16(e1, f1); h0 = _mm_unpackhi_epi16(g1, h1); a1 = _mm_unpacklo_epi32(a0, b0); b1 = _mm_unpackhi_epi32(a0, b0); c1 = _mm_unpacklo_epi32(c0, d0); d1 = _mm_unpackhi_epi32(c0, d0); e1 = _mm_unpacklo_epi32(e0, f0); f1 = _mm_unpackhi_epi32(e0, f0); g1 = _mm_unpacklo_epi32(g0, h0); h1 = _mm_unpackhi_epi32(g0, h0); // We don't have a storeh instruction for integers, so interpret // as a float. Have a storel (_mm_storel_epi64). as = (__m128 *) &a1; bs = (__m128 *) &b1; cs = (__m128 *) &c1; ds = (__m128 *) &d1; es = (__m128 *) &e1; fs = (__m128 *) &f1; gs = (__m128 *) &g1; hs = (__m128 *) &h1; _mm_storel_pi((__m64 *) &out_b[(jj + 0) * nrows + ii], *as); _mm_storel_pi((__m64 *) &out_b[(jj + 2) * nrows + ii], *bs); _mm_storel_pi((__m64 *) &out_b[(jj + 4) * nrows + ii], *cs); _mm_storel_pi((__m64 *) &out_b[(jj + 6) * nrows + ii], *ds); _mm_storel_pi((__m64 *) &out_b[(jj + 8) * nrows + ii], *es); _mm_storel_pi((__m64 *) &out_b[(jj + 10) * nrows + ii], *fs); _mm_storel_pi((__m64 *) &out_b[(jj + 12) * nrows + ii], *gs); _mm_storel_pi((__m64 *) &out_b[(jj + 14) * nrows + ii], *hs); _mm_storeh_pi((__m64 *) &out_b[(jj + 1) * nrows + ii], *as); _mm_storeh_pi((__m64 *) &out_b[(jj + 3) * nrows + ii], *bs); _mm_storeh_pi((__m64 *) &out_b[(jj + 5) * nrows + ii], *cs); _mm_storeh_pi((__m64 *) &out_b[(jj + 7) * nrows + ii], *ds); _mm_storeh_pi((__m64 *) &out_b[(jj + 9) * nrows + ii], *es); _mm_storeh_pi((__m64 *) &out_b[(jj + 11) * nrows + ii], *fs); _mm_storeh_pi((__m64 *) &out_b[(jj + 13) * nrows + ii], *gs); _mm_storeh_pi((__m64 *) &out_b[(jj + 15) * nrows + ii], *hs); } for (jj = nbyte_row - nbyte_row % 16; jj < nbyte_row; jj ++) { out_b[jj * nrows + ii + 0] = in_b[(ii + 0)*nbyte_row + jj]; out_b[jj * nrows + ii + 1] = in_b[(ii + 1)*nbyte_row + jj]; out_b[jj * nrows + ii + 2] = in_b[(ii + 2)*nbyte_row + jj]; out_b[jj * nrows + ii + 3] = in_b[(ii + 3)*nbyte_row + jj]; out_b[jj * nrows + ii + 4] = in_b[(ii + 4)*nbyte_row + jj]; out_b[jj * nrows + ii + 5] = in_b[(ii + 5)*nbyte_row + jj]; out_b[jj * nrows + ii + 6] = in_b[(ii + 6)*nbyte_row + jj]; out_b[jj * nrows + ii + 7] = in_b[(ii + 7)*nbyte_row + jj]; } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); // With a bit of care, this could be written such that such that it is // in_buf = out_buf safe. const char* in_b = (const char*) in; uint16_t* out_ui16 = (uint16_t*) out; size_t ii, jj, kk; size_t nbyte = elem_size * size; __m128i xmm; int32_t bt; if (elem_size % 2) { bshuf_shuffle_bit_eightelem_scal(in, out, size, elem_size); } else { for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { for (jj = 0; jj + 15 < 8 * elem_size; jj += 16) { xmm = _mm_loadu_si128((__m128i *) &in_b[ii + jj]); for (kk = 0; kk < 8; kk++) { bt = _mm_movemask_epi8(xmm); xmm = _mm_slli_epi16(xmm, 1); size_t ind = (ii + jj / 8 + (7 - kk) * elem_size); out_ui16[ind / 2] = bt; } } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_SSE(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_SSE(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } #else // #ifdef USESSE2 int64_t bshuf_untrans_bit_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_bit_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_byte_bitrow_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_bit_byte_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_byte_elem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } int64_t bshuf_trans_byte_elem_SSE_64(const void* in, void* out, const size_t size) { return -11; } int64_t bshuf_trans_byte_elem_SSE_32(const void* in, void* out, const size_t size) { return -11; } int64_t bshuf_trans_byte_elem_SSE_16(const void* in, void* out, const size_t size) { return -11; } int64_t bshuf_shuffle_bit_eightelem_SSE(const void* in, void* out, const size_t size, const size_t elem_size) { return -11; } #endif // #ifdef USESSE2 /* ---- Code that requires AVX2. Intel Haswell (2013) and later. ---- */ /* ---- Worker code that uses AVX2 ---- * * The following code makes use of the AVX2 instruction set and specialized * 32 byte registers. The AVX2 instructions are present on newer x86 * processors. The first Intel processor microarchitecture supporting AVX2 was * Haswell (2013). * */ #ifdef USEAVX2 /* Transpose bits within bytes. */ int64_t bshuf_trans_bit_byte_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { size_t ii, kk; const char* in_b = (const char*) in; char* out_b = (char*) out; int32_t* out_i32; size_t nbyte = elem_size * size; int64_t count; __m256i ymm; int32_t bt; for (ii = 0; ii + 31 < nbyte; ii += 32) { ymm = _mm256_loadu_si256((__m256i *) &in_b[ii]); for (kk = 0; kk < 8; kk++) { bt = _mm256_movemask_epi8(ymm); ymm = _mm256_slli_epi16(ymm, 1); out_i32 = (int32_t*) &out_b[((7 - kk) * nbyte + ii) / 8]; *out_i32 = bt; } } count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size, nbyte - nbyte % 32); return count; } /* Transpose bits within elements. */ int64_t bshuf_trans_bit_elem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_elem_SSE(in, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bit_byte_AVX(out, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } /* For data organized into a row for each bit (8 * elem_size rows), transpose * the bytes. */ int64_t bshuf_trans_byte_bitrow_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { size_t hh, ii, jj, kk, mm; const char* in_b = (const char*) in; char* out_b = (char*) out; CHECK_MULT_EIGHT(size); size_t nrows = 8 * elem_size; size_t nbyte_row = size / 8; if (elem_size % 4) return bshuf_trans_byte_bitrow_SSE(in, out, size, elem_size); __m256i ymm_0[8]; __m256i ymm_1[8]; __m256i ymm_storeage[8][4]; for (jj = 0; jj + 31 < nbyte_row; jj += 32) { for (ii = 0; ii + 3 < elem_size; ii += 4) { for (hh = 0; hh < 4; hh ++) { for (kk = 0; kk < 8; kk ++){ ymm_0[kk] = _mm256_loadu_si256((__m256i *) &in_b[ (ii * 8 + hh * 8 + kk) * nbyte_row + jj]); } for (kk = 0; kk < 4; kk ++){ ymm_1[kk] = _mm256_unpacklo_epi8(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); ymm_1[kk + 4] = _mm256_unpackhi_epi8(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); } for (kk = 0; kk < 2; kk ++){ for (mm = 0; mm < 2; mm ++){ ymm_0[kk * 4 + mm] = _mm256_unpacklo_epi16( ymm_1[kk * 4 + mm * 2], ymm_1[kk * 4 + mm * 2 + 1]); ymm_0[kk * 4 + mm + 2] = _mm256_unpackhi_epi16( ymm_1[kk * 4 + mm * 2], ymm_1[kk * 4 + mm * 2 + 1]); } } for (kk = 0; kk < 4; kk ++){ ymm_1[kk * 2] = _mm256_unpacklo_epi32(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); ymm_1[kk * 2 + 1] = _mm256_unpackhi_epi32(ymm_0[kk * 2], ymm_0[kk * 2 + 1]); } for (kk = 0; kk < 8; kk ++){ ymm_storeage[kk][hh] = ymm_1[kk]; } } for (mm = 0; mm < 8; mm ++) { for (kk = 0; kk < 4; kk ++){ ymm_0[kk] = ymm_storeage[mm][kk]; } ymm_1[0] = _mm256_unpacklo_epi64(ymm_0[0], ymm_0[1]); ymm_1[1] = _mm256_unpacklo_epi64(ymm_0[2], ymm_0[3]); ymm_1[2] = _mm256_unpackhi_epi64(ymm_0[0], ymm_0[1]); ymm_1[3] = _mm256_unpackhi_epi64(ymm_0[2], ymm_0[3]); ymm_0[0] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 32); ymm_0[1] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 32); ymm_0[2] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 49); ymm_0[3] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 49); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 0 * 16) * nrows + ii * 8], ymm_0[0]); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 0 * 16 + 1) * nrows + ii * 8], ymm_0[1]); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 1 * 16) * nrows + ii * 8], ymm_0[2]); _mm256_storeu_si256((__m256i *) &out_b[ (jj + mm * 2 + 1 * 16 + 1) * nrows + ii * 8], ymm_0[3]); } } } for (ii = 0; ii < nrows; ii ++ ) { for (jj = nbyte_row - nbyte_row % 32; jj < nbyte_row; jj ++) { out_b[jj * nrows + ii] = in_b[ii * nbyte_row + jj]; } } return size * elem_size; } /* Shuffle bits within the bytes of eight element blocks. */ int64_t bshuf_shuffle_bit_eightelem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { CHECK_MULT_EIGHT(size); // With a bit of care, this could be written such that such that it is // in_buf = out_buf safe. const char* in_b = (const char*) in; char* out_b = (char*) out; size_t ii, jj, kk; size_t nbyte = elem_size * size; __m256i ymm; int32_t bt; if (elem_size % 4) { return bshuf_shuffle_bit_eightelem_SSE(in, out, size, elem_size); } else { for (jj = 0; jj + 31 < 8 * elem_size; jj += 32) { for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) { ymm = _mm256_loadu_si256((__m256i *) &in_b[ii + jj]); for (kk = 0; kk < 8; kk++) { bt = _mm256_movemask_epi8(ymm); ymm = _mm256_slli_epi16(ymm, 1); size_t ind = (ii + jj / 8 + (7 - kk) * elem_size); * (int32_t *) &out_b[ind] = bt; } } } } return size * elem_size; } /* Untranspose bits within elements. */ int64_t bshuf_untrans_bit_elem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; CHECK_MULT_EIGHT(size); void* tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; count = bshuf_trans_byte_bitrow_AVX(in, tmp_buf, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); count = bshuf_shuffle_bit_eightelem_AVX(tmp_buf, out, size, elem_size); free(tmp_buf); return count; } #else // #ifdef USEAVX2 int64_t bshuf_trans_bit_byte_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_trans_bit_elem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_trans_byte_bitrow_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_shuffle_bit_eightelem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } int64_t bshuf_untrans_bit_elem_AVX(const void* in, void* out, const size_t size, const size_t elem_size) { return -12; } #endif // #ifdef USEAVX2 /* ---- Drivers selecting best instruction set at compile time. ---- */ int64_t bshuf_trans_bit_elem(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; #ifdef USEAVX2 count = bshuf_trans_bit_elem_AVX(in, out, size, elem_size); #elif defined(USESSE2) count = bshuf_trans_bit_elem_SSE(in, out, size, elem_size); #elif defined(USEARMNEON) count = bshuf_trans_bit_elem_NEON(in, out, size, elem_size); #else count = bshuf_trans_bit_elem_scal(in, out, size, elem_size); #endif return count; } int64_t bshuf_untrans_bit_elem(const void* in, void* out, const size_t size, const size_t elem_size) { int64_t count; #ifdef USEAVX2 count = bshuf_untrans_bit_elem_AVX(in, out, size, elem_size); #elif defined(USESSE2) count = bshuf_untrans_bit_elem_SSE(in, out, size, elem_size); #elif defined(USEARMNEON) count = bshuf_untrans_bit_elem_NEON(in, out, size, elem_size); #else count = bshuf_untrans_bit_elem_scal(in, out, size, elem_size); #endif return count; } /* ---- Wrappers for implementing blocking ---- */ /* Wrap a function for processing a single block to process an entire buffer in * parallel. */ int64_t bshuf_blocked_wrap_fun(bshufBlockFunDef fun, const void* in, void* out, \ const size_t size, const size_t elem_size, size_t block_size, const int option) { omp_size_t ii = 0; int64_t err = 0; int64_t count, cum_count=0; size_t last_block_size; size_t leftover_bytes; size_t this_iter; char *last_in; char *last_out; ioc_chain C; ioc_init(&C, in, out); if (block_size == 0) { block_size = bshuf_default_block_size(elem_size); } if (block_size % BSHUF_BLOCKED_MULT) return -81; #if defined(_OPENMP) #pragma omp parallel for schedule(dynamic, 1) \ private(count) reduction(+ : cum_count) #endif for (ii = 0; ii < (omp_size_t)( size / block_size ); ii ++) { count = fun(&C, block_size, elem_size, option); if (count < 0) err = count; cum_count += count; } last_block_size = size % block_size; last_block_size = last_block_size - last_block_size % BSHUF_BLOCKED_MULT; if (last_block_size) { count = fun(&C, last_block_size, elem_size, option); if (count < 0) err = count; cum_count += count; } if (err < 0) return err; leftover_bytes = size % BSHUF_BLOCKED_MULT * elem_size; //this_iter; last_in = (char *) ioc_get_in(&C, &this_iter); ioc_set_next_in(&C, &this_iter, (void *) (last_in + leftover_bytes)); last_out = (char *) ioc_get_out(&C, &this_iter); ioc_set_next_out(&C, &this_iter, (void *) (last_out + leftover_bytes)); memcpy(last_out, last_in, leftover_bytes); ioc_destroy(&C); return cum_count + leftover_bytes; } /* Bitshuffle a single block. */ int64_t bshuf_bitshuffle_block(ioc_chain *C_ptr, \ const size_t size, const size_t elem_size, const int option) { size_t this_iter; const void *in; void *out; int64_t count; in = ioc_get_in(C_ptr, &this_iter); ioc_set_next_in(C_ptr, &this_iter, (void*) ((char*) in + size * elem_size)); out = ioc_get_out(C_ptr, &this_iter); ioc_set_next_out(C_ptr, &this_iter, (void *) ((char *) out + size * elem_size)); count = bshuf_trans_bit_elem(in, out, size, elem_size); return count; } /* Bitunshuffle a single block. */ int64_t bshuf_bitunshuffle_block(ioc_chain* C_ptr, \ const size_t size, const size_t elem_size, const int option) { size_t this_iter; const void *in; void *out; int64_t count; in = ioc_get_in(C_ptr, &this_iter); ioc_set_next_in(C_ptr, &this_iter, (void*) ((char*) in + size * elem_size)); out = ioc_get_out(C_ptr, &this_iter); ioc_set_next_out(C_ptr, &this_iter, (void *) ((char *) out + size * elem_size)); count = bshuf_untrans_bit_elem(in, out, size, elem_size); return count; } /* Write a 64 bit unsigned integer to a buffer in big endian order. */ void bshuf_write_uint64_BE(void* buf, uint64_t num) { int ii; uint8_t* b = (uint8_t*) buf; uint64_t pow28 = 1 << 8; for (ii = 7; ii >= 0; ii--) { b[ii] = num % pow28; num = num / pow28; } } /* Read a 64 bit unsigned integer from a buffer big endian order. */ uint64_t bshuf_read_uint64_BE(void* buf) { int ii; uint8_t* b = (uint8_t*) buf; uint64_t num = 0, pow28 = 1 << 8, cp = 1; for (ii = 7; ii >= 0; ii--) { num += b[ii] * cp; cp *= pow28; } return num; } /* Write a 32 bit unsigned integer to a buffer in big endian order. */ void bshuf_write_uint32_BE(void* buf, uint32_t num) { int ii; uint8_t* b = (uint8_t*) buf; uint32_t pow28 = 1 << 8; for (ii = 3; ii >= 0; ii--) { b[ii] = num % pow28; num = num / pow28; } } /* Read a 32 bit unsigned integer from a buffer big endian order. */ uint32_t bshuf_read_uint32_BE(const void* buf) { int ii; uint8_t* b = (uint8_t*) buf; uint32_t num = 0, pow28 = 1 << 8, cp = 1; for (ii = 3; ii >= 0; ii--) { num += b[ii] * cp; cp *= pow28; } return num; } /* ---- Public functions ---- * * See header file for description and usage. * */ size_t bshuf_default_block_size(const size_t elem_size) { // This function needs to be absolutely stable between versions. // Otherwise encoded data will not be decodable. size_t block_size = BSHUF_TARGET_BLOCK_SIZE_B / elem_size; // Ensure it is a required multiple. block_size = (block_size / BSHUF_BLOCKED_MULT) * BSHUF_BLOCKED_MULT; return MAX(block_size, BSHUF_MIN_RECOMMEND_BLOCK); } int64_t bshuf_bitshuffle(const void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_bitshuffle_block, in, out, size, elem_size, block_size, 0/*option*/); } int64_t bshuf_bitunshuffle(const void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_bitunshuffle_block, in, out, size, elem_size, block_size, 0/*option*/); } #undef TRANS_BIT_8X8 #undef TRANS_ELEM_TYPE #undef MAX #undef CHECK_MULT_EIGHT #undef CHECK_ERR_FREE #undef USESSE2 #undef USEAVX2
input.c
#include<stdlib.h> #include<sys/time.h> #include<stdio.h> #include<omp.h> #define SIZE 20 #define THRESHOLD 0.1 int main(int argc, char *argv[]) { double threshold = THRESHOLD; if (argc == 2) { sscanf(argv[1], "%lf", &threshold); } printf("Threshold: %lf\n", threshold); // Getting current time to help randomize the system srand(10); // Initializing the 2D ocean float arr[SIZE][SIZE]; int p=0, q=0; for(p=0; p < SIZE; p++) { for(q = 0; q < SIZE; q++) { arr[p][q] = rand() % (SIZE*10); } } // Printing the Input Ocean for(p = 0; p < SIZE; p++) { for(q = 0; q < SIZE; q++) { fprintf(stderr, "%.2f\t", arr[p][q]); } fprintf(stderr, "\n"); } float diff = 0; // Propagating the Ocean Waves #pragma omp parallel shared(diff) { /** fprintf(stderr, "\n Hello World by Thread # %d\n", omp_get_thread_num()); **/ int done = 0; float mydiff = 0; int loop = 0; struct timeval tvStart, tvStop; double start = (double) clock(); gettimeofday(&tvStart, 0); while(!done) { loop++; mydiff = 0; diff = 0; #pragma omp barrier int mymin = (SIZE/omp_get_num_threads())*omp_get_thread_num(); // Assuming SIZE%omp_get_num_threads()==0 int mymax = mymin + SIZE/omp_get_num_threads(); int i, j; for (i = mymin; i < mymax; i++) { // i spans from mymin (inclusive) to mymax (exclusive) for(j = 0; j < SIZE; j++) { float temp = arr[i][j]; arr[i][j] = 0.2 * (arr[i][j] + ((i+1)>=SIZE?0:arr[i+1][j]) + ((j+1)>=SIZE?0:arr[i][j+1]) + ((i-1)<0?0:arr[i-1][j]) + ((j-1)<0?0:arr[i][j-1])); mydiff += arr[i][j] < temp ? temp - arr[i][j] : arr[i][j] -temp; } } #pragma omp critical { diff += mydiff; } #pragma omp barrier if(((float)diff)/(SIZE*SIZE) < threshold || loop > 100000) { done = 1; } #pragma omp barrier } double stop = (double)clock(); gettimeofday(&tvStop, 0); fprintf(stdout, "Time taken by thread %d, for %d loops is %ld microseconds.\n",omp_get_thread_num(), loop, 1000000*(tvStop.tv_sec-tvStart.tv_sec) + (tvStop.tv_usec-tvStart.tv_usec)); } for(p = 0; p < SIZE; p++) { for(q = 0; q < SIZE; q++) { fprintf(stderr, "%.2f\t", arr[p][q]); } fprintf(stderr, "\n"); } }
openmp_task2.c
///TAFFO_TEST_ARGS -fopenmp #include <stdio.h> #define MAX_N (100) void nested_task_invocation(int index) { if (index > 0) nested_task_invocation(index-1); else #pragma omp task { printf("result: %d\n", index); } } void compute_result(int index) { nested_task_invocation(index); } int main(int argc, char *argv[]) { float array[MAX_N] __attribute__((annotate("target('array') scalar(range(0,1000) final)"))); float result __attribute__((annotate("target('result') scalar(range(0,5000) final)"))) = 0; int i; #pragma omp parallel { #pragma omp single compute_result(10); } #pragma omp parallel for for (i = 0; i < MAX_N; i++) { array[i] = i * 1.0; } for (i = 0; i < MAX_N; i++) { result += array[i]; } printf("result: %f\n", result); }
par_add_cycle.c
/****************************************************************************** * Copyright (c) 1998 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * ParAMG cycling routine * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "par_amg.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGCycle *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGAdditiveCycle( void *amg_vdata) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; /* Data Structure variables */ hypre_ParCSRMatrix **A_array; hypre_ParCSRMatrix **P_array; hypre_ParCSRMatrix **R_array; hypre_ParCSRMatrix *Lambda; hypre_ParCSRMatrix *Atilde; hypre_ParVector **F_array; hypre_ParVector **U_array; hypre_ParVector *Vtemp; hypre_ParVector *Ztemp; hypre_ParVector *Xtilde, *Rtilde; hypre_IntArray **CF_marker_array; HYPRE_Int *CF_marker; HYPRE_Int num_levels; HYPRE_Int addlvl, add_end; HYPRE_Int additive; HYPRE_Int mult_additive; HYPRE_Int simple; HYPRE_Int add_last_lvl; HYPRE_Int i, j, num_rows; HYPRE_Int n_global; HYPRE_Int rlx_order; /* Local variables */ HYPRE_Int Solve_err_flag = 0; HYPRE_Int level; HYPRE_Int coarse_grid; HYPRE_Int fine_grid; HYPRE_Int rlx_down; HYPRE_Int rlx_up; HYPRE_Int rlx_coarse; HYPRE_Int *grid_relax_type; HYPRE_Int *num_grid_sweeps; hypre_Vector **l1_norms; HYPRE_Real alpha, beta; HYPRE_Real *u_data; HYPRE_Real *v_data; hypre_Vector *l1_norms_lvl; HYPRE_Real *D_inv; HYPRE_Real *x_global; HYPRE_Real *r_global; HYPRE_Real *relax_weight; HYPRE_Real *omega; #if 0 HYPRE_Real *D_mat; HYPRE_Real *S_vec; #endif HYPRE_ANNOTATE_FUNC_BEGIN; /* Acquire data and allocate storage */ A_array = hypre_ParAMGDataAArray(amg_data); F_array = hypre_ParAMGDataFArray(amg_data); U_array = hypre_ParAMGDataUArray(amg_data); P_array = hypre_ParAMGDataPArray(amg_data); R_array = hypre_ParAMGDataRArray(amg_data); CF_marker_array = hypre_ParAMGDataCFMarkerArray(amg_data); Vtemp = hypre_ParAMGDataVtemp(amg_data); Ztemp = hypre_ParAMGDataZtemp(amg_data); num_levels = hypre_ParAMGDataNumLevels(amg_data); additive = hypre_ParAMGDataAdditive(amg_data); mult_additive = hypre_ParAMGDataMultAdditive(amg_data); simple = hypre_ParAMGDataSimple(amg_data); add_last_lvl = hypre_ParAMGDataAddLastLvl(amg_data); grid_relax_type = hypre_ParAMGDataGridRelaxType(amg_data); Lambda = hypre_ParAMGDataLambda(amg_data); Atilde = hypre_ParAMGDataAtilde(amg_data); Xtilde = hypre_ParAMGDataXtilde(amg_data); Rtilde = hypre_ParAMGDataRtilde(amg_data); l1_norms = hypre_ParAMGDataL1Norms(amg_data); D_inv = hypre_ParAMGDataDinv(amg_data); relax_weight = hypre_ParAMGDataRelaxWeight(amg_data); omega = hypre_ParAMGDataOmega(amg_data); rlx_order = hypre_ParAMGDataRelaxOrder(amg_data); num_grid_sweeps = hypre_ParAMGDataNumGridSweeps(amg_data); /* Initialize */ addlvl = hypre_max(additive, mult_additive); addlvl = hypre_max(addlvl, simple); if (add_last_lvl == -1 ) { add_end = num_levels - 1; } else { add_end = add_last_lvl; } Solve_err_flag = 0; /*--------------------------------------------------------------------- * Main loop of cycling --- multiplicative version --- V-cycle *--------------------------------------------------------------------*/ /* down cycle */ rlx_down = grid_relax_type[1]; rlx_up = grid_relax_type[2]; rlx_coarse = grid_relax_type[3]; for (level = 0; level < num_levels - 1; level++) { HYPRE_ANNOTATE_MGLEVEL_BEGIN(level); fine_grid = level; coarse_grid = level + 1; u_data = hypre_VectorData(hypre_ParVectorLocalVector(U_array[fine_grid])); v_data = hypre_VectorData(hypre_ParVectorLocalVector(Vtemp)); l1_norms_lvl = l1_norms[level]; hypre_ParVectorSetConstantValues(U_array[coarse_grid], 0.0); if (level < addlvl || level > add_end) /* multiplicative version */ { /* smoothing step */ if (rlx_down == 0) { HYPRE_Real *A_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A_array[fine_grid])); HYPRE_Int *A_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A_array[fine_grid])); num_rows = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A_array[fine_grid])); for (j = 0; j < num_grid_sweeps[1]; j++) { hypre_ParVectorCopy(F_array[fine_grid], Vtemp); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { u_data[i] = relax_weight[level] * v_data[i] / A_data[A_i[i]]; } } } else if (rlx_down != 18) { /*hypre_BoomerAMGRelax(A_array[fine_grid],F_array[fine_grid],NULL,rlx_down,0,*/ CF_marker = hypre_IntArrayData(CF_marker_array[fine_grid]); for (j = 0; j < num_grid_sweeps[1]; j++) { hypre_BoomerAMGRelaxIF(A_array[fine_grid], F_array[fine_grid], CF_marker, rlx_down, rlx_order, 1, relax_weight[fine_grid], omega[fine_grid], l1_norms[level] ? hypre_VectorData(l1_norms[level]) : NULL, U_array[fine_grid], Vtemp, Ztemp); hypre_ParVectorCopy(F_array[fine_grid], Vtemp); } } else { num_rows = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A_array[fine_grid])); for (j = 0; j < num_grid_sweeps[1]; j++) { hypre_ParVectorCopy(F_array[fine_grid], Vtemp); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { u_data[i] += v_data[i] / hypre_VectorData(l1_norms_lvl)[i]; } } } alpha = -1.0; beta = 1.0; hypre_ParCSRMatrixMatvec(alpha, A_array[fine_grid], U_array[fine_grid], beta, Vtemp); alpha = 1.0; beta = 0.0; hypre_ParCSRMatrixMatvecT(alpha, R_array[fine_grid], Vtemp, beta, F_array[coarse_grid]); } else /* additive version */ { hypre_ParVectorCopy(F_array[fine_grid], Vtemp); if (level == 0) /* compute residual */ { hypre_ParVectorCopy(Vtemp, Rtilde); hypre_ParVectorCopy(U_array[fine_grid], Xtilde); } alpha = 1.0; beta = 0.0; hypre_ParCSRMatrixMatvecT(alpha, R_array[fine_grid], Vtemp, beta, F_array[coarse_grid]); } HYPRE_ANNOTATE_MGLEVEL_END(level); } /* additive smoothing and solve coarse grid */ HYPRE_ANNOTATE_MGLEVEL_BEGIN(num_levels - 1); if (addlvl < num_levels) { if (simple > -1) { x_global = hypre_VectorData(hypre_ParVectorLocalVector(Xtilde)); r_global = hypre_VectorData(hypre_ParVectorLocalVector(Rtilde)); n_global = hypre_VectorSize(hypre_ParVectorLocalVector(Xtilde)); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n_global; i++) { x_global[i] += D_inv[i] * r_global[i]; } } else { if (num_grid_sweeps[1] > 1) { n_global = hypre_VectorSize(hypre_ParVectorLocalVector(Rtilde)); hypre_ParVector *Tmptilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); hypre_Vector *Tmptilde_local = hypre_SeqVectorCreate(n_global); hypre_SeqVectorInitialize(Tmptilde_local); hypre_ParVectorLocalVector(Tmptilde) = Tmptilde_local; hypre_ParVectorOwnsData(Tmptilde) = 1; hypre_ParCSRMatrixMatvec(1.0, Lambda, Rtilde, 0.0, Tmptilde); hypre_ParVectorScale(2.0, Rtilde); hypre_ParCSRMatrixMatvec(-1.0, Atilde, Tmptilde, 1.0, Rtilde); hypre_ParVectorDestroy(Tmptilde); } hypre_ParCSRMatrixMatvec(1.0, Lambda, Rtilde, 1.0, Xtilde); } if (addlvl == 0) { hypre_ParVectorCopy(Xtilde, U_array[0]); } } if (add_end < num_levels - 1) { fine_grid = num_levels - 1; for (j = 0; j < num_grid_sweeps[3]; j++) if (rlx_coarse == 18) hypre_ParCSRRelax(A_array[fine_grid], F_array[fine_grid], 1, 1, l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, 1.0, 1.0, 0, 0, 0, 0, U_array[fine_grid], Vtemp, Ztemp); else hypre_BoomerAMGRelaxIF(A_array[fine_grid], F_array[fine_grid], NULL, rlx_coarse, 0, 0, relax_weight[fine_grid], omega[fine_grid], l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, U_array[fine_grid], Vtemp, Ztemp); } HYPRE_ANNOTATE_MGLEVEL_END(num_levels - 1); /* up cycle */ for (level = num_levels - 1; level > 0; level--) { HYPRE_ANNOTATE_MGLEVEL_BEGIN(level); fine_grid = level - 1; coarse_grid = level; if (level <= addlvl || level > add_end + 1) /* multiplicative version */ { alpha = 1.0; beta = 1.0; hypre_ParCSRMatrixMatvec(alpha, P_array[fine_grid], U_array[coarse_grid], beta, U_array[fine_grid]); if (rlx_up != 18) { /*hypre_BoomerAMGRelax(A_array[fine_grid],F_array[fine_grid],NULL,rlx_up,0,*/ CF_marker = hypre_IntArrayData(CF_marker_array[fine_grid]); for (j = 0; j < num_grid_sweeps[2]; j++) { hypre_BoomerAMGRelaxIF(A_array[fine_grid], F_array[fine_grid], CF_marker, rlx_up, rlx_order, 2, relax_weight[fine_grid], omega[fine_grid], l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, U_array[fine_grid], Vtemp, Ztemp); } } else if (rlx_order) { CF_marker = hypre_IntArrayData(CF_marker_array[fine_grid]); HYPRE_Int loc_relax_points[2]; loc_relax_points[0] = -1; loc_relax_points[1] = 1; for (j = 0; j < num_grid_sweeps[2]; j++) { for (i = 0; i < 2; i++) { hypre_ParCSRRelax_L1_Jacobi(A_array[fine_grid], F_array[fine_grid], CF_marker, loc_relax_points[i], 1.0, l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, U_array[fine_grid], Vtemp); } } } else for (j = 0; j < num_grid_sweeps[2]; j++) hypre_ParCSRRelax(A_array[fine_grid], F_array[fine_grid], 1, 1, l1_norms[fine_grid] ? hypre_VectorData(l1_norms[fine_grid]) : NULL, 1.0, 1.0, 0, 0, 0, 0, U_array[fine_grid], Vtemp, Ztemp); } else /* additive version */ { alpha = 1.0; beta = 1.0; hypre_ParCSRMatrixMatvec(alpha, P_array[fine_grid], U_array[coarse_grid], beta, U_array[fine_grid]); } HYPRE_ANNOTATE_MGLEVEL_END(level); } HYPRE_ANNOTATE_FUNC_END; return (Solve_err_flag); } HYPRE_Int hypre_CreateLambda(void *amg_vdata) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; /* Data Structure variables */ MPI_Comm comm; hypre_ParCSRMatrix **A_array; hypre_ParVector **F_array; hypre_ParVector **U_array; hypre_ParCSRMatrix *A_tmp; hypre_ParCSRMatrix *Lambda; hypre_CSRMatrix *L_diag; hypre_CSRMatrix *L_offd; hypre_ParCSRMatrix *Atilde; hypre_CSRMatrix *Atilde_diag; hypre_CSRMatrix *Atilde_offd; HYPRE_Real *Atilde_diag_data; HYPRE_Real *Atilde_offd_data; hypre_CSRMatrix *A_tmp_diag; hypre_CSRMatrix *A_tmp_offd; hypre_ParVector *Xtilde; hypre_ParVector *Rtilde; hypre_Vector *Xtilde_local; hypre_Vector *Rtilde_local; hypre_ParCSRCommPkg *comm_pkg; hypre_ParCSRCommPkg *L_comm_pkg = NULL; hypre_ParCSRCommHandle *comm_handle; HYPRE_Real *L_diag_data; HYPRE_Real *L_offd_data; HYPRE_Real *buf_data = NULL; HYPRE_Real *tmp_data; HYPRE_Real *x_data; HYPRE_Real *r_data; hypre_Vector *l1_norms; HYPRE_Real *A_tmp_diag_data; HYPRE_Real *A_tmp_offd_data; HYPRE_Real *D_data = NULL; HYPRE_Real *D_data_offd = NULL; HYPRE_Int *L_diag_i; HYPRE_Int *L_diag_j; HYPRE_Int *L_offd_i; HYPRE_Int *L_offd_j; HYPRE_Int *Atilde_diag_i; HYPRE_Int *Atilde_diag_j; HYPRE_Int *Atilde_offd_i; HYPRE_Int *Atilde_offd_j; HYPRE_Int *A_tmp_diag_i; HYPRE_Int *A_tmp_offd_i; HYPRE_Int *A_tmp_diag_j; HYPRE_Int *A_tmp_offd_j; HYPRE_Int *L_recv_ptr = NULL; HYPRE_Int *L_send_ptr = NULL; HYPRE_Int *L_recv_procs = NULL; HYPRE_Int *L_send_procs = NULL; HYPRE_Int *L_send_map_elmts = NULL; HYPRE_Int *recv_procs; HYPRE_Int *send_procs; HYPRE_Int *send_map_elmts; HYPRE_Int *send_map_starts; HYPRE_Int *recv_vec_starts; HYPRE_Int *all_send_procs = NULL; HYPRE_Int *all_recv_procs = NULL; HYPRE_Int *remap = NULL; HYPRE_Int *level_start; HYPRE_Int addlvl; HYPRE_Int additive; HYPRE_Int mult_additive; HYPRE_Int num_levels; HYPRE_Int num_add_lvls; HYPRE_Int num_procs; HYPRE_Int num_sends, num_recvs; HYPRE_Int num_sends_L = 0; HYPRE_Int num_recvs_L = 0; HYPRE_Int send_data_L = 0; HYPRE_Int num_rows_L = 0; HYPRE_Int num_rows_tmp = 0; HYPRE_Int num_cols_offd_L = 0; HYPRE_Int num_cols_offd = 0; HYPRE_Int level, i, j, k; HYPRE_Int this_proc, cnt, cnt_diag, cnt_offd; HYPRE_Int A_cnt_diag, A_cnt_offd; HYPRE_Int cnt_recv, cnt_send, cnt_row, row_start; HYPRE_Int start_diag, start_offd, indx, cnt_map; HYPRE_Int start, j_indx, index, cnt_level; HYPRE_Int max_sends, max_recvs; HYPRE_Int ns; /* Local variables */ HYPRE_Int Solve_err_flag = 0; HYPRE_Int num_nonzeros_diag; HYPRE_Int num_nonzeros_offd; hypre_Vector **l1_norms_ptr = NULL; /*HYPRE_Real *relax_weight = NULL; HYPRE_Int relax_type; */ HYPRE_Int add_rlx; HYPRE_Int add_last_lvl, add_end; HYPRE_Real add_rlx_wt; /* Acquire data and allocate storage */ A_array = hypre_ParAMGDataAArray(amg_data); F_array = hypre_ParAMGDataFArray(amg_data); U_array = hypre_ParAMGDataUArray(amg_data); additive = hypre_ParAMGDataAdditive(amg_data); mult_additive = hypre_ParAMGDataMultAdditive(amg_data); add_last_lvl = hypre_ParAMGDataAddLastLvl(amg_data); num_levels = hypre_ParAMGDataNumLevels(amg_data); /*relax_weight = hypre_ParAMGDataRelaxWeight(amg_data); relax_type = hypre_ParAMGDataGridRelaxType(amg_data)[1];*/ comm = hypre_ParCSRMatrixComm(A_array[0]); add_rlx = hypre_ParAMGDataAddRelaxType(amg_data); add_rlx_wt = hypre_ParAMGDataAddRelaxWt(amg_data); ns = hypre_ParAMGDataNumGridSweeps(amg_data)[1]; hypre_MPI_Comm_size(comm, &num_procs); l1_norms_ptr = hypre_ParAMGDataL1Norms(amg_data); addlvl = hypre_max(additive, mult_additive); if (add_last_lvl != -1) { add_end = add_last_lvl + 1; } else { add_end = num_levels; } num_add_lvls = add_end + 1 - addlvl; level_start = hypre_CTAlloc(HYPRE_Int, num_add_lvls + 1, HYPRE_MEMORY_HOST); send_data_L = 0; num_rows_L = 0; num_cols_offd_L = 0; num_nonzeros_diag = 0; num_nonzeros_offd = 0; level_start[0] = 0; cnt = 1; max_sends = 0; max_recvs = 0; for (i = addlvl; i < add_end; i++) { A_tmp = A_array[i]; A_tmp_diag = hypre_ParCSRMatrixDiag(A_tmp); A_tmp_offd = hypre_ParCSRMatrixOffd(A_tmp); A_tmp_diag_i = hypre_CSRMatrixI(A_tmp_diag); A_tmp_offd_i = hypre_CSRMatrixI(A_tmp_offd); num_rows_tmp = hypre_CSRMatrixNumRows(A_tmp_diag); num_cols_offd = hypre_CSRMatrixNumCols(A_tmp_offd); num_rows_L += num_rows_tmp; level_start[cnt] = level_start[cnt - 1] + num_rows_tmp; cnt++; num_cols_offd_L += num_cols_offd; num_nonzeros_diag += A_tmp_diag_i[num_rows_tmp]; num_nonzeros_offd += A_tmp_offd_i[num_rows_tmp]; comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); max_sends += num_sends; if (num_sends) { send_data_L += hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); } max_recvs += hypre_ParCSRCommPkgNumRecvs(comm_pkg); } } if (max_sends >= num_procs || max_recvs >= num_procs) { max_sends = num_procs; max_recvs = num_procs; } if (max_sends) { all_send_procs = hypre_CTAlloc(HYPRE_Int, max_sends, HYPRE_MEMORY_HOST); } if (max_recvs) { all_recv_procs = hypre_CTAlloc(HYPRE_Int, max_recvs, HYPRE_MEMORY_HOST); } cnt_send = 0; cnt_recv = 0; if (max_sends || max_recvs) { if (max_sends < num_procs && max_recvs < num_procs) { for (i = addlvl; i < add_end; i++) { A_tmp = A_array[i]; comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); for (j = 0; j < num_sends; j++) { all_send_procs[cnt_send++] = send_procs[j]; } for (j = 0; j < num_recvs; j++) { all_recv_procs[cnt_recv++] = recv_procs[j]; } } } if (max_sends) { hypre_qsort0(all_send_procs, 0, max_sends - 1); num_sends_L = 1; this_proc = all_send_procs[0]; for (i = 1; i < max_sends; i++) { if (all_send_procs[i] > this_proc) { this_proc = all_send_procs[i]; all_send_procs[num_sends_L++] = this_proc; } } L_send_procs = hypre_CTAlloc(HYPRE_Int, num_sends_L, HYPRE_MEMORY_HOST); for (j = 0; j < num_sends_L; j++) { L_send_procs[j] = all_send_procs[j]; } hypre_TFree(all_send_procs, HYPRE_MEMORY_HOST); } if (max_recvs) { hypre_qsort0(all_recv_procs, 0, max_recvs - 1); num_recvs_L = 1; this_proc = all_recv_procs[0]; for (i = 1; i < max_recvs; i++) { if (all_recv_procs[i] > this_proc) { this_proc = all_recv_procs[i]; all_recv_procs[num_recvs_L++] = this_proc; } } L_recv_procs = hypre_CTAlloc(HYPRE_Int, num_recvs_L, HYPRE_MEMORY_HOST); for (j = 0; j < num_recvs_L; j++) { L_recv_procs[j] = all_recv_procs[j]; } hypre_TFree(all_recv_procs, HYPRE_MEMORY_HOST); } L_recv_ptr = hypre_CTAlloc(HYPRE_Int, num_recvs_L + 1, HYPRE_MEMORY_HOST); L_send_ptr = hypre_CTAlloc(HYPRE_Int, num_sends_L + 1, HYPRE_MEMORY_HOST); for (i = addlvl; i < add_end; i++) { A_tmp = A_array[i]; comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); } else { num_sends = 0; num_recvs = 0; } for (k = 0; k < num_sends; k++) { this_proc = hypre_BinarySearch(L_send_procs, send_procs[k], num_sends_L); L_send_ptr[this_proc + 1] += send_map_starts[k + 1] - send_map_starts[k]; } for (k = 0; k < num_recvs; k++) { this_proc = hypre_BinarySearch(L_recv_procs, recv_procs[k], num_recvs_L); L_recv_ptr[this_proc + 1] += recv_vec_starts[k + 1] - recv_vec_starts[k]; } } L_recv_ptr[0] = 0; for (i = 1; i < num_recvs_L; i++) { L_recv_ptr[i + 1] += L_recv_ptr[i]; } L_send_ptr[0] = 0; for (i = 1; i < num_sends_L; i++) { L_send_ptr[i + 1] += L_send_ptr[i]; } } else { num_recvs_L = 0; num_sends_L = 0; for (i = addlvl; i < add_end; i++) { A_tmp = A_array[i]; comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); for (j = 0; j < num_sends; j++) { this_proc = send_procs[j]; if (all_send_procs[this_proc] == 0) { num_sends_L++; } all_send_procs[this_proc] += send_map_starts[j + 1] - send_map_starts[j]; } for (j = 0; j < num_recvs; j++) { this_proc = recv_procs[j]; if (all_recv_procs[this_proc] == 0) { num_recvs_L++; } all_recv_procs[this_proc] += recv_vec_starts[j + 1] - recv_vec_starts[j]; } } } if (max_sends) { L_send_procs = hypre_CTAlloc(HYPRE_Int, num_sends_L, HYPRE_MEMORY_HOST); L_send_ptr = hypre_CTAlloc(HYPRE_Int, num_sends_L + 1, HYPRE_MEMORY_HOST); num_sends_L = 0; for (j = 0; j < num_procs; j++) { this_proc = all_send_procs[j]; if (this_proc) { L_send_procs[num_sends_L++] = j; L_send_ptr[num_sends_L] = this_proc + L_send_ptr[num_sends_L - 1]; } } } if (max_recvs) { L_recv_procs = hypre_CTAlloc(HYPRE_Int, num_recvs_L, HYPRE_MEMORY_HOST); L_recv_ptr = hypre_CTAlloc(HYPRE_Int, num_recvs_L + 1, HYPRE_MEMORY_HOST); num_recvs_L = 0; for (j = 0; j < num_procs; j++) { this_proc = all_recv_procs[j]; if (this_proc) { L_recv_procs[num_recvs_L++] = j; L_recv_ptr[num_recvs_L] = this_proc + L_recv_ptr[num_recvs_L - 1]; } } } } } if (max_sends) { hypre_TFree(all_send_procs, HYPRE_MEMORY_HOST); } if (max_recvs) { hypre_TFree(all_recv_procs, HYPRE_MEMORY_HOST); } L_diag = hypre_CSRMatrixCreate(num_rows_L, num_rows_L, num_nonzeros_diag); L_offd = hypre_CSRMatrixCreate(num_rows_L, num_cols_offd_L, num_nonzeros_offd); hypre_CSRMatrixInitialize(L_diag); hypre_CSRMatrixInitialize(L_offd); if (num_nonzeros_diag) { L_diag_data = hypre_CSRMatrixData(L_diag); L_diag_j = hypre_CSRMatrixJ(L_diag); } L_diag_i = hypre_CSRMatrixI(L_diag); if (num_nonzeros_offd) { L_offd_data = hypre_CSRMatrixData(L_offd); L_offd_j = hypre_CSRMatrixJ(L_offd); } L_offd_i = hypre_CSRMatrixI(L_offd); if (ns > 1) { Atilde_diag = hypre_CSRMatrixCreate(num_rows_L, num_rows_L, num_nonzeros_diag); Atilde_offd = hypre_CSRMatrixCreate(num_rows_L, num_cols_offd_L, num_nonzeros_offd); hypre_CSRMatrixInitialize(Atilde_diag); hypre_CSRMatrixInitialize(Atilde_offd); if (num_nonzeros_diag) { Atilde_diag_data = hypre_CSRMatrixData(Atilde_diag); Atilde_diag_j = hypre_CSRMatrixJ(Atilde_diag); } Atilde_diag_i = hypre_CSRMatrixI(Atilde_diag); if (num_nonzeros_offd) { Atilde_offd_data = hypre_CSRMatrixData(Atilde_offd); Atilde_offd_j = hypre_CSRMatrixJ(Atilde_offd); } Atilde_offd_i = hypre_CSRMatrixI(Atilde_offd); } if (num_rows_L) { D_data = hypre_CTAlloc(HYPRE_Real, num_rows_L, HYPRE_MEMORY_HOST); } if (send_data_L) { L_send_map_elmts = hypre_CTAlloc(HYPRE_Int, send_data_L, HYPRE_MEMORY_HOST); buf_data = hypre_CTAlloc(HYPRE_Real, send_data_L, HYPRE_MEMORY_HOST); } if (num_cols_offd_L) { D_data_offd = hypre_CTAlloc(HYPRE_Real, num_cols_offd_L, HYPRE_MEMORY_HOST); /*L_col_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_L);*/ remap = hypre_CTAlloc(HYPRE_Int, num_cols_offd_L, HYPRE_MEMORY_HOST); } Rtilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); Rtilde_local = hypre_SeqVectorCreate(num_rows_L); hypre_SeqVectorInitialize(Rtilde_local); hypre_ParVectorLocalVector(Rtilde) = Rtilde_local; hypre_ParVectorOwnsData(Rtilde) = 1; Xtilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); Xtilde_local = hypre_SeqVectorCreate(num_rows_L); hypre_SeqVectorInitialize(Xtilde_local); hypre_ParVectorLocalVector(Xtilde) = Xtilde_local; hypre_ParVectorOwnsData(Xtilde) = 1; x_data = hypre_VectorData(hypre_ParVectorLocalVector(Xtilde)); r_data = hypre_VectorData(hypre_ParVectorLocalVector(Rtilde)); cnt = 0; cnt_level = 0; cnt_diag = 0; cnt_offd = 0; cnt_row = 1; L_diag_i[0] = 0; L_offd_i[0] = 0; if (ns > 1) { A_cnt_diag = 0; A_cnt_offd = 0; Atilde_diag_i[0] = 0; Atilde_offd_i[0] = 0; } for (level = addlvl; level < add_end; level++) { row_start = level_start[cnt_level]; if (level != 0) { tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(F_array[level])); if (tmp_data) { hypre_TFree(tmp_data, hypre_VectorMemoryLocation(hypre_ParVectorLocalVector(F_array[level]))); } hypre_VectorData(hypre_ParVectorLocalVector(F_array[level])) = &r_data[row_start]; hypre_VectorOwnsData(hypre_ParVectorLocalVector(F_array[level])) = 0; tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(U_array[level])); if (tmp_data) { hypre_TFree(tmp_data, hypre_VectorMemoryLocation(hypre_ParVectorLocalVector(U_array[level]))); } hypre_VectorData(hypre_ParVectorLocalVector(U_array[level])) = &x_data[row_start]; hypre_VectorOwnsData(hypre_ParVectorLocalVector(U_array[level])) = 0; } cnt_level++; start_diag = L_diag_i[cnt_row - 1]; start_offd = L_offd_i[cnt_row - 1]; A_tmp = A_array[level]; A_tmp_diag = hypre_ParCSRMatrixDiag(A_tmp); A_tmp_offd = hypre_ParCSRMatrixOffd(A_tmp); comm_pkg = hypre_ParCSRMatrixCommPkg(A_tmp); A_tmp_diag_i = hypre_CSRMatrixI(A_tmp_diag); A_tmp_offd_i = hypre_CSRMatrixI(A_tmp_offd); A_tmp_diag_j = hypre_CSRMatrixJ(A_tmp_diag); A_tmp_offd_j = hypre_CSRMatrixJ(A_tmp_offd); A_tmp_diag_data = hypre_CSRMatrixData(A_tmp_diag); A_tmp_offd_data = hypre_CSRMatrixData(A_tmp_offd); num_rows_tmp = hypre_CSRMatrixNumRows(A_tmp_diag); if (comm_pkg) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); } else { num_sends = 0; num_recvs = 0; } /* Compute new combined communication package */ for (i = 0; i < num_sends; i++) { this_proc = hypre_BinarySearch(L_send_procs, send_procs[i], num_sends_L); indx = L_send_ptr[this_proc]; for (j = send_map_starts[i]; j < send_map_starts[i + 1]; j++) { L_send_map_elmts[indx++] = row_start + send_map_elmts[j]; } L_send_ptr[this_proc] = indx; } cnt_map = 0; for (i = 0; i < num_recvs; i++) { this_proc = hypre_BinarySearch(L_recv_procs, recv_procs[i], num_recvs_L); indx = L_recv_ptr[this_proc]; for (j = recv_vec_starts[i]; j < recv_vec_starts[i + 1]; j++) { remap[cnt_map++] = indx++; } L_recv_ptr[this_proc] = indx; } /* Compute Lambda */ if (add_rlx == 0) { /*HYPRE_Real rlx_wt = relax_weight[level];*/ #ifdef HYPRE_USING_OPENMP #pragma omp for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows_tmp; i++) { D_data[i] = add_rlx_wt / A_tmp_diag_data[A_tmp_diag_i[i]]; L_diag_i[cnt_row + i] = start_diag + A_tmp_diag_i[i + 1]; L_offd_i[cnt_row + i] = start_offd + A_tmp_offd_i[i + 1]; } if (ns > 1) for (i = 0; i < num_rows_tmp; i++) { Atilde_diag_i[cnt_row + i] = start_diag + A_tmp_diag_i[i + 1]; Atilde_offd_i[cnt_row + i] = start_offd + A_tmp_offd_i[i + 1]; } } else { l1_norms = l1_norms_ptr[level]; #ifdef HYPRE_USING_OPENMP #pragma omp for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows_tmp; i++) { D_data[i] = 1.0 / hypre_VectorData(l1_norms)[i]; L_diag_i[cnt_row + i] = start_diag + A_tmp_diag_i[i + 1]; L_offd_i[cnt_row + i] = start_offd + A_tmp_offd_i[i + 1]; } if (ns > 1) { for (i = 0; i < num_rows_tmp; i++) { Atilde_diag_i[cnt_row + i] = start_diag + A_tmp_diag_i[i + 1]; Atilde_offd_i[cnt_row + i] = start_offd + A_tmp_offd_i[i + 1]; } } } if (num_procs > 1) { index = 0; for (i = 0; i < num_sends; i++) { start = send_map_starts[i]; for (j = start; j < send_map_starts[i + 1]; j++) { buf_data[index++] = D_data[send_map_elmts[j]]; } } comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, buf_data, D_data_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } for (i = 0; i < num_rows_tmp; i++) { j_indx = A_tmp_diag_i[i]; if (ns > 1) { Atilde_diag_data[A_cnt_diag] = A_tmp_diag_data[j_indx]; Atilde_diag_j[A_cnt_diag++] = i + row_start; } L_diag_data[cnt_diag] = (2.0 - A_tmp_diag_data[j_indx] * D_data[i]) * D_data[i]; L_diag_j[cnt_diag++] = i + row_start; for (j = A_tmp_diag_i[i] + 1; j < A_tmp_diag_i[i + 1]; j++) { j_indx = A_tmp_diag_j[j]; L_diag_data[cnt_diag] = (- A_tmp_diag_data[j] * D_data[j_indx]) * D_data[i]; L_diag_j[cnt_diag++] = j_indx + row_start; } for (j = A_tmp_offd_i[i]; j < A_tmp_offd_i[i + 1]; j++) { j_indx = A_tmp_offd_j[j]; L_offd_data[cnt_offd] = (- A_tmp_offd_data[j] * D_data_offd[j_indx]) * D_data[i]; L_offd_j[cnt_offd++] = remap[j_indx]; } if (ns > 1) { for (j = A_tmp_diag_i[i] + 1; j < A_tmp_diag_i[i + 1]; j++) { j_indx = A_tmp_diag_j[j]; Atilde_diag_data[A_cnt_diag] = A_tmp_diag_data[j]; Atilde_diag_j[A_cnt_diag++] = j_indx + row_start; } for (j = A_tmp_offd_i[i]; j < A_tmp_offd_i[i + 1]; j++) { j_indx = A_tmp_offd_j[j]; Atilde_offd_data[A_cnt_offd] = A_tmp_offd_data[j]; Atilde_offd_j[A_cnt_offd++] = remap[j_indx]; } } } cnt_row += num_rows_tmp; } if (L_send_ptr) { for (i = num_sends_L - 1; i > 0; i--) { L_send_ptr[i] = L_send_ptr[i - 1]; } L_send_ptr[0] = 0; } else { L_send_ptr = hypre_CTAlloc(HYPRE_Int, 1, HYPRE_MEMORY_HOST); } if (L_recv_ptr) { for (i = num_recvs_L - 1; i > 0; i--) { L_recv_ptr[i] = L_recv_ptr[i - 1]; } L_recv_ptr[0] = 0; } else { L_recv_ptr = hypre_CTAlloc(HYPRE_Int, 1, HYPRE_MEMORY_HOST); } L_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgNumRecvs(L_comm_pkg) = num_recvs_L; hypre_ParCSRCommPkgNumSends(L_comm_pkg) = num_sends_L; hypre_ParCSRCommPkgRecvProcs(L_comm_pkg) = L_recv_procs; hypre_ParCSRCommPkgSendProcs(L_comm_pkg) = L_send_procs; hypre_ParCSRCommPkgRecvVecStarts(L_comm_pkg) = L_recv_ptr; hypre_ParCSRCommPkgSendMapStarts(L_comm_pkg) = L_send_ptr; hypre_ParCSRCommPkgSendMapElmts(L_comm_pkg) = L_send_map_elmts; hypre_ParCSRCommPkgComm(L_comm_pkg) = comm; Lambda = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDiag(Lambda) = L_diag; hypre_ParCSRMatrixOffd(Lambda) = L_offd; hypre_ParCSRMatrixCommPkg(Lambda) = L_comm_pkg; hypre_ParCSRMatrixComm(Lambda) = comm; hypre_ParCSRMatrixOwnsData(Lambda) = 1; if (ns > 1) { /*hypre_ParCSRCommPkg *A_comm_pkg = NULL; HYPRE_Int *A_recv_ptr = NULL; HYPRE_Int *A_send_ptr = NULL; HYPRE_Int *A_recv_procs = NULL; HYPRE_Int *A_send_procs = NULL; HYPRE_Int *A_send_map_elmts = NULL; A_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); A_recv_ptr = hypre_CTAlloc(HYPRE_Int, num_recvs+1, HYPRE_MEMORY_HOST); A_send_ptr = hypre_CTAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); A_recv_procs = hypre_CTAlloc(HYPRE_Int, num_recvs_L, HYPRE_MEMORY_HOST); A_send_procs = hypre_CTAlloc(HYPRE_Int, num_sends_L, HYPRE_MEMORY_HOST); A_send_map_elmts = hypre_CTAlloc(HYPRE_Int, L_send_ptr[num_sends_L], HYPRE_MEMORY_HOST); for (i=0; i<num_recvs_L+1; i++) A_recv_ptr[i] = L_recv_ptr[i]; for (i=0; i<num_sends_L+1; i++) A_send_ptr[i] = L_send_ptr[i]; for (i=0; i<num_recvs_L; i++) A_recv_procs[i] = L_recv_procs[i]; for (i=0; i<num_sends_L; i++) A_send_procs[i] = L_send_procs[i]; for (i=0; i < L_send_ptr[num_sends_L]; i++) A_send_map_elmts[i] = L_send_map_elmts[i]; hypre_ParCSRCommPkgNumRecvs(A_comm_pkg) = num_recvs_L; hypre_ParCSRCommPkgNumSends(A_comm_pkg) = num_sends_L; hypre_ParCSRCommPkgRecvProcs(A_comm_pkg) = A_recv_procs; hypre_ParCSRCommPkgSendProcs(A_comm_pkg) = A_send_procs; hypre_ParCSRCommPkgRecvVecStarts(A_comm_pkg) = A_recv_ptr; hypre_ParCSRCommPkgSendMapStarts(A_comm_pkg) = A_send_ptr; hypre_ParCSRCommPkgSendMapElmts(A_comm_pkg) = A_send_map_elmts; hypre_ParCSRCommPkgComm(A_comm_pkg) = comm; */ Atilde = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDiag(Atilde) = Atilde_diag; hypre_ParCSRMatrixOffd(Atilde) = Atilde_offd; hypre_ParCSRMatrixCommPkg(Atilde) = L_comm_pkg; hypre_ParCSRMatrixComm(Atilde) = comm; hypre_ParCSRMatrixOwnsData(Atilde) = 1; hypre_ParAMGDataAtilde(amg_data) = Atilde; } hypre_ParAMGDataLambda(amg_data) = Lambda; hypre_ParAMGDataRtilde(amg_data) = Rtilde; hypre_ParAMGDataXtilde(amg_data) = Xtilde; hypre_TFree(D_data_offd, HYPRE_MEMORY_HOST); hypre_TFree(D_data, HYPRE_MEMORY_HOST); if (num_procs > 1) { hypre_TFree(buf_data, HYPRE_MEMORY_HOST); } hypre_TFree(remap, HYPRE_MEMORY_HOST); hypre_TFree(buf_data, HYPRE_MEMORY_HOST); hypre_TFree(level_start, HYPRE_MEMORY_HOST); return Solve_err_flag; } HYPRE_Int hypre_CreateDinv(void *amg_vdata) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; /* Data Structure variables */ hypre_ParCSRMatrix **A_array; hypre_ParVector **F_array; hypre_ParVector **U_array; hypre_ParCSRMatrix *A_tmp; hypre_CSRMatrix *A_tmp_diag; hypre_ParVector *Xtilde; hypre_ParVector *Rtilde; hypre_Vector *Xtilde_local; hypre_Vector *Rtilde_local; HYPRE_Real *x_data; HYPRE_Real *r_data; HYPRE_Real *tmp_data; HYPRE_Real *D_inv = NULL; /*HYPRE_Real *relax_weight = NULL; HYPRE_Real relax_type;*/ HYPRE_Int addlvl; HYPRE_Int num_levels; HYPRE_Int num_rows_L; HYPRE_Int num_rows_tmp; HYPRE_Int level, i; HYPRE_Int add_rlx; HYPRE_Real add_rlx_wt; HYPRE_Int add_last_lvl, add_end; /* Local variables */ HYPRE_Int Solve_err_flag = 0; hypre_Vector **l1_norms_ptr = NULL; hypre_Vector *l1_norms; HYPRE_Int l1_start; /* Acquire data and allocate storage */ A_array = hypre_ParAMGDataAArray(amg_data); F_array = hypre_ParAMGDataFArray(amg_data); U_array = hypre_ParAMGDataUArray(amg_data); addlvl = hypre_ParAMGDataSimple(amg_data); num_levels = hypre_ParAMGDataNumLevels(amg_data); add_rlx_wt = hypre_ParAMGDataAddRelaxWt(amg_data); add_rlx = hypre_ParAMGDataAddRelaxType(amg_data); add_last_lvl = hypre_ParAMGDataAddLastLvl(amg_data); /*relax_weight = hypre_ParAMGDataRelaxWeight(amg_data); relax_type = hypre_ParAMGDataGridRelaxType(amg_data)[1];*/ l1_norms_ptr = hypre_ParAMGDataL1Norms(amg_data); /* smooth_option = hypre_ParAMGDataSmoothOption(amg_data); */ if (add_last_lvl == -1 ) { add_end = num_levels; } else { add_end = add_last_lvl; } num_rows_L = 0; for (i = addlvl; i < add_end; i++) { A_tmp = A_array[i]; A_tmp_diag = hypre_ParCSRMatrixDiag(A_tmp); num_rows_tmp = hypre_CSRMatrixNumRows(A_tmp_diag); num_rows_L += num_rows_tmp; } Rtilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); Rtilde_local = hypre_SeqVectorCreate(num_rows_L); hypre_SeqVectorInitialize(Rtilde_local); hypre_ParVectorLocalVector(Rtilde) = Rtilde_local; hypre_ParVectorOwnsData(Rtilde) = 1; Xtilde = hypre_CTAlloc(hypre_ParVector, 1, HYPRE_MEMORY_HOST); Xtilde_local = hypre_SeqVectorCreate(num_rows_L); hypre_SeqVectorInitialize(Xtilde_local); hypre_ParVectorLocalVector(Xtilde) = Xtilde_local; hypre_ParVectorOwnsData(Xtilde) = 1; x_data = hypre_VectorData(hypre_ParVectorLocalVector(Xtilde)); r_data = hypre_VectorData(hypre_ParVectorLocalVector(Rtilde)); D_inv = hypre_CTAlloc(HYPRE_Real, num_rows_L, HYPRE_MEMORY_HOST); l1_start = 0; for (level = addlvl; level < add_end; level++) { if (level != 0) { tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(F_array[level])); if (tmp_data) { hypre_TFree(tmp_data, hypre_VectorMemoryLocation(hypre_ParVectorLocalVector(F_array[level]))); } hypre_VectorData(hypre_ParVectorLocalVector(F_array[level])) = &r_data[l1_start]; hypre_VectorOwnsData(hypre_ParVectorLocalVector(F_array[level])) = 0; tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(U_array[level])); if (tmp_data) { hypre_TFree(tmp_data, hypre_VectorMemoryLocation(hypre_ParVectorLocalVector(U_array[level]))); } hypre_VectorData(hypre_ParVectorLocalVector(U_array[level])) = &x_data[l1_start]; hypre_VectorOwnsData(hypre_ParVectorLocalVector(U_array[level])) = 0; } A_tmp = A_array[level]; A_tmp_diag = hypre_ParCSRMatrixDiag(A_tmp); num_rows_tmp = hypre_CSRMatrixNumRows(A_tmp_diag); if (add_rlx == 0) { /*HYPRE_Real rlx_wt = relax_weight[level];*/ HYPRE_Int *A_tmp_diag_i = hypre_CSRMatrixI(A_tmp_diag); HYPRE_Real *A_tmp_diag_data = hypre_CSRMatrixData(A_tmp_diag); #ifdef HYPRE_USING_OPENMP #pragma omp for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows_tmp; i++) { D_inv[l1_start + i] = add_rlx_wt / A_tmp_diag_data[A_tmp_diag_i[i]]; } } else { l1_norms = l1_norms_ptr[level]; #ifdef HYPRE_USING_OPENMP #pragma omp for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows_tmp; i++) { D_inv[l1_start + i] = 1.0 / hypre_VectorData(l1_norms)[i]; } } l1_start += num_rows_tmp; } hypre_ParAMGDataDinv(amg_data) = D_inv; hypre_ParAMGDataRtilde(amg_data) = Rtilde; hypre_ParAMGDataXtilde(amg_data) = Xtilde; return Solve_err_flag; }
GB_binop__islt_int16.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__islt_int16) // A.*B function (eWiseMult): GB (_AemultB_01__islt_int16) // A.*B function (eWiseMult): GB (_AemultB_02__islt_int16) // A.*B function (eWiseMult): GB (_AemultB_03__islt_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__islt_int16) // A*D function (colscale): GB (_AxD__islt_int16) // D*A function (rowscale): GB (_DxB__islt_int16) // C+=B function (dense accum): GB (_Cdense_accumB__islt_int16) // C+=b function (dense accum): GB (_Cdense_accumb__islt_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__islt_int16) // C=scalar+B GB (_bind1st__islt_int16) // C=scalar+B' GB (_bind1st_tran__islt_int16) // C=A+scalar GB (_bind2nd__islt_int16) // C=A'+scalar GB (_bind2nd_tran__islt_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_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) \ int16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x < y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISLT || GxB_NO_INT16 || GxB_NO_ISLT_INT16) //------------------------------------------------------------------------------ // 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__islt_int16) ( 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__islt_int16) ( 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__islt_int16) ( 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 int16_t int16_t bwork = (*((int16_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__islt_int16) ( 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 int16_t *restrict Cx = (int16_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__islt_int16) ( 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 int16_t *restrict Cx = (int16_t *) 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__islt_int16) ( 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__islt_int16) ( 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__islt_int16) ( 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__islt_int16) ( 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__islt_int16) ( 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__islt_int16) ( 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 int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_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 ; int16_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__islt_int16) ( 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 ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB (_bind1st_tran__islt_int16) ( 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 \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB (_bind2nd_tran__islt_int16) ( 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 int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_AxB_saxpy3_template.c
//------------------------------------------------------------------------------ // GB_AxB_saxpy3_template: C=A*B, C<M>=A*B, or C<!M>=A*B via saxpy3 method //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // GB_AxB_saxpy3_template.c computes C=A*B for any semiring and matrix types. // It is #include'd in GB_AxB_saxpy3 to construct the generic method (for // arbitary user-defined operators and/or typecasting), and in the hard-coded // GB_Asaxpy3B* workers in the Generated/ folder. #include "GB_unused.h" //------------------------------------------------------------------------------ // template code for C=A*B via the saxpy3 method //------------------------------------------------------------------------------ { //-------------------------------------------------------------------------- // get the chunk size //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; //-------------------------------------------------------------------------- // get M, A, B, and C //-------------------------------------------------------------------------- int64_t *GB_RESTRICT Cp = C->p ; // const int64_t *GB_RESTRICT Ch = C->h ; const int64_t cvlen = C->vlen ; const int64_t cnvec = C->nvec ; const int64_t *GB_RESTRICT Bp = B->p ; const int64_t *GB_RESTRICT Bh = B->h ; const int64_t *GB_RESTRICT Bi = B->i ; const GB_BTYPE *GB_RESTRICT Bx = B_is_pattern ? NULL : B->x ; // const int64_t bvlen = B->vlen ; // const int64_t bnvec = B->nvec ; // const bool B_is_hyper = B->is_hyper ; const int64_t *GB_RESTRICT Ap = A->p ; const int64_t *GB_RESTRICT Ah = A->h ; const int64_t *GB_RESTRICT Ai = A->i ; const int64_t anvec = A->nvec ; const bool A_is_hyper = GB_IS_HYPER (A) ; const GB_ATYPE *GB_RESTRICT Ax = A_is_pattern ? NULL : A->x ; const int64_t *GB_RESTRICT Mp = NULL ; const int64_t *GB_RESTRICT Mh = NULL ; const int64_t *GB_RESTRICT Mi = NULL ; const GB_void *GB_RESTRICT Mx = NULL ; size_t msize = 0 ; int64_t mnvec = 0 ; bool M_is_hyper = false ; if (M != NULL) { Mp = M->p ; Mh = M->h ; Mi = M->i ; Mx = (Mask_struct ? NULL : (M->x)) ; msize = M->type->size ; mnvec = M->nvec ; M_is_hyper = M->is_hyper ; } // 3 cases: // M not present and Mask_comp false: compute C=A*B // M present and Mask_comp false: compute C<M>=A*B // M present and Mask_comp true : compute C<!M>=A*B // If M is NULL on input, then Mask_comp is also false on input. bool mask_is_M = (M != NULL && !Mask_comp) ; //========================================================================== // phase2: numeric work for fine tasks //========================================================================== // Coarse tasks: nothing to do in phase2. // Fine tasks: compute nnz (C(:,j)), and values in Hx via atomics. int taskid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (taskid = 0 ; taskid < nfine ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- int64_t kk = TaskList [taskid].vector ; int64_t hash_size = TaskList [taskid].hsize ; bool use_Gustavson = (hash_size == cvlen) ; int64_t pB = TaskList [taskid].start ; int64_t pB_end = TaskList [taskid].end + 1 ; #if !GB_IS_ANY_PAIR_SEMIRING GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ; #endif int64_t pleft = 0, pright = anvec-1 ; if (use_Gustavson) { //------------------------------------------------------------------ // phase2: fine Gustavson task //------------------------------------------------------------------ // Hf [i] == 0: unlocked, i has not been seen in C(:,j). // Hx [i] is not initialized. // M(i,j) is 0, or M is not present. // if M: Hf [i] stays equal to 0 (or 3 if locked) // if !M, or no M: C(i,j) is a new entry seen for 1st time // Hf [i] == 1: unlocked, i has not been seen in C(:,j). // Hx [i] is not initialized. M is present. // M(i,j) is 1. (either M or !M case) // if M: C(i,j) is a new entry seen for the first time. // if !M: Hf [i] stays equal to 1 (or 3 if locked) // Hf [i] == 2: unlocked, i has been seen in C(:,j). // Hx [i] is initialized. This case is independent of M. // Hf [i] == 3: locked. Hx [i] cannot be accessed. uint8_t *GB_RESTRICT Hf = TaskList [taskid].Hf ; if (M == NULL) { //-------------------------------------------------------------- // phase2: fine Gustavson task, C=A*B //-------------------------------------------------------------- // Hf [i] is initially 0. // 0 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j) uint8_t f ; #if GB_IS_ANY_MONOID GB_ATOMIC_READ f = Hf [i] ; // grab the entry if (f == 2) continue ; // check if already updated GB_ATOMIC_WRITE Hf [i] = 2 ; // flag the entry GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t #else #if GB_HAS_ATOMIC GB_ATOMIC_READ f = Hf [i] ; // grab the entry if (f == 2) // if true, update C(i,j) { GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t continue ; // C(i,j) has been updated } #endif do // lock the entry { GB_ATOMIC_CAPTURE { f = Hf [i] ; Hf [i] = 3 ; } } while (f == 3) ; // lock owner gets f=0 or 2 if (f == 0) { // C(i,j) is a new entry GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t } else // f == 2 { // C(i,j) already appears in C(:,j) GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t } GB_ATOMIC_WRITE Hf [i] = 2 ; // unlock the entry #endif } } } else if (mask_is_M) { //-------------------------------------------------------------- // phase2: fine Gustavson task, C<M>=A*B //-------------------------------------------------------------- // Hf [i] is 0 if M(i,j) not present or M(i,j)=0. // 0 -> 1 : has already been done in phase0 if M(i,j)=1 // 0 -> 0 : to ignore, if M(i,j)=0 // 1 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen GB_GET_M_j ; // get M(:,j) GB_GET_M_j_RANGE (16) ; // get first and last in M(:,j) for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #if GB_IS_ANY_MONOID #define GB_IKJ \ uint8_t f ; \ GB_ATOMIC_READ \ f = Hf [i] ; /* grab the entry */ \ if (f == 0 || f == 2) continue ; \ GB_ATOMIC_WRITE \ Hf [i] = 2 ; /* unlock the entry */ \ GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \ GB_ATOMIC_WRITE_HX (i, t) ; /* Hx [i] = t */ #else #define GB_IKJ \ { \ GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \ uint8_t f ; \ GB_ATOMIC_READ \ f = Hf [i] ; /* grab the entry */ \ if (GB_HAS_ATOMIC && (f == 2)) \ { \ /* C(i,j) already seen; update it */ \ GB_ATOMIC_UPDATE_HX (i, t) ; /* Hx [i] += t */ \ continue ; /* C(i,j) has been updated */ \ } \ if (f == 0) continue ; /* M(i,j)=0; ignore C(i,j)*/ \ do /* lock the entry */ \ { \ GB_ATOMIC_CAPTURE \ { \ f = Hf [i] ; Hf [i] = 3 ; \ } \ } while (f == 3) ; /* lock owner gets f=1 or 2 */ \ if (f == 1) \ { \ /* C(i,j) is a new entry */ \ GB_ATOMIC_WRITE_HX (i, t) ; /* Hx [i] = t */ \ } \ else /* f == 2 */ \ { \ /* C(i,j) already appears in C(:,j) */ \ GB_ATOMIC_UPDATE_HX (i, t) ; /* Hx [i] += t */ \ } \ GB_ATOMIC_WRITE \ Hf [i] = 2 ; /* unlock the entry */ \ } #endif #define GB_IKJ_VECTORIZE #define GB_IKJ_IVDEP GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ_VECTORIZE #undef GB_IKJ_IVDEP #undef GB_IKJ } } else { //-------------------------------------------------------------- // phase2: fine Gustavson task, C<!M>=A*B //-------------------------------------------------------------- // Hf [i] is 0 if M(i,j) not present or M(i,j)=0. // 0 -> 1 : has already been done in phase0 if M(i,j)=1 // 1 -> 1 : to ignore, if M(i,j)=1 // 0 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j) uint8_t f ; #if GB_IS_ANY_MONOID GB_ATOMIC_READ f = Hf [i] ; // grab the entry if (f == 1 || f == 2) continue ; GB_ATOMIC_WRITE Hf [i] = 2 ; // unlock the entry GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t #else GB_ATOMIC_READ f = Hf [i] ; // grab the entry #if GB_HAS_ATOMIC if (f == 2) // if true, update C(i,j) { GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t continue ; // C(i,j) has been updated } #endif if (f == 1) continue ; // M(i,j)=1; ignore C(i,j) do // lock the entry { GB_ATOMIC_CAPTURE { f = Hf [i] ; Hf [i] = 3 ; } } while (f == 3) ; // lock owner of gets f=0 or 2 if (f == 0) { // C(i,j) is a new entry GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t } else // f == 2 { // C(i,j) already seen GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t } GB_ATOMIC_WRITE Hf [i] = 2 ; // unlock the entry #endif } } } } else { //------------------------------------------------------------------ // phase2: fine hash task //------------------------------------------------------------------ // Each hash entry Hf [hash] splits into two parts, (h,f). f // is in the 2 least significant bits. h is 62 bits, and is // the 1-based index i of the C(i,j) entry stored at that // location in the hash table. // If M is present (M or !M), and M(i,j)=1, then (i+1,1) // has been inserted into the hash table, in phase0. // Given Hf [hash] split into (h,f) // h == 0, f == 0: unlocked and unoccupied. // note that if f=0, h must be zero too. // h == i+1, f == 1: unlocked, occupied by M(i,j)=1. // C(i,j) has not been seen, or is ignored. // Hx is not initialized. M is present. // if !M: this entry will be ignored in C. // h == i+1, f == 2: unlocked, occupied by C(i,j). // Hx is initialized. M is no longer // relevant. // h == (anything), f == 3: locked. int64_t *GB_RESTRICT Hf = TaskList [taskid].Hf ; int64_t hash_bits = (hash_size-1) ; if (M == NULL) { //-------------------------------------------------------------- // phase2: fine hash task, C=A*B //-------------------------------------------------------------- // Given Hf [hash] split into (h,f) // h == 0 , f == 0 : unlocked and unoccupied. // h == i+1, f == 2 : unlocked, occupied by C(i,j). // Hx is initialized. // h == ..., f == 3 : locked. // 0 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j) int64_t i1 = i + 1 ; // i1 = one-based index int64_t i_unlocked = (i1 << 2) + 2 ; // (i+1,2) for (GB_HASH (i)) // find i in hash table { int64_t hf ; GB_ATOMIC_READ hf = Hf [hash] ; // grab the entry #if GB_HAS_ATOMIC if (hf == i_unlocked) // if true, update C(i,j) { GB_ATOMIC_UPDATE_HX (hash, t) ;// Hx [.]+=t break ; // C(i,j) has been updated } #endif int64_t h = (hf >> 2) ; if (h == 0 || h == i1) { // h=0: unoccupied, h=i1: occupied by i do // lock the entry { GB_ATOMIC_CAPTURE { hf = Hf [hash] ; Hf [hash] |= 3 ; } } while ((hf & 3) == 3) ; // owner: f=0 or 2 if (hf == 0) // f == 0 { // C(i,j) is a new entry in C(:,j) // Hx [hash] = t GB_ATOMIC_WRITE_HX (hash, t) ; GB_ATOMIC_WRITE Hf [hash] = i_unlocked ; // unlock entry break ; } if (hf == i_unlocked) // f == 2 { // C(i,j) already appears in C(:,j) // Hx [hash] += t GB_ATOMIC_UPDATE_HX (hash, t) ; GB_ATOMIC_WRITE Hf [hash] = i_unlocked ; // unlock entry break ; } // hash table occupied, but not with i GB_ATOMIC_WRITE Hf [hash] = hf ; // unlock with prior value } } } } } else if (mask_is_M) { //-------------------------------------------------------------- // phase2: fine hash task, C<M>=A*B //-------------------------------------------------------------- // Given Hf [hash] split into (h,f) // h == 0 , f == 0 : unlocked, unoccupied. C(i,j) ignored // h == i+1, f == 1 : unlocked, occupied by M(i,j)=1. // C(i,j) has not been seen. // Hx is not initialized. // h == i+1, f == 2 : unlocked, occupied by C(i,j), M(i,j)=1 // Hx is initialized. // h == ..., f == 3 : locked. // 0 -> 0 : to ignore, if M(i,j)=0 // 1 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen GB_GET_M_j ; // get M(:,j) GB_GET_M_j_RANGE (16) ; // get first and last in M(:,j) for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #define GB_IKJ_VECTORIZE #define GB_IKJ_IVDEP #define GB_IKJ \ { \ GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \ int64_t i1 = i + 1 ; /* i1 = one-based index */ \ int64_t i_unlocked = (i1 << 2) + 2 ; /* (i+1,2) */ \ for (GB_HASH (i)) /* find i in hash table */ \ { \ int64_t hf ; \ GB_ATOMIC_READ \ hf = Hf [hash] ; /* grab the entry */ \ if (GB_HAS_ATOMIC && (hf == i_unlocked)) \ { \ /* Hx [hash] += t */ \ GB_ATOMIC_UPDATE_HX (hash, t) ; \ break ; /* C(i,j) has been updated */ \ } \ if (hf == 0) break ; /* M(i,j)=0; ignore Cij */ \ if ((hf >> 2) == i1) /* if true, i found */ \ { \ do /* lock the entry */ \ { \ GB_ATOMIC_CAPTURE \ { \ hf = Hf [hash] ; Hf [hash] |= 3 ; \ } \ } while ((hf & 3) == 3) ; /* own: f=1,2 */ \ if ((hf & 3) == 1) /* f == 1 */ \ { \ /* C(i,j) is a new entry in C(:,j) */ \ /* Hx [hash] = t */ \ GB_ATOMIC_WRITE_HX (hash, t) ; \ } \ else /* f == 2 */ \ { \ /* C(i,j) already appears in C(:,j) */ \ /* Hx [hash] += t */ \ GB_ATOMIC_UPDATE_HX (hash, t) ; \ } \ GB_ATOMIC_WRITE \ Hf [hash] = i_unlocked ; /* unlock entry */ \ break ; \ } \ } \ } GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ_VECTORIZE #undef GB_IKJ_IVDEP #undef GB_IKJ } } else { //-------------------------------------------------------------- // phase2: fine hash task, C<!M>=A*B //-------------------------------------------------------------- // Given Hf [hash] split into (h,f) // h == 0 , f == 0 : unlocked and unoccupied. // h == i+1, f == 1 : unlocked, occupied by M(i,j)=1. // C(i,j) is ignored. // h == i+1, f == 2 : unlocked, occupied by C(i,j). // Hx is initialized. // h == (anything), f == 3: locked. // 1 -> 1 : to ignore, if M(i,j)=1 // 0 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j) int64_t i1 = i + 1 ; // i1 = one-based index int64_t i_unlocked = (i1 << 2) + 2 ; // (i+1,2) int64_t i_masked = (i1 << 2) + 1 ; // (i+1,1) for (GB_HASH (i)) // find i in hash table { int64_t hf ; GB_ATOMIC_READ hf = Hf [hash] ; // grab the entry #if GB_HAS_ATOMIC if (hf == i_unlocked) // if true, update C(i,j) { GB_ATOMIC_UPDATE_HX (hash, t) ;// Hx [.]+=t break ; // C(i,j) has been updated } #endif if (hf == i_masked) break ; // M(i,j)=1; ignore int64_t h = (hf >> 2) ; if (h == 0 || h == i1) { // h=0: unoccupied, h=i1: occupied by i do // lock the entry { GB_ATOMIC_CAPTURE { hf = Hf [hash] ; Hf [hash] |= 3 ; } } while ((hf & 3) == 3) ; // owner: f=0,1,2 if (hf == 0) // f == 0 { // C(i,j) is a new entry in C(:,j) // Hx [hash] = t GB_ATOMIC_WRITE_HX (hash, t) ; GB_ATOMIC_WRITE Hf [hash] = i_unlocked ; // unlock entry break ; } if (hf == i_unlocked) // f == 2 { // C(i,j) already appears in C(:,j) // Hx [hash] += t GB_ATOMIC_UPDATE_HX (hash, t) ; GB_ATOMIC_WRITE Hf [hash] = i_unlocked ; // unlock entry break ; } // hash table occupied, but not with i, // or with i but M(i,j)=1 so C(i,j) ignored GB_ATOMIC_WRITE Hf [hash] = hf ; // unlock with prior value } } } } } } } //========================================================================== // phase3/phase4: count nnz(C(:,j)) for fine tasks, cumsum of Cp //========================================================================== int64_t cjnz_max = GB_AxB_saxpy3_cumsum (C, TaskList, nfine, chunk, nthreads) ; //========================================================================== // phase5: numeric phase for coarse tasks, gather for fine tasks //========================================================================== // allocate Ci and Cx int64_t cnz = Cp [cnvec] ; GrB_Info info = GB_ix_alloc (C, cnz, true, Context) ; if (info != GrB_SUCCESS) { // out of memory return (GrB_OUT_OF_MEMORY) ; } int64_t *GB_RESTRICT Ci = C->i ; GB_CTYPE *GB_RESTRICT Cx = C->x ; #if GB_IS_ANY_PAIR_SEMIRING // ANY_PAIR semiring: result is purely symbolic int64_t pC ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (pC = 0 ; pC < cnz ; pC++) { Cx [pC] = 1 ; } // Just a precaution; these variables are not used below. Any attempt // to access them will lead to a compile error. #define Cx is not used #define Hx is not used // these have been renamed to ANY_PAIR: // EQ_PAIR // LAND_PAIR // LOR_PAIR // MAX_PAIR // MIN_PAIR // TIMES_PAIR #endif #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- #if !GB_IS_ANY_PAIR_SEMIRING GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ; #endif int64_t hash_size = TaskList [taskid].hsize ; bool use_Gustavson = (hash_size == cvlen) ; if (taskid < nfine) { //------------------------------------------------------------------ // fine task: gather pattern and values //------------------------------------------------------------------ int64_t kk = TaskList [taskid].vector ; int team_size = TaskList [taskid].team_size ; int master = TaskList [taskid].master ; int my_teamid = taskid - master ; int64_t pC = Cp [kk] ; if (use_Gustavson) { //-------------------------------------------------------------- // phase5: fine Gustavson task, C=A*B, C<M>=A*B, or C<!M>=A*B //-------------------------------------------------------------- // Hf [i] == 2 if C(i,j) is an entry in C(:,j) uint8_t *GB_RESTRICT Hf = TaskList [taskid].Hf ; int64_t cjnz = Cp [kk+1] - pC ; int64_t istart, iend ; GB_PARTITION (istart, iend, cvlen, my_teamid, team_size) ; if (cjnz == cvlen) { // C(:,j) is dense for (int64_t i = istart ; i < iend ; i++) { Ci [pC + i] = i ; } #if !GB_IS_ANY_PAIR_SEMIRING // copy Hx [istart:iend-1] into Cx [pC+istart:pC+iend-1] GB_CIJ_MEMCPY (pC + istart, istart, iend - istart) ; #endif } else { // C(:,j) is sparse pC += TaskList [taskid].my_cjnz ; for (int64_t i = istart ; i < iend ; i++) { if (Hf [i] == 2) { #if !GB_IS_ANY_PAIR_SEMIRING GB_CIJ_GATHER (pC, i) ; // Cx [pC] = Hx [i] #endif Ci [pC++] = i ; } } } } else { //-------------------------------------------------------------- // phase5: fine hash task, C=A*B, C<M>=A*B, C<!M>=A*B //-------------------------------------------------------------- // (Hf [hash] & 3) == 2 if C(i,j) is an entry in C(:,j), // and the index i of the entry is (Hf [hash] >> 2) - 1. int64_t *GB_RESTRICT Hf = TaskList [taskid].Hf ; int64_t mystart, myend ; GB_PARTITION (mystart, myend, hash_size, my_teamid, team_size) ; pC += TaskList [taskid].my_cjnz ; for (int64_t hash = mystart ; hash < myend ; hash++) { int64_t hf = Hf [hash] ; if ((hf & 3) == 2) { int64_t i = (hf >> 2) - 1 ; // found C(i,j) in hash Ci [pC++] = i ; } } } } else { //------------------------------------------------------------------ // numeric coarse task: compute C(:,kfirst:klast) //------------------------------------------------------------------ int64_t *GB_RESTRICT Hf = TaskList [taskid].Hf ; int64_t kfirst = TaskList [taskid].start ; int64_t klast = TaskList [taskid].end ; int64_t nk = klast - kfirst + 1 ; int64_t mark = 2*nk + 1 ; if (use_Gustavson) { //-------------------------------------------------------------- // phase5: coarse Gustavson task //-------------------------------------------------------------- if (M == NULL) { //---------------------------------------------------------- // phase5: coarse Gustavson task, C=A*B //---------------------------------------------------------- for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_B_j ; // get B(:,j) mark++ ; if (cjnz == cvlen) // C(:,j) is dense { GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j) } else if (bjnz == 1) // C(:,j) = A(:,k)*B(k,j) { GB_COMPUTE_C_j_WHEN_NNZ_B_j_IS_ONE ; } else if (16 * cjnz > cvlen) // C(:,j) is not very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j) if (Hf [i] != mark) { // C(i,j) = A(i,k) * B(k,j) Hf [i] = mark ; GB_HX_WRITE (i, t) ; // Hx [i] = t } else { // C(i,j) += A(i,k) * B(k,j) GB_HX_UPDATE (i, t) ; // Hx [i] += t } } } GB_GATHER_ALL_C_j(mark) ; // gather into C(:,j) } else // C(:,j) is very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j) if (Hf [i] != mark) { // C(i,j) = A(i,k) * B(k,j) Hf [i] = mark ; GB_HX_WRITE (i, t) ; // Hx [i] = t Ci [pC++] = i ; } else { // C(i,j) += A(i,k) * B(k,j) GB_HX_UPDATE (i, t) ; // Hx [i] += t } } } GB_SORT_AND_GATHER_C_j ; // gather into C(:,j) } } } else if (mask_is_M) { //---------------------------------------------------------- // phase5: coarse Gustavson task, C<M>=A*B //---------------------------------------------------------- // Initially, Hf [...] < mark for all of Hf. // Hf [i] < mark : M(i,j)=0, C(i,j) is ignored. // Hf [i] == mark : M(i,j)=1, and C(i,j) not yet seen. // Hf [i] == mark+1 : M(i,j)=1, and C(i,j) has been seen. for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_B_j ; // get B(:,j) if (cjnz == cvlen) // C(:,j) is dense { GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j) continue ; // no need to examine M(:,j) } GB_GET_M_j ; // get M(:,j) GB_GET_M_j_RANGE (64) ; // get first and last in M(:,j) mark += 2 ; int64_t mark1 = mark+1 ; // scatter M(:,j) GB_SCATTER_M_j (pM_start, pM_end, mark) ; if (16 * cjnz > cvlen) // C(:,j) is not very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #define GB_IKJ_VECTORIZE GB_PRAGMA_VECTORIZE #define GB_IKJ_IVDEP GB_PRAGMA_IVDEP #define GB_IKJ \ { \ int64_t hf = Hf [i] ; \ if (hf == mark) \ { \ /* C(i,j) = A(i,k) * B(k,j) */ \ Hf [i] = mark1 ; /* mark as seen */\ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ GB_HX_WRITE (i, t) ; /* Hx [i] = t */ \ } \ else if (hf == mark1) \ { \ /* C(i,j) += A(i,k) * B(k,j) */ \ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ GB_HX_UPDATE (i, t) ;/* Hx [i] += t */ \ } \ } GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ_VECTORIZE #undef GB_IKJ_IVDEP #undef GB_IKJ } GB_GATHER_ALL_C_j(mark1) ; // gather into C(:,j) } else // C(:,j) is very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #define GB_IKJ_VECTORIZE GB_PRAGMA_VECTORIZE #define GB_IKJ_IVDEP GB_PRAGMA_IVDEP #define GB_IKJ \ { \ int64_t hf = Hf [i] ; \ if (hf == mark) \ { \ /* C(i,j) = A(i,k) * B(k,j) */ \ Hf [i] = mark1 ; /* mark as seen */\ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ GB_HX_WRITE (i, t) ; /* Hx [i] = t */ \ Ci [pC++] = i ; /* C(:,j) pattern */ \ } \ else if (hf == mark1) \ { \ /* C(i,j) += A(i,k) * B(k,j) */ \ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ GB_HX_UPDATE (i, t) ;/* Hx [i] += t */ \ } \ } GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ_VECTORIZE #undef GB_IKJ_IVDEP #undef GB_IKJ } GB_SORT_AND_GATHER_C_j ; // gather into C(:,j) } } } else { //---------------------------------------------------------- // phase5: coarse Gustavson task, C<!M>=A*B //---------------------------------------------------------- // if !M: // Hf [i] < mark : M(i,j)=0, C(i,j) is not yet seen. // Hf [i] == mark : M(i,j)=1, so C(i,j) is ignored. // Hf [i] == mark+1 : M(i,j)=0, and C(i,j) has been seen. for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_B_j ; // get B(:,j) if (cjnz == cvlen) // C(:,j) is dense { GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j) continue ; // no need to examine M(:,j) } GB_GET_M_j ; // get M(:,j) mark += 2 ; int64_t mark1 = mark+1 ; // scatter M(:,j) GB_SCATTER_M_j (pM_start, pM_end, mark) ; if (16 * cjnz > cvlen) // C(:,j) is not very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) int64_t hf = Hf [i] ; if (hf < mark) { // C(i,j) = A(i,k) * B(k,j) Hf [i] = mark1 ; // mark as seen GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j) GB_HX_WRITE (i, t) ; // Hx [i] = t } else if (hf == mark1) { // C(i,j) += A(i,k) * B(k,j) GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j) GB_HX_UPDATE (i, t) ;// Hx [i] += t } } } GB_GATHER_ALL_C_j(mark1) ; // gather into C(:,j) } else // C(:,j) is very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) int64_t hf = Hf [i] ; if (hf < mark) { // C(i,j) = A(i,k) * B(k,j) Hf [i] = mark1 ; // mark as seen GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j) GB_HX_WRITE (i, t) ; // Hx [i] = t Ci [pC++] = i ; // create C(:,j) pattern } else if (hf == mark1) { // C(i,j) += A(i,k) * B(k,j) GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j) GB_HX_UPDATE (i, t) ; // Hx [i] += t } } } GB_SORT_AND_GATHER_C_j ; // gather into C(:,j) } } } } else { //-------------------------------------------------------------- // phase5: coarse hash task //-------------------------------------------------------------- int64_t *GB_RESTRICT Hi = TaskList [taskid].Hi ; int64_t hash_bits = (hash_size-1) ; if (M == NULL) { //---------------------------------------------------------- // phase5: coarse hash task, C=A*B //---------------------------------------------------------- // Initially, Hf [...] < mark for all of Hf. // Let f = Hf [hash] and h = Hi [hash] // f < mark : unoccupied. // h == i, f == mark : occupied with C(i,j) for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_B_j ; // get B(:,j) if (bjnz == 1) // C(:,j) = A(:,k)*B(k,j) { GB_COMPUTE_C_j_WHEN_NNZ_B_j_IS_ONE ; continue ; } mark++ ; for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j) for (GB_HASH (i)) // find i in hash table { if (Hf [hash] == mark) { // hash entry is occupied if (Hi [hash] == i) { // i already in the hash table // Hx [hash] += t ; GB_HX_UPDATE (hash, t) ; break ; } } else { // hash entry is not occupied Hf [hash] = mark ; Hi [hash] = i ; GB_HX_WRITE (hash, t) ;// Hx[hash]=t Ci [pC++] = i ; break ; } } } } // found i if: Hf [hash] == mark and Hi [hash] == i GB_SORT_AND_GATHER_HASHED_C_j (mark, Hi [hash] == i) } } else if (mask_is_M) { //---------------------------------------------------------- // phase5: coarse hash task, C<M>=A*B //---------------------------------------------------------- // Initially, Hf [...] < mark for all of Hf. // Let h = Hi [hash] and f = Hf [hash]. // f < mark : M(i,j)=0, C(i,j) is ignored. // h == i, f == mark : M(i,j)=1, and C(i,j) not yet seen. // h == i, f == mark+1 : M(i,j)=1, and C(i,j) has been seen. for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_M_j ; // get M(:,j) GB_GET_M_j_RANGE (64) ; // get 1st & last in M(:,j) mark += 2 ; int64_t mark1 = mark+1 ; GB_HASH_M_j ; // hash M(:,j) GB_GET_B_j ; // get B(:,j) for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #define GB_IKJ_VECTORIZE #define GB_IKJ_IVDEP #define GB_IKJ \ { \ for (GB_HASH (i)) /* find i in hash */ \ { \ int64_t f = Hf [hash] ; \ if (f < mark) break ; /* M(i,j)=0, ignore*/\ if (Hi [hash] == i) \ { \ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ if (f == mark) /* if true, i is new */ \ { \ /* C(i,j) is new */ \ Hf [hash] = mark1 ; /* mark seen */\ GB_HX_WRITE (hash, t) ;/*Hx[.]=t */\ Ci [pC++] = i ; \ } \ else \ { \ /* C(i,j) has been seen; update */ \ GB_HX_UPDATE (hash, t) ; \ } \ break ; \ } \ } \ } GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ_VECTORIZE #undef GB_IKJ_IVDEP #undef GB_IKJ } // found i if: Hf [hash] == mark1 and Hi [hash] == i GB_SORT_AND_GATHER_HASHED_C_j (mark1, Hi [hash] == i) ; } } else { //---------------------------------------------------------- // phase5: coarse hash task, C<!M>=A*B //---------------------------------------------------------- // Initially, Hf [...] < mark for all of Hf. // Let h = Hi [hash] and f = Hf [hash]. // f < mark: unoccupied, M(i,j)=0, and C(i,j) not yet seen. // h == i, f == mark : M(i,j)=1. C(i,j) ignored. // h == i, f == mark+1 : M(i,j)=0, and C(i,j) has been seen. for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_M_j ; // get M(:,j) mark += 2 ; int64_t mark1 = mark+1 ; GB_HASH_M_j ; // hash M(:,j) GB_GET_B_j ; // get B(:,j) for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) for (GB_HASH (i)) // find i in hash { int64_t f = Hf [hash] ; if (f < mark) // if true, i is new { // C(i,j) is new Hf [hash] = mark1 ; // mark C(i,j) seen Hi [hash] = i ; GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j) GB_HX_WRITE (hash, t) ; // Hx [hash] = t Ci [pC++] = i ; break ; } if (Hi [hash] == i) { if (f == mark1) { // C(i,j) has been seen; update it. GB_MULT_A_ik_B_kj ;//t=A(i,k)*B(k,j) GB_HX_UPDATE (hash, t) ;//Hx[ ] += t } break ; } } } } // found i if: Hf [hash] == mark1 and Hi [hash] == i GB_SORT_AND_GATHER_HASHED_C_j (mark1, Hi [hash] == i) ; } } } } } //========================================================================== // phase6: final gather phase for fine hash tasks //========================================================================== if (cjnz_max > 0) { int64_t *GB_RESTRICT W = NULL ; bool parallel_sort = (cjnz_max > GB_BASECASE && nthreads > 1) ; if (parallel_sort) { // allocate workspace for parallel mergesort GB_MALLOC_MEMORY (W, cjnz_max, sizeof (int64_t)) ; if (W == NULL) { // out of memory return (GrB_OUT_OF_MEMORY) ; } } for (taskid = 0 ; taskid < nfine ; taskid++) { int64_t hash_size = TaskList [taskid].hsize ; bool use_Gustavson = (hash_size == cvlen) ; if (!use_Gustavson && taskid == TaskList [taskid].master) { //-------------------------------------------------------------- // phase6: fine hash task, C=A*B, C<M>=A*B, C<!M>=A*B //-------------------------------------------------------------- // (Hf [hash] & 3) == 2 if C(i,j) is an entry in C(:,j), // and the index i of the entry is (Hf [hash] >> 2) - 1. int64_t kk = TaskList [taskid].vector ; int64_t hash_bits = (hash_size-1) ; int64_t *GB_RESTRICT Hf = TaskList [taskid].Hf ; int64_t cjnz = Cp [kk+1] - Cp [kk] ; // sort the pattern of C(:,j) int nth = GB_nthreads (cjnz, chunk, nthreads) ; if (parallel_sort && nth > 1) { // parallel mergesort GB_msort_1 (Ci + Cp [kk], W, cjnz, nth) ; } else { // sequential quicksort GB_qsort_1a (Ci + Cp [kk], cjnz) ; } #if !GB_IS_ANY_PAIR_SEMIRING GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ; // gather the values of C(:,j) int64_t pC ; #pragma omp parallel for num_threads(nth) schedule(static) for (pC = Cp [kk] ; pC < Cp [kk+1] ; pC++) { int64_t i = Ci [pC] ; // get C(i,j) int64_t i1 = i + 1 ; for (GB_HASH (i)) // find i in hash table { int64_t hf = Hf [hash] ; if ((hf & 3) == 2 && (hf >> 2) == i1) { // found i in the hash table GB_CIJ_GATHER (pC, hash) ; // Cx[pC] = Hx[hash] break ; } } } #endif } } // free workspace GB_FREE_MEMORY (W, cjnz_max, sizeof (int64_t)) ; } } #undef Cx #undef Hx
GB_binop__bxnor_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef 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__bxnor_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__bxnor_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__bxnor_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__bxnor_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bxnor_uint64) // A*D function (colscale): GB (_AxD__bxnor_uint64) // D*A function (rowscale): GB (_DxB__bxnor_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__bxnor_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__bxnor_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bxnor_uint64) // C=scalar+B GB (_bind1st__bxnor_uint64) // C=scalar+B' GB (_bind1st_tran__bxnor_uint64) // C=A+scalar GB (_bind2nd__bxnor_uint64) // C=A'+scalar GB (_bind2nd_tran__bxnor_uint64) // C type: uint64_t // A type: uint64_t // A pattern? 0 // B type: uint64_t // B pattern? 0 // BinaryOp: cij = ~((aij) ^ (bij)) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = ~((x) ^ (y)) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BXNOR || GxB_NO_UINT64 || GxB_NO_BXNOR_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__bxnor_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bxnor_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bxnor_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__bxnor_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__bxnor_uint64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bxnor_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint64_t alpha_scalar ; uint64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ; beta_scalar = (*((uint64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__bxnor_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bxnor_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__bxnor_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bxnor_uint64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bxnor_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = ~((x) ^ (bij)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bxnor_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = ~((aij) ^ (y)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ~((x) ^ (aij)) ; \ } GrB_Info GB (_bind1st_tran__bxnor_uint64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ~((aij) ^ (y)) ; \ } GrB_Info GB (_bind2nd_tran__bxnor_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
convolution_1x1_pack16.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv1x1s1_sgemm_pack16_avx512(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; const int size = w * h; Mat bottom_im2col = bottom_blob; bottom_im2col.w = size; bottom_im2col.h = 1; im2col_sgemm_pack16_avx512(bottom_im2col, top_blob, kernel, _bias, opt); } static void conv1x1s2_sgemm_pack16_avx512(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; const int tailstep = (w - 2 * outw + w) * 16; Mat bottom_blob_shrinked; bottom_blob_shrinked.create(outw, outh, channels, elemsize, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < channels; p++) { const float* r0 = bottom_blob.channel(p); float* outptr = bottom_blob_shrinked.channel(p); for (int i = 0; i < outh; i++) { int j = 0; for (; j < outw; j++) { __m512 _v = _mm512_loadu_ps(r0); _mm512_storeu_ps(outptr, _v); r0 += 32; outptr += 16; } r0 += tailstep; } } conv1x1s1_sgemm_pack16_avx512(bottom_blob_shrinked, top_blob, kernel, _bias, opt); }
l7_push_setup.c
/* * Copyright (c) 2011-2019, Triad National Security, LLC. * All rights Reserved. * * CLAMR -- LA-CC-11-094 * * Copyright 2011-2019. Triad National Security, LLC. This software was produced * under U.S. Government contract 89233218CNA000001 for Los Alamos National * Laboratory (LANL), which is operated by Triad National Security, LLC * for the U.S. Department of Energy. The U.S. Government has rights to use, * reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR * TRIAD NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified * to produce derivative works, such modified software should be clearly marked, * so as not to confuse it with the version available from LANL. * * Additionally, redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Triad National Security, LLC, Los Alamos * National Laboratory, LANL, the U.S. Government, 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 TRIAD NATIONAL SECURITY, LLC 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 TRIAD NATIONAL * SECURITY, LLC 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 <stdlib.h> #include "l7.h" #include "l7p.h" #define L7_LOCATION "L7_PUSH_SETUP" int L7_Push_Setup( const int num_comm_partners, const int *comm_partner, const int *send_buffer_count, int **send_database, int *receive_count_total, int *l7_push_id ) { /* Purpose * ======= * L7_Push_Setup is used to setup the update/scatter database for * when senders know which data to send and to what process. Each * process sends in the data it needs to send in a send_database * which is a ragged right array with the first index the * num_comm_partners and the second the send_buffer_count for each * processor with the indices to send. From this, a communication * pattern and buffers are setup that allows subsequent calls to * L7_Push_Update. * * Arguments * ========= * num_comm_partners (input) const L7_INT * global indexing set starts with 1 (Fortran) * or with 0 (C) * * comm_partner (input) const L7_INT * Starting index number of calling process * in global indexing set. * * send_buffer_count (input) const L7_INT * Number of indices owned by calling process. * * send_database (input) const L7_INT* * Array containing indices needed by * calling process. * * receive_count_total (output) const L7_INT * Number of indices of interest listed * in array 'num_indices_needed'. * * l7_push_id (input/output) int* * Handle to database to be setup. * * 0: L7 sets up a new database, and * assigns it a value. * > 0: L7 resets existing database with * input information. That is, it reuses * the allocated memory. * < 0: An error is returned. * * Notes: * ===== * 1) The indices are handled as 4-byte integers. ?? * * 2) Serial compilation creates a no-op. ?? * * Program Flow ?? * ============ * 0) Check input for basic validity. * 1) Set communication parameters within database. * 2) Deternine processes this pe receives from. * 3) Determine the number of processes this pe sends to. * 4) Send number of as well as the indices needed from each sending process. * 5) Set up array containing the pes this pe sends indices to. * 6) Set up array containing the indices this pe sends to others. */ /* * Local variables. */ int ierr; /* Error code for return */ #ifdef HAVE_MPI l7_push_id_database *l7_push_id_db; /* * Executable Statements */ if (! l7.mpi_initialized){ return(0); } if (l7.initialized != 1){ ierr = -1; L7_ASSERT( l7.initialized == 1, "L7 not initialized", ierr); } /* * Check input */ /* if (my_start_index < 0){ ierr = -1; L7_ASSERT( my_start_index >= 0, "my_start_index < 0", ierr); } */ if (num_comm_partners < 0){ ierr = -1; L7_ASSERT( num_comm_partners >= 0, "num_comm_partners < 0", ierr); } /* if (num_indices_needed > 0){ if (indices_needed == NULL){ ierr = -1; L7_ASSERT( (int *)indices_needed != NULL, "indices_needed == NULL", ierr); } } */ if (*l7_push_id < 0){ ierr = *l7_push_id; L7_ASSERT( *l7_push_id >=0, "L7 Push Id must be either 0 (new id) or > 0 (existing id)", ierr); } /* * Setup database structure. */ if (*l7_push_id != 0){ /* * Find it in the database and update based on new input. */ if (l7.first_push_db == NULL){ L7_ASSERT(l7.first_push_db != NULL, "Uninitialized l7_push_id input, but no ids in database", ierr); } l7_push_id_db = l7.first_push_db; while (l7_push_id_db){ if (l7_push_id_db->l7_push_id == *l7_push_id) break; l7_push_id_db = l7_push_id_db->next_push_db; } if (l7.first_push_db == NULL){ ierr = -1; L7_ASSERT( l7.first_push_db != NULL, "Uninitialized l7_push_id input, but not found in this list", ierr); } } else{ /* * Allocate new database, insert into linked list. */ if (l7.num_push_dbs >= L7_MAX_NUM_DBS){ ierr = -1; L7_ASSERT(l7.num_push_dbs < L7_MAX_NUM_DBS, "Too many L7 databases allocated", ierr); } l7_push_id_db = (l7_push_id_database*)calloc(1L, sizeof(l7_push_id_database) ); if (l7_push_id_db == NULL){ ierr = -1; L7_ASSERT( l7_push_id_db != NULL, "Failed to allocate new database", ierr); } if ( !(l7.first_push_db) ){ l7.first_push_db = l7_push_id_db; l7.last_push_db = l7_push_id_db; l7_push_id_db->next_push_db = NULL; /* Paranoia */ l7_push_id_db->l7_push_id = 1; l7.num_push_dbs = 1; } else{ /* * Assign a l7_id. */ l7_push_id_db->l7_push_id = l7.last_push_db->l7_push_id + 1; /* * Reset links. */ l7.last_push_db->next_push_db = l7_push_id_db; l7.last_push_db = l7_push_id_db; l7.num_push_dbs++; } *l7_push_id = l7_push_id_db->l7_push_id; /* * Initialize some parameters. */ /* l7_id_db->recv_counts_len = 0; l7_id_db->recv_from_len = 0; l7_id_db->send_to_len = 0; l7_id_db->send_counts_len = 0; l7_id_db->indices_to_send_len = 0; l7_id_db->mpi_request_len = 0; l7_id_db->mpi_status_len = 0; */ } /* * Allocate arrays and * Store input in database. */ if (l7_push_id_db->num_comm_partners < num_comm_partners){ // comm_partner if (l7_push_id_db->comm_partner) free(l7_push_id_db->comm_partner); l7_push_id_db->comm_partner = (int *) calloc(num_comm_partners,sizeof(int)); if (l7_push_id_db->comm_partner == NULL){ ierr = -1; L7_ASSERT( (int*)(l7_push_id_db->comm_partner) != NULL, "Memory failure for comm_partner", ierr); } // send_buffer_count if (l7_push_id_db->send_buffer_count) free(l7_push_id_db->send_buffer_count); l7_push_id_db->send_buffer_count = (int *) calloc(num_comm_partners,sizeof(int)); if (l7_push_id_db->send_buffer_count == NULL){ ierr = -1; L7_ASSERT( (int*)(l7_push_id_db->send_buffer_count) != NULL, "Memory failure for send_buffer_count", ierr); } // recv_buffer_count if (l7_push_id_db->recv_buffer_count) free(l7_push_id_db->recv_buffer_count); l7_push_id_db->recv_buffer_count = (int *) calloc(num_comm_partners,sizeof(int)); if (l7_push_id_db->recv_buffer_count == NULL){ ierr = -1; L7_ASSERT( (int*)(l7_push_id_db->recv_buffer_count) != NULL, "Memory failure for recv_buffer_count", ierr); } // send_database if (l7_push_id_db->send_database){ for (int ip = 0; ip < num_comm_partners; ip++){ if (l7_push_id_db->send_database[ip]) free(l7_push_id_db->send_database[ip]); } if (l7_push_id_db->send_database) free(l7_push_id_db->send_database); } l7_push_id_db->send_database = (int **) calloc(num_comm_partners,sizeof(int *)); if (l7_push_id_db->send_database == NULL){ ierr = -1; L7_ASSERT( (int*)(l7_push_id_db->send_database) != NULL, "Memory failure for send_database", ierr); } for (int ip = 0; ip < num_comm_partners; ip++){ l7_push_id_db->send_database[ip] = (int *) calloc(send_buffer_count[ip],sizeof(int)); if (l7_push_id_db->send_database[ip] == NULL){ ierr = -1; L7_ASSERT( (int*)(l7_push_id_db->send_database) != NULL, "Memory failure for send_database", ierr); } } // send_buffer if (l7_push_id_db->send_buffer){ for (int ip = 0; ip < num_comm_partners; ip++){ if (l7_push_id_db->send_buffer[ip]) free(l7_push_id_db->send_buffer[ip]); } if (l7_push_id_db->send_buffer) free(l7_push_id_db->send_buffer); } l7_push_id_db->send_buffer = (int **) calloc(num_comm_partners,sizeof(int *)); if (l7_push_id_db->send_buffer == NULL){ ierr = -1; L7_ASSERT( (int*)(l7_push_id_db->send_buffer) != NULL, "Memory failure for send_buffer", ierr); } for (int ip = 0; ip < num_comm_partners; ip++){ l7_push_id_db->send_buffer[ip] = (int *) calloc(send_buffer_count[ip],sizeof(int)); if (l7_push_id_db->send_buffer[ip] == NULL){ ierr = -1; L7_ASSERT( (int*)(l7_push_id_db->send_buffer) != NULL, "Memory failure for send_buffer", ierr); } } } /* * Copy input data into database */ l7_push_id_db->num_comm_partners = num_comm_partners; #ifdef _OPENMP_SIMD #pragma omp simd #endif for (int ip = 0; ip < num_comm_partners; ip++){ l7_push_id_db->comm_partner[ip] = comm_partner[ip]; l7_push_id_db->send_buffer_count[ip] = send_buffer_count[ip]; } for (int ip = 0; ip < num_comm_partners; ip++){ int count = send_buffer_count[ip]; // create simple int count to help vectorization #ifdef _OPENMP_SIMD #pragma omp simd #endif for (int ic = 0; ic < count; ic++){ l7_push_id_db->send_database[ip][ic] = send_database[ip][ic]; } } /* * Get receive counts by communication */ MPI_Request request[2*num_comm_partners]; MPI_Status status[2*num_comm_partners]; for (int ip = 0; ip < num_comm_partners; ip++){ MPI_Irecv(&l7_push_id_db->recv_buffer_count[ip], 1, MPI_INT, l7_push_id_db->comm_partner[ip], l7_push_id_db->comm_partner[ip], MPI_COMM_WORLD, &request[ip]); } for (int ip = 0; ip < num_comm_partners; ip++){ MPI_Isend(&l7_push_id_db->send_buffer_count[ip], 1, MPI_INT, l7_push_id_db->comm_partner[ip], l7.penum, MPI_COMM_WORLD, &request[num_comm_partners+ip]); } MPI_Waitall(2*num_comm_partners, request, status); /* * Calculate sum of receives */ *receive_count_total = 0; for (int ip = 0; ip < num_comm_partners; ip++){ *receive_count_total += l7_push_id_db->recv_buffer_count[ip]; } l7_push_id_db->receive_count_total = *receive_count_total; #endif /* HAVE_MPI */ ierr = L7_OK; return(ierr); } /* End L7_Push_Setup */
irbuilder_unroll_partial_factor.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs // RUN: %clang_cc1 -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=51 -x c -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-LABEL: define {{.*}}@unroll_partial_factor( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[B_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[C_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[D_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[I:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[AGG_CAPTURED:.+]] = alloca %struct.anon, align 8 // CHECK-NEXT: %[[AGG_CAPTURED1:.+]] = alloca %struct.anon.0, align 4 // CHECK-NEXT: %[[DOTCOUNT_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8 // CHECK-NEXT: store float* %[[B:.+]], float** %[[B_ADDR]], align 8 // CHECK-NEXT: store float* %[[C:.+]], float** %[[C_ADDR]], align 8 // CHECK-NEXT: store float* %[[D:.+]], float** %[[D_ADDR]], align 8 // CHECK-NEXT: store i32 0, i32* %[[I]], align 4 // CHECK-NEXT: %[[TMP0:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 0 // CHECK-NEXT: store i32* %[[I]], i32** %[[TMP0]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: store i32 %[[TMP2]], i32* %[[TMP1]], align 4 // CHECK-NEXT: call void @__captured_stmt(i32* %[[DOTCOUNT_ADDR]], %struct.anon* %[[AGG_CAPTURED]]) // CHECK-NEXT: %[[DOTCOUNT:.+]] = load i32, i32* %[[DOTCOUNT_ADDR]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_PREHEADER]]: // CHECK-NEXT: br label %[[OMP_LOOP_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_HEADER]]: // CHECK-NEXT: %[[OMP_LOOP_IV:.+]] = phi i32 [ 0, %[[OMP_LOOP_PREHEADER]] ], [ %[[OMP_LOOP_NEXT:.+]], %[[OMP_LOOP_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_LOOP_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_COND]]: // CHECK-NEXT: %[[OMP_LOOP_CMP:.+]] = icmp ult i32 %[[OMP_LOOP_IV]], %[[DOTCOUNT]] // CHECK-NEXT: br i1 %[[OMP_LOOP_CMP]], label %[[OMP_LOOP_BODY:.+]], label %[[OMP_LOOP_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_BODY]]: // CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[OMP_LOOP_IV]], %struct.anon.0* %[[AGG_CAPTURED1]]) // CHECK-NEXT: %[[TMP3:.+]] = load float*, float** %[[B_ADDR]], align 8 // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM:.+]] = sext i32 %[[TMP4]] to i64 // CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP3]], i64 %[[IDXPROM]] // CHECK-NEXT: %[[TMP5:.+]] = load float, float* %[[ARRAYIDX]], align 4 // CHECK-NEXT: %[[TMP6:.+]] = load float*, float** %[[C_ADDR]], align 8 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM2:.+]] = sext i32 %[[TMP7]] to i64 // CHECK-NEXT: %[[ARRAYIDX3:.+]] = getelementptr inbounds float, float* %[[TMP6]], i64 %[[IDXPROM2]] // CHECK-NEXT: %[[TMP8:.+]] = load float, float* %[[ARRAYIDX3]], align 4 // CHECK-NEXT: %[[MUL:.+]] = fmul float %[[TMP5]], %[[TMP8]] // CHECK-NEXT: %[[TMP9:.+]] = load float*, float** %[[D_ADDR]], align 8 // CHECK-NEXT: %[[TMP10:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM4:.+]] = sext i32 %[[TMP10]] to i64 // CHECK-NEXT: %[[ARRAYIDX5:.+]] = getelementptr inbounds float, float* %[[TMP9]], i64 %[[IDXPROM4]] // CHECK-NEXT: %[[TMP11:.+]] = load float, float* %[[ARRAYIDX5]], align 4 // CHECK-NEXT: %[[MUL6:.+]] = fmul float %[[MUL]], %[[TMP11]] // CHECK-NEXT: %[[TMP12:.+]] = load float*, float** %[[A_ADDR]], align 8 // CHECK-NEXT: %[[TMP13:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM7:.+]] = sext i32 %[[TMP13]] to i64 // CHECK-NEXT: %[[ARRAYIDX8:.+]] = getelementptr inbounds float, float* %[[TMP12]], i64 %[[IDXPROM7]] // CHECK-NEXT: store float %[[MUL6]], float* %[[ARRAYIDX8]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_INC]]: // CHECK-NEXT: %[[OMP_LOOP_NEXT]] = add nuw i32 %[[OMP_LOOP_IV]], 1 // CHECK-NEXT: br label %[[OMP_LOOP_HEADER]], !llvm.loop ![[LOOP3:[0-9]+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_EXIT]]: // CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_AFTER]]: // CHECK-NEXT: ret void // CHECK-NEXT: } void unroll_partial_factor(float *a, float *b, float *c, float *d) { #pragma omp unroll partial(3) for (int i = 0; i < 2; i++) { a[i] = b[i] * c[i] * d[i]; } } #endif // HEADER // CHECK-LABEL: define {{.*}}@__captured_stmt( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[DISTANCE_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon*, align 8 // CHECK-NEXT: %[[DOTSTART:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTOP:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTEP:.+]] = alloca i32, align 4 // CHECK-NEXT: store i32* %[[DISTANCE:.+]], i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store %struct.anon* %[[__CONTEXT:.+]], %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon*, %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32*, i32** %[[TMP1]], align 8 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[TMP2]], align 4 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[DOTSTART]], align 4 // CHECK-NEXT: store i32 2, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: store i32 1, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[CMP:.+]] = icmp slt i32 %[[TMP4]], %[[TMP5]] // CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_TRUE]]: // CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[SUB:.+]] = sub nsw i32 %[[TMP6]], %[[TMP7]] // CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB1:.+]] = sub i32 %[[TMP8]], 1 // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB1]] // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[TMP9]] // CHECK-NEXT: br label %[[COND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_FALSE]]: // CHECK-NEXT: br label %[[COND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_END]]: // CHECK-NEXT: %[[COND:.+]] = phi i32 [ %[[DIV]], %[[COND_TRUE]] ], [ 0, %[[COND_FALSE]] ] // CHECK-NEXT: %[[TMP10:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP10]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define {{.*}}@__captured_stmt.1( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[LOOPVAR_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[LOGICAL_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon.0*, align 8 // CHECK-NEXT: store i32* %[[LOOPVAR:.+]], i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[LOGICAL:.+]], i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: store %struct.anon.0* %[[__CONTEXT:.+]], %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon.0*, %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[TMP1]], align 4 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: %[[MUL:.+]] = mul i32 1, %[[TMP3]] // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[TMP2]], %[[MUL]] // CHECK-NEXT: %[[TMP4:.+]] = load i32*, i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[ADD]], i32* %[[TMP4]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4} // CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 51} // CHECK: ![[META2:[0-9]+]] = // CHECK: ![[LOOP3]] = distinct !{![[LOOP3]], ![[LOOPPROP4:[0-9]+]], ![[LOOPPROP5:[0-9]+]]} // CHECK: ![[LOOPPROP4]] = !{!"llvm.loop.unroll.enable"} // CHECK: ![[LOOPPROP5]] = !{!"llvm.loop.unroll.count", i32 3}
GB_unaryop__minv_fp32_int64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_fp32_int64 // op(A') function: GB_tran__minv_fp32_int64 // C type: float // A type: int64_t // cast: float cij = (float) aij // unaryop: cij = (1.0F)/aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ float // 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 = (1.0F)/x ; // casting #define GB_CASTING(z, aij) \ float z = (float) aij ; // 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 (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP32 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_fp32_int64 ( float *Cx, // Cx and Ax may be aliased int64_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_fp32_int64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
update_W_b.c
#include "q_incs.h" #include "dnn_types.h" #include "update_W_b.h" int update_W_b( float ***W, float ***dW, float **b, float **db, int nl, int *npl, bool **d, // true => dropout; false => keep float alpha // learning rate ) { int status = 0; // Updates the 'W' and 'b' for ( int l = 1; l < nl; l++ ) { // for layer, starting from one float **W_l = W[l]; float **dW_l = dW[l]; float *b_l = b[l]; float *db_l = db[l]; bool *d_l = d[l]; #pragma omp parallel for for ( int jprime = 0; jprime < npl[l-1]; jprime++ ) { // for neurons in layer l-1 if ( d_l[jprime] ) { continue; } // TODO: Study carefully float *W_l_jprime = W_l[jprime]; float *dW_l_jprime = dW_l[jprime]; #pragma omp simd for ( int j = 0; j < npl[l]; j++ ) { // for neurons in layer l W_l_jprime[j] -= ( alpha * dW_l_jprime[j] ); #ifdef COUNT num_b_flops += 2; #endif } /* above is equivalent to below for ( int j = 0; j < npl[l]; j++ ) { *W_l_jprime++ -= ( alpha * *dW_l_jprime++ ); } */ } #pragma omp simd for ( int j = 0; j < npl[l]; j++ ) { b_l[j] -= ( alpha * db_l[j] ); #ifdef COUNT num_b_flops += 2; #endif } } BYE: return status; }
bigquic.h
#ifndef _QUIC_H_ #define _QUIC_H_ #include <algorithm> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <math.h> #include <vector> //#ifdef _OPENMP //#endif #ifdef __cplusplus extern "C" { #endif #include "metis.h" #include "omp.h" #ifdef __cplusplus } #endif #include <time.h> using namespace std; void NormalizeData(int p, int n, double *samples, double *samples_new, vector<int> &mapping); double computeSij(const double *samples, long p, long n, long i, long j); double innerproduct(vector<double> &x, vector<double> &y); void vector_plus(vector<double> &x, vector<double> &y, vector<double> &z, double c); class smat_t { public: long p; long nnz; vector<double> values; vector<long> row_ptr; vector<long> col_idx; int is_symmetric; vector<long> id_map; smat_t() { is_symmetric = 0; } smat_t(smat_t &X, smat_t &D, double alpha) { smat_t(); is_symmetric = 0; p = X.p; nnz = 0; values.resize(X.nnz+D.nnz); row_ptr.resize(p+1); col_idx.resize(X.nnz+D.nnz); for ( long i=0 ; i<p ; i++ ) { row_ptr[i] = nnz; long idx1 = X.row_ptr[i]; long idx2 = D.row_ptr[i]; while ( (idx1 <X.row_ptr[i+1]) && (idx2<D.row_ptr[i+1])) { if ( X.col_idx[idx1] < D.col_idx[idx2] ) { col_idx[nnz] = X.col_idx[idx1]; values[nnz] = X.values[idx1]; idx1++, nnz++; } else if ( X.col_idx[idx1] > D.col_idx[idx2]) { col_idx[nnz] = D.col_idx[idx2]; values[nnz] = alpha*D.values[idx2]; idx2++, nnz++; } else { col_idx[nnz] = X.col_idx[idx1]; values[nnz] = X.values[idx1]+alpha*D.values[idx2]; idx1++, idx2++, nnz++; } } if ( idx1 < X.row_ptr[i+1] ) { for ( ; idx1<X.row_ptr[i+1] ; idx1++, nnz++ ) { col_idx[nnz] = X.col_idx[idx1]; values[nnz] = X.values[idx1]; } } else if ( idx2 < D.row_ptr[i+1]) { for ( ; idx2<D.row_ptr[i+1] ; idx2++, nnz++ ) { col_idx[nnz] = D.col_idx[idx2]; values[nnz] = alpha*D.values[idx2]; } } } row_ptr[p] = nnz; } smat_t(long p_) { smat_t(); p = p_; is_symmetric = 0; } smat_t(smat_t &X) { smat_t(); p = X.p; nnz = X.nnz; values = X.values; row_ptr = X.row_ptr; col_idx = X.col_idx; is_symmetric = 0; } int identity(long p_) { p = p_; nnz = p; values.resize(p); row_ptr.resize(p+1); col_idx.resize(p); for ( long i=0 ; i<p ; i++) { values[i] =1; col_idx[i] = i; row_ptr[i] = i; } row_ptr[p] = p; return 1; } int reset() { values.clear(); col_idx.clear(); row_ptr.clear(); nnz = 0; return 1; } // Form the graph with node id in id_map. // Cannot work when the id_map is not in increasing order. void form_originalgraph() { int realp = id_map[p-1]+1; for ( long idx=0 ; idx<nnz ; idx++ ) col_idx[idx] = id_map[col_idx[idx]]; vector<long> tmp = row_ptr; row_ptr.resize(realp+1); for ( long i=0 ; i<=id_map[0] ; i++) row_ptr[i] = 0; long lastid = id_map[0]; for ( long i=1 ; i<p ; i++ ) { long nowid = id_map[i]; for ( long ii=lastid+1 ; ii<=nowid ; ii++) row_ptr[ii] = tmp[i]; lastid = nowid; } for ( long i=id_map[p-1]+1 ; i<=realp ; i++) row_ptr[i] = nnz; p = realp; } void dfs(long &ncluster, vector<long> &cluster_ind) { vector<long> stack (p); long top; ncluster = 0; cluster_ind.resize(p); for ( long i=0 ; i<p ; i++ ) cluster_ind[i] = 0; for ( long i=0 ; i<p ; i++ ) if ( cluster_ind[i] == 0) { ncluster++; cluster_ind[i] = ncluster; stack[0] = i; top = 1; while (top >0 ) { top--; long nowi = stack[top]; for ( long idx = row_ptr[nowi] ; idx < row_ptr[nowi+1] ; idx++ ) { long nowj = col_idx[idx]; if ( cluster_ind[nowj] == 0 ) { stack[top] = nowj; top++; cluster_ind[nowj] = ncluster; } } } } } void ComputeAx(vector<double> &x, vector<double> &Ax) { ComputeAx(x, Ax, p); } void ComputeAx_omp(vector<double> &x, vector<double> &Ax, long p_) { Ax.resize(p_); for ( long i=0 ; i<p_ ; i++ ) Ax[i] = 0; for (long i=0 ; i<p_ ; i++ ) { for ( long idx = row_ptr[i] ; idx < row_ptr[i+1] ; idx++) { long j = col_idx[idx]; double v = values[idx]; Ax[i] += v*x[j]; if ( i!=j ) Ax[j] += v*x[i]; } } } void ComputeAx(vector<double> &x, vector<double> &Ax, long p_) { Ax.resize(p_); for ( long i=0 ; i<p_ ; i++ ) Ax[i] = 0; if ( is_symmetric != 1 ) { for (long i=0 ; i<p_ ; i++ ) for ( long idx = row_ptr[i] ; idx < row_ptr[i+1] ; idx++) { long j = col_idx[idx]; double v = values[idx]; Ax[i] += v*x[j]; // if ( is_symmetric != 1) if ( i!=j ) Ax[j] += v*x[i]; } } else { for (long i=0 ; i<p_ ; i++ ) { double tmp=0; for ( long idx = row_ptr[i] ; idx < row_ptr[i+1] ; idx++) { long j = col_idx[idx]; double v = values[idx]; tmp += v*x[j]; } Ax[i] = tmp; } } } int ComputeAinvb_omp(vector<double> &b, vector<double> &x, long p_, double tol = 1e-15) { vector<double> r(p_), pp(p_), Ax_result(p_); int maxiter = 15; // Initial from x = 0 for ( int i=0 ; i<p_ ; i++) x[i] = 0; r = b; pp = r; double r_norm = innerproduct(r,r); double initial = r_norm; // printf("initial rnorm: %lf\n", r_norm); if ( r_norm <1e-13) return 0; int iter; for ( iter = 0; iter<maxiter ; iter++) { ComputeAx_omp(pp, Ax_result, p_); double alpha = innerproduct(r, r)/innerproduct(Ax_result, pp); vector_plus(x, x, pp, alpha); vector_plus(r, r, Ax_result, (-1)*alpha); double r_norm_now = innerproduct(r,r); // printf("residual: %lf\n", r_norm_now); if ( r_norm_now < tol*initial) break; double beta = r_norm_now/r_norm; r_norm = r_norm_now; vector_plus(pp, r, pp, beta); } return (iter+1); } int ComputeAinvb(vector<double> &b, vector<double> &x, double tol = 1e-5) { return ComputeAinvb(b, x, p, tol); } int ComputeAinvb(vector<double> &b, vector<double> &x, long p_, double tol = 1e-15) { vector<double> r(p_), pp(p_), Ax_result(p_); int maxiter = 15; // Initial from x = 0 for ( int i=0 ; i<p_ ; i++) x[i] = 0; r = b; pp = r; double r_norm = innerproduct(r,r); double initial = r_norm; // printf("initial rnorm: %lf\n", r_norm); if ( r_norm <1e-13) return 0; int iter; for ( iter = 0; iter<maxiter ; iter++) { ComputeAx(pp, Ax_result, p_); double alpha = innerproduct(r, r)/innerproduct(Ax_result, pp); vector_plus(x, x, pp, alpha); vector_plus(r, r, Ax_result, (-1)*alpha); double r_norm_now = innerproduct(r,r); // printf("residual: %lf\n", r_norm_now); if ( r_norm_now < tol*initial) break; double beta = r_norm_now/r_norm; r_norm = r_norm_now; vector_plus(pp, r, pp, beta); } return (iter+1); } int ComputeLogdet_serial(double &result, double tol=1e-5) { double logdet = 0; // check if all diagonals are positive int pd = 1; long i; for ( i=0 ; i<p ; i++ ) { if ( row_ptr[i+1]-1 < 0) break; if ( col_idx[row_ptr[i+1]-1] != i) break; if ( values[row_ptr[i+1]-1] < 0) break; } if ( i<p ) return 0; logdet = log(values[0]); for ( long pend=1 ; pend<p ; pend++) { // compute double tmp = values[row_ptr[pend+1]-1]; vector<double> b (pend,0); for ( long idx = row_ptr[pend] ; idx < row_ptr[pend+1]-1 ; idx++ ) b[col_idx[idx]] = values[idx]; if ( pend == 1 ) tmp = tmp - b[0]*b[0]/values[0]; else { vector<double> Ainvb (pend,0); ComputeAinvb_omp(b, Ainvb, pend, tol); tmp = tmp - innerproduct(b, Ainvb); } if ( tmp <= 0) return 0; logdet += log(tmp); // if ( pend %100 == 0) // printf("logdet iter %d: %lf\n", pend, logdet); } result = logdet; return 1; } int ComputeLogdet(double &result, double tol=1e-5) { double logdet = 0; // check if all diagonals are positive int pd = 1; long i; for ( i=0 ; i<p ; i++ ) { if ( row_ptr[i+1]-1 < 0) break; if ( col_idx[row_ptr[i+1]-1] != i) break; if ( values[row_ptr[i+1]-1] < 0) break; } if ( i<p ) return 0; logdet = 0; int errorflag = 0; //#pragma omp parallel for shared(errorflag) reduction(+:logdet) for ( long pend=1 ; pend<p ; pend++) { if (errorflag==1) continue; // compute double tmp = values[row_ptr[pend+1]-1]; vector<double> b (pend,0); for ( long idx = row_ptr[pend] ; idx < row_ptr[pend+1]-1 ; idx++ ) b[col_idx[idx]] = values[idx]; if ( pend == 1 ) tmp = tmp - b[0]*b[0]/values[0]; else { vector<double> Ainvb (pend,0); ComputeAinvb_omp(b, Ainvb, pend, tol); tmp = tmp - innerproduct(b, Ainvb); } if ( tmp <= tol) errorflag = 1; // return 0; logdet += log(tmp); // if ( pend %100 == 0) // printf("logdet iter %d: %lf\n", pend, logdet); } logdet += log(values[0]); result = logdet; if (errorflag == 1) return 0; else return 1; } double l1norm() { double result =0; for ( long i=0 ; i<p ; i++ ) for ( long idx = row_ptr[i] ; idx<row_ptr[i+1] ; idx++ ) { if ( col_idx[idx] == i ) result += fabs(values[idx]); else result += fabs(values[idx])*2; } return result; } double ComputetrSX(const double *samples, long n) { double result = 0; const double *si, *sj; for ( long i=0 ; i<p ; i++ ) { si = &(samples[n*i]); for ( long idx = row_ptr[i] ; idx<row_ptr[i+1] ; idx++ ) { sj = &(samples[n*col_idx[idx]]); double tmp = 0; for ( long t=0 ; t<n ; t++ ) tmp += si[t]*sj[t]; if ( col_idx[idx] == i ) result += values[idx]*tmp; else result += values[idx]*tmp*2; } } return result; } int copyfrom(smat_t &X) { p = X.p; nnz = X.nnz; values = X.values; row_ptr = X.row_ptr; col_idx = X.col_idx; return 0; } // make a symmetric matrix from lower triangular matrix int symmetricfrom(smat_t &X) { is_symmetric = 1; p=X.p; // Copy the idmap if there exists one if ( (unsigned)X.id_map.size() == X.p ) { id_map.resize(X.p); for ( long i=0 ;i<X.p ; i++ ) id_map[i] = X.id_map[i]; } nnz = 0; row_ptr.resize(p+1,0); col_idx.resize(2*X.nnz); values.resize(2*X.nnz); vector<long> tmp(p); for ( long i=0 ; i<p ; i++ ) tmp[i] = X.row_ptr[i]; for (long i=0 ; i<p ; i++) { row_ptr[i] = nnz; for ( long idx = X.row_ptr[i] ; idx<X.row_ptr[i+1] ; idx++ ) { col_idx[nnz] = X.col_idx[idx]; values[nnz] = X.values[idx]; nnz++; } for ( long j=i+1 ; j<p ; j++ ) { if ( tmp[j] < X.row_ptr[j+1] ) { if ( X.col_idx[tmp[j]] == i) { col_idx[nnz] = j; values[nnz] = X.values[tmp[j]]; nnz++; tmp[j]++; } } } } row_ptr[p] = nnz; return 0; } void print(FILE *fp) { fprintf(fp, "p: %ld, nnz: %ld\n", p, nnz); for ( long i=0 ; i<p ; i++ ) { for ( long idx = row_ptr[i] ; idx<row_ptr[i+1] ; idx++ ) { if ( (unsigned)id_map.size() == p ) fprintf(fp, "%ld %ld %f\n", id_map[i]+1, id_map[col_idx[idx]]+1, values[idx]); else fprintf(fp, "%ld %ld %f\n", i+1, col_idx[idx]+1, values[idx]); } } } void addblock(smat_t &A) { values.resize(nnz + A.nnz); for ( long i=0 ; i<A.nnz ; i++ ) values[i+nnz] = A.values[i]; col_idx.resize(nnz+A.nnz); for ( long i=0 ; i<A.nnz ; i++ ) col_idx[i+nnz] = A.col_idx[i]+p; row_ptr.resize(p+A.p+1); for ( long i=0 ; i<=A.p ; i++ ) row_ptr[i+p] = A.row_ptr[i]+nnz; p += A.p; nnz += A.nnz; } double comp_within_ratio(vector<long> &block_ind) { double within_w= 0, total_w = 0; for ( long i=0 ; i<p ; i++ ) for ( long idx = row_ptr[i] ; idx<row_ptr[i+1] ; idx++ ) { if ( block_ind[i] == block_ind[col_idx[idx]]) within_w += fabs(values[idx]); total_w += fabs(values[idx]); } return within_w/total_w; } /* void random_graph(long p_, double rate_) { p = p_; nnz = 0; srand(0); col_idx.resize(int(p*p*rate_/2)+100); values.resize(int(p*p*rate_/2)+100); row_ptr.resize(p+1); for (long i=0 ; i<p ; i++ ) { long subp = int((i+1)*rate_); row_ptr[i] = nnz; if ( subp > 0 ) { vector<long> rowii (subpb); for ( long j=0 ; j<subp ; j++ ) rowii[j] = rand()%p; sort(rowii.begin(), rowii.end()); col_idx[nnz] = rowii[0]; values[nnz] = rand()%2; if (values[nnz] == 0) values[nnz] = -1; values[nnz]*=0.1; nnz ++; for ( long j=1 ; j<subp ; j++ ) if ( rowii[j] != rowii[j-1] ) { col_idx[nnz] = rowii[j]; values[nnz] = rand()%2; if ( values[nnz] == 0 ) values[nnz] = -1; values[nnz]*=0.1; nnz++; } } col_idx[nnz] = i; values[nnz] = 1; nnz++; } row_ptr[p] = nnz; } */ void clustering(vector<long> &block_ind, long nblock) { int nvtxs = p ; int wgtflag = 0, numflag = 0,nparts = 1, options[11], edgecut=1 ; block_ind.resize(p); idxtype *xadj = (idxtype *)malloc(sizeof(idxtype)*(p+1)); for ( long i=0 ; i<=p ; i++) xadj[i] = row_ptr[i]; idxtype *adjncy = (idxtype *)malloc(sizeof(idxtype)*nnz); for ( long idx=0 ; idx<nnz ; idx++ ) adjncy[idx] = col_idx[idx]; idxtype *vwgt = (idxtype *)malloc(sizeof(idxtype)*p); for ( long i=0 ; i<p ; i++ ) vwgt[i] = 1; idxtype *adjwgt = (idxtype *)malloc(sizeof(idxtype)*nnz); for ( long idx=0 ; idx<nnz ; idx++ ) adjwgt[idx] = int(values[idx]*1000); nparts = nblock; //idxtype *part = (idxtype *)malloc(sizeof(idxtype)*p); options[0] = 0; char passToIdxmalloc[] = "main: part"; idxtype *part = idxmalloc(p, passToIdxmalloc); METIS_PartGraphKway(&nvtxs, xadj, adjncy, vwgt, adjwgt, &wgtflag, &numflag, &nparts, options, &edgecut, part); for ( long i=0 ; i<p ; i++ ) block_ind[i] = part[i]; free(xadj); free(adjncy); free(vwgt); free(adjwgt); free(part); } }; extern "C" { void QUIC(int p, int n, double* samples, double lambda, double tol, int msg, int maxIter, int nblock, int numthreads, smat_t& X, vector<double> &objlist, vector<double> &timelist); } #endif
mixed_tentusscher_myo_epi_2004_S1_4.c
// Scenario 1 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S1_4.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { static bool first_call = true; if(first_call) { print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n"); first_call = false; } // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } // Initial conditions for TenTusscher myocardium if (mapping[sv_id] == 0) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } // Initial conditions for TenTusscher epicardium else { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.5808390037434,0.00128660871673998,0.780017411965445,0.779866089420134,0.000174427830947983,0.485221044706665,0.00293766951726531,0.999998352403933,1.92945075222659e-08,1.88789743418140e-05,0.999774028269383,1.00656274895341,0.999980305363904,5.75119942688369e-05,0.652562498130868,9.24127402937561,140.252453661949}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = (uint32_t )i; for (int j = 0; j < num_steps; ++j) { if (mapping[i] == 0) solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]); else solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_myo(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Myocardium cell real Gks=0.062; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Myocardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; // [!] Myocardium cell R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; } void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_epi(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={14.1821693920716,0.000262369857178200,0.000171567529876738,0.000414005106483591,0.297500226048348,0.162622717394298,0.207515183338143,3.39980849488085,0.0224798791846427,2.56467648820225,1096.76282222310,0.000572145335603343,0.124382279366777,0.0197003709329121,0.00191117528600119,6.10868623397025e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
haval_fmt_plug.c
/* HAVAL cracker patch for JtR. Hacked together during April of 2013 by Dhiru * Kholia <dhiru at openwall.com>. * * This software is Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.com> 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. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_haval_256_3; extern struct fmt_main fmt_haval_128_4; #elif FMT_REGISTERS_H john_register_one(&fmt_haval_256_3); john_register_one(&fmt_haval_128_4); #else #include <string.h> #include "arch.h" #include "sph_haval.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #if !FAST_FORMATS_OMP #undef _OPENMP #endif #ifdef _OPENMP static int omp_t = 1; #include <omp.h> // Tuned on core i7 quad HT // 256-3 128-4 // 1 227k 228k // 64 6359k 5489k // 128 7953k 6654k // 256 8923k 7618k // 512 9804k 8223k // 1k 10307k 8569k ** set to this value // 2k 10081k 8427k // 4k 10551k 8893k #ifndef OMP_SCALE #ifdef __MIC__ #define OMP_SCALE 64 #else #define OMP_SCALE 1024 #endif // __MIC__ #endif // OMP_SCALE #endif // _OPENMP #include "memdbg.h" #define FORMAT_TAG "$haval$" #define TAG_LENGTH (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE256 32 #define BINARY_SIZE128 16 #define SALT_SIZE 0 #define BINARY_ALIGN 4 #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests haval_256_3_tests[] = { {"91850C6487C9829E791FC5B58E98E372F3063256BB7D313A93F1F83B426AEDCC", "HAVAL"}, {"$haval$91850C6487C9829E791FC5B58E98E372F3063256BB7D313A93F1F83B426AEDCC", "HAVAL"}, // john.pot uses lower case hex, so repeat that hash with lower case hex {"$haval$91850c6487c9829e791fc5b58e98e372f3063256bb7d313a93f1f83b426aedcc", "HAVAL"}, {"8699f1e3384d05b2a84b032693e2b6f46df85a13a50d93808d6874bb8fb9e86c", "abc"}, {"$haval$8699f1e3384d05b2a84b032693e2b6f46df85a13a50d93808d6874bb8fb9e86c", "abc"}, {"cd43bec91c50e5f781fc50a78a3e9c8c48b407fa35a20c972178d63867dbe158", "john"}, {"$haval$cd43bec91c50e5f781fc50a78a3e9c8c48b407fa35a20c972178d63867dbe158", "john"}, {"5aa9c913463f82260071629c8ac2c54d73b3af016ffd8e8ce128558d909fab06", "passweird"}, {"$haval$5aa9c913463f82260071629c8ac2c54d73b3af016ffd8e8ce128558d909fab06", "passweird"}, {NULL} }; static struct fmt_tests haval_128_4_tests[] = { {"EE6BBF4D6A46A679B3A856C88538BB98", ""}, {"$haval$ee6bbf4d6a46a679b3a856c88538bb98", ""}, {"6f2132867c9648419adcd5013e532fa2", "abc"}, {"$haval$6f2132867c9648419adcd5013e532fa2", "abc"}, {"c98232b4ae6e7ef3235e838387111f23", "john"}, {"$haval$c98232b4ae6e7ef3235e838387111f23", "john"}, {"50683b38df349781b2ef29e7720eb730", "passweird"}, {"$haval$50683b38df349781b2ef29e7720eb730", "passweird"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE256 / sizeof(uint32_t)]; 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 if (!saved_key) { saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self, int len) { char *p; p = ciphertext; if (!strncmp(p, FORMAT_TAG, TAG_LENGTH)) p += TAG_LENGTH; if (strnlen(p, len + 1) != len) return 0; while(*p) if (atoi16[ARCH_INDEX(*p++)] == 0x7f) return 0; return 1; } /* we need independent valids, since the $haval$ signature is the same */ /* otherwise, if we have input with a mix of both types, then ALL of them */ /* will validate, even though only the ones of the proper type will actually */ /* be tested. If we had a singleton crypt function (which both 128-4 and */ /* 256-3 used, then a single valid would also work. But since each have */ /* their own crypt, and they are NOT compatible, then we need separate valids */ static int valid3(char *ciphertext, struct fmt_main *self) { return valid(ciphertext, self, 64); } static int valid4(char *ciphertext, struct fmt_main *self) { return valid(ciphertext, self, 32); } static void *get_binary_256(char *ciphertext) { static union { unsigned char c[32]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) p = strrchr(ciphertext, '$') + 1; else p = ciphertext; for (i = 0; i < 32; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static void *get_binary_128(char *ciphertext) { static union { unsigned char c[16]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) p = strrchr(ciphertext, '$') + 1; else p = ciphertext; for (i = 0; i < 16; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static int crypt_256_3(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { sph_haval256_3_context ctx; sph_haval256_3_init(&ctx); sph_haval256_3(&ctx, saved_key[index], strlen(saved_key[index])); sph_haval256_3_close(&ctx, (unsigned char*)crypt_out[index]); } return count; } static int crypt_128_4(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { sph_haval128_4_context ctx; sph_haval128_4_init(&ctx); sph_haval128_4(&ctx, saved_key[index], strlen(saved_key[index])); sph_haval128_4_close(&ctx, (unsigned char*)crypt_out[index]); } return count; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one256(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE256); } static int cmp_one128(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE128); } static int cmp_exact(char *source, int index) { return 1; } static void haval_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 char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[TAG_LENGTH + 2 * BINARY_SIZE256 + 1]; if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) ciphertext += TAG_LENGTH; strcpy(out, FORMAT_TAG); strcpy(&out[TAG_LENGTH], ciphertext); strlwr(&out[TAG_LENGTH]); return out; } struct fmt_main fmt_haval_256_3 = { { "HAVAL-256-3", "", ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE256, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE, { NULL }, { FORMAT_TAG }, haval_256_3_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid3, split, get_binary_256, fmt_default_salt, { NULL }, 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, NULL, fmt_default_set_salt, haval_set_key, get_key, fmt_default_clear_keys, crypt_256_3, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one256, cmp_exact } }; struct fmt_main fmt_haval_128_4 = { { "HAVAL-128-4", "", ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE128, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE, { NULL }, { NULL }, haval_128_4_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid4, split, get_binary_128, fmt_default_salt, { NULL }, 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, NULL, fmt_default_set_salt, haval_set_key, get_key, fmt_default_clear_keys, crypt_128_4, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one128, cmp_exact } }; #endif /* plugin stanza */
a.29.1.c
/* { dg-do run } */ #include <assert.h> int A[2][2] = { 1, 2, 3, 4 }; void f (int n, int B[n][n], int C[]) { int D[2][2] = { 1, 2, 3, 4 }; int E[n][n]; assert (n >= 2); E[1][1] = 4; #pragma omp parallel firstprivate(B, C, D, E) { assert (sizeof (B) == sizeof (int (*)[n])); /* { dg-warning "on array function parameter" } */ assert (sizeof (C) == sizeof (int *)); /* { dg-warning "on array function parameter" } */ assert (sizeof (D) == 4 * sizeof (int)); assert (sizeof (E) == n * n * sizeof (int)); /* Private B and C have values of original B and C. */ assert (&B[1][1] == &A[1][1]); assert (&C[3] == &A[1][1]); assert (D[1][1] == 4); assert (E[1][1] == 4); } } int main () { f (2, A, A[0]); return 0; }
tree-ssa-loop-ivcanon.c
/* Induction variable canonicalization and loop peeling. Copyright (C) 2004-2015 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ /* This pass detects the loops that iterate a constant number of times, adds a canonical induction variable (step -1, tested against 0) and replaces the exit test. This enables the less powerful rtl level analysis to use this information. This might spoil the code in some cases (by increasing register pressure). Note that in the case the new variable is not needed, ivopts will get rid of it, so it might only be a problem when there are no other linear induction variables. In that case the created optimization possibilities are likely to pay up. We also perform - complete unrolling (or peeling) when the loops is rolling few enough times - simple peeling (i.e. copying few initial iterations prior the loop) when number of iteration estimate is known (typically by the profile info). */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "hash-set.h" #include "machmode.h" #include "vec.h" #include "double-int.h" #include "input.h" #include "alias.h" #include "symtab.h" #include "wide-int.h" #include "inchash.h" #include "tree.h" #include "fold-const.h" #include "tm_p.h" #include "profile.h" #include "predict.h" #include "hard-reg-set.h" #include "input.h" #include "function.h" #include "dominance.h" #include "cfg.h" #include "basic-block.h" #include "gimple-pretty-print.h" #include "tree-ssa-alias.h" #include "internal-fn.h" #include "gimple-fold.h" #include "tree-eh.h" #include "gimple-expr.h" #include "is-a.h" #include "gimple.h" #include "gimple-iterator.h" #include "gimple-ssa.h" #include "hash-map.h" #include "plugin-api.h" #include "ipa-ref.h" #include "cgraph.h" #include "tree-cfg.h" #include "tree-phinodes.h" #include "ssa-iterators.h" #include "stringpool.h" #include "tree-ssanames.h" #include "tree-ssa-loop-manip.h" #include "tree-ssa-loop-niter.h" #include "tree-ssa-loop.h" #include "tree-into-ssa.h" #include "cfgloop.h" #include "tree-pass.h" #include "tree-chrec.h" #include "tree-scalar-evolution.h" #include "params.h" #include "flags.h" #include "tree-inline.h" #include "target.h" #include "tree-cfgcleanup.h" #include "builtins.h" /* Specifies types of loops that may be unrolled. */ enum unroll_level { UL_SINGLE_ITER, /* Only loops that exit immediately in the first iteration. */ UL_NO_GROWTH, /* Only loops whose unrolling will not cause increase of code size. */ UL_ALL /* All suitable loops. */ }; /* Adds a canonical induction variable to LOOP iterating NITER times. EXIT is the exit edge whose condition is replaced. */ static void create_canonical_iv (struct loop *loop, edge exit, tree niter) { edge in; tree type, var; gcond *cond; gimple_stmt_iterator incr_at; enum tree_code cmp; if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "Added canonical iv to loop %d, ", loop->num); print_generic_expr (dump_file, niter, TDF_SLIM); fprintf (dump_file, " iterations.\n"); } cond = as_a <gcond *> (last_stmt (exit->src)); in = EDGE_SUCC (exit->src, 0); if (in == exit) in = EDGE_SUCC (exit->src, 1); /* Note that we do not need to worry about overflows, since type of niter is always unsigned and all comparisons are just for equality/nonequality -- i.e. everything works with a modulo arithmetics. */ type = TREE_TYPE (niter); niter = fold_build2 (PLUS_EXPR, type, niter, build_int_cst (type, 1)); incr_at = gsi_last_bb (in->src); create_iv (niter, build_int_cst (type, -1), NULL_TREE, loop, &incr_at, false, NULL, &var); cmp = (exit->flags & EDGE_TRUE_VALUE) ? EQ_EXPR : NE_EXPR; gimple_cond_set_code (cond, cmp); gimple_cond_set_lhs (cond, var); gimple_cond_set_rhs (cond, build_int_cst (type, 0)); update_stmt (cond); } /* Describe size of loop as detected by tree_estimate_loop_size. */ struct loop_size { /* Number of instructions in the loop. */ int overall; /* Number of instructions that will be likely optimized out in peeled iterations of loop (i.e. computation based on induction variable where induction variable starts at known constant.) */ int eliminated_by_peeling; /* Same statistics for last iteration of loop: it is smaller because instructions after exit are not executed. */ int last_iteration; int last_iteration_eliminated_by_peeling; /* If some IV computation will become constant. */ bool constant_iv; /* Number of call stmts that are not a builtin and are pure or const present on the hot path. */ int num_pure_calls_on_hot_path; /* Number of call stmts that are not a builtin and are not pure nor const present on the hot path. */ int num_non_pure_calls_on_hot_path; /* Number of statements other than calls in the loop. */ int non_call_stmts_on_hot_path; /* Number of branches seen on the hot path. */ int num_branches_on_hot_path; }; /* Return true if OP in STMT will be constant after peeling LOOP. */ static bool constant_after_peeling (tree op, gimple stmt, struct loop *loop) { affine_iv iv; if (is_gimple_min_invariant (op)) return true; /* We can still fold accesses to constant arrays when index is known. */ if (TREE_CODE (op) != SSA_NAME) { tree base = op; /* First make fast look if we see constant array inside. */ while (handled_component_p (base)) base = TREE_OPERAND (base, 0); if ((DECL_P (base) && ctor_for_folding (base) != error_mark_node) || CONSTANT_CLASS_P (base)) { /* If so, see if we understand all the indices. */ base = op; while (handled_component_p (base)) { if (TREE_CODE (base) == ARRAY_REF && !constant_after_peeling (TREE_OPERAND (base, 1), stmt, loop)) return false; base = TREE_OPERAND (base, 0); } return true; } return false; } /* Induction variables are constants. */ if (!simple_iv (loop, loop_containing_stmt (stmt), op, &iv, false)) return false; if (!is_gimple_min_invariant (iv.base)) return false; if (!is_gimple_min_invariant (iv.step)) return false; return true; } /* Computes an estimated number of insns in LOOP. EXIT (if non-NULL) is an exite edge that will be eliminated in all but last iteration of the loop. EDGE_TO_CANCEL (if non-NULL) is an non-exit edge eliminated in the last iteration of loop. Return results in SIZE, estimate benefits for complete unrolling exiting by EXIT. Stop estimating after UPPER_BOUND is met. Return true in this case. */ static bool tree_estimate_loop_size (struct loop *loop, edge exit, edge edge_to_cancel, struct loop_size *size, int upper_bound) { basic_block *body = get_loop_body (loop); gimple_stmt_iterator gsi; unsigned int i; bool after_exit; vec<basic_block> path = get_loop_hot_path (loop); size->overall = 0; size->eliminated_by_peeling = 0; size->last_iteration = 0; size->last_iteration_eliminated_by_peeling = 0; size->num_pure_calls_on_hot_path = 0; size->num_non_pure_calls_on_hot_path = 0; size->non_call_stmts_on_hot_path = 0; size->num_branches_on_hot_path = 0; size->constant_iv = 0; if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Estimating sizes for loop %i\n", loop->num); for (i = 0; i < loop->num_nodes; i++) { if (edge_to_cancel && body[i] != edge_to_cancel->src && dominated_by_p (CDI_DOMINATORS, body[i], edge_to_cancel->src)) after_exit = true; else after_exit = false; if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " BB: %i, after_exit: %i\n", body[i]->index, after_exit); for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi); gsi_next (&gsi)) { gimple stmt = gsi_stmt (gsi); int num = estimate_num_insns (stmt, &eni_size_weights); bool likely_eliminated = false; bool likely_eliminated_last = false; bool likely_eliminated_peeled = false; if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, " size: %3i ", num); print_gimple_stmt (dump_file, gsi_stmt (gsi), 0, 0); } /* Look for reasons why we might optimize this stmt away. */ if (gimple_has_side_effects (stmt)) ; /* Exit conditional. */ else if (exit && body[i] == exit->src && stmt == last_stmt (exit->src)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " Exit condition will be eliminated " "in peeled copies.\n"); likely_eliminated_peeled = true; } else if (edge_to_cancel && body[i] == edge_to_cancel->src && stmt == last_stmt (edge_to_cancel->src)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " Exit condition will be eliminated " "in last copy.\n"); likely_eliminated_last = true; } /* Sets of IV variables */ else if (gimple_code (stmt) == GIMPLE_ASSIGN && constant_after_peeling (gimple_assign_lhs (stmt), stmt, loop)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " Induction variable computation will" " be folded away.\n"); likely_eliminated = true; } /* Assignments of IV variables. */ else if (gimple_code (stmt) == GIMPLE_ASSIGN && TREE_CODE (gimple_assign_lhs (stmt)) == SSA_NAME && constant_after_peeling (gimple_assign_rhs1 (stmt), stmt, loop) && (gimple_assign_rhs_class (stmt) != GIMPLE_BINARY_RHS || constant_after_peeling (gimple_assign_rhs2 (stmt), stmt, loop))) { size->constant_iv = true; if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " Constant expression will be folded away.\n"); likely_eliminated = true; } /* Conditionals. */ else if ((gimple_code (stmt) == GIMPLE_COND && constant_after_peeling (gimple_cond_lhs (stmt), stmt, loop) && constant_after_peeling (gimple_cond_rhs (stmt), stmt, loop)) || (gimple_code (stmt) == GIMPLE_SWITCH && constant_after_peeling (gimple_switch_index ( as_a <gswitch *> (stmt)), stmt, loop))) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, " Constant conditional.\n"); likely_eliminated = true; } size->overall += num; if (likely_eliminated || likely_eliminated_peeled) size->eliminated_by_peeling += num; if (!after_exit) { size->last_iteration += num; if (likely_eliminated || likely_eliminated_last) size->last_iteration_eliminated_by_peeling += num; } if ((size->overall * 3 / 2 - size->eliminated_by_peeling - size->last_iteration_eliminated_by_peeling) > upper_bound) { free (body); path.release (); return true; } } } while (path.length ()) { basic_block bb = path.pop (); for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi)) { gimple stmt = gsi_stmt (gsi); if (gimple_code (stmt) == GIMPLE_CALL) { int flags = gimple_call_flags (stmt); tree decl = gimple_call_fndecl (stmt); if (decl && DECL_IS_BUILTIN (decl) && is_inexpensive_builtin (decl)) ; else if (flags & (ECF_PURE | ECF_CONST)) size->num_pure_calls_on_hot_path++; else size->num_non_pure_calls_on_hot_path++; size->num_branches_on_hot_path ++; } else if (gimple_code (stmt) != GIMPLE_CALL && gimple_code (stmt) != GIMPLE_DEBUG) size->non_call_stmts_on_hot_path++; if (((gimple_code (stmt) == GIMPLE_COND && (!constant_after_peeling (gimple_cond_lhs (stmt), stmt, loop) || constant_after_peeling (gimple_cond_rhs (stmt), stmt, loop))) || (gimple_code (stmt) == GIMPLE_SWITCH && !constant_after_peeling (gimple_switch_index ( as_a <gswitch *> (stmt)), stmt, loop))) && (!exit || bb != exit->src)) size->num_branches_on_hot_path++; } } path.release (); if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "size: %i-%i, last_iteration: %i-%i\n", size->overall, size->eliminated_by_peeling, size->last_iteration, size->last_iteration_eliminated_by_peeling); free (body); return false; } /* Estimate number of insns of completely unrolled loop. It is (NUNROLL + 1) * size of loop body with taking into account the fact that in last copy everything after exit conditional is dead and that some instructions will be eliminated after peeling. Loop body is likely going to simplify further, this is difficult to guess, we just decrease the result by 1/3. */ static unsigned HOST_WIDE_INT estimated_unrolled_size (struct loop_size *size, unsigned HOST_WIDE_INT nunroll) { HOST_WIDE_INT unr_insns = ((nunroll) * (HOST_WIDE_INT) (size->overall - size->eliminated_by_peeling)); if (!nunroll) unr_insns = 0; unr_insns += size->last_iteration - size->last_iteration_eliminated_by_peeling; unr_insns = unr_insns * 2 / 3; if (unr_insns <= 0) unr_insns = 1; return unr_insns; } /* Loop LOOP is known to not loop. See if there is an edge in the loop body that can be remove to make the loop to always exit and at the same time it does not make any code potentially executed during the last iteration dead. After complete unrolling we still may get rid of the conditional on the exit in the last copy even if we have no idea what it does. This is quite common case for loops of form int a[5]; for (i=0;i<b;i++) a[i]=0; Here we prove the loop to iterate 5 times but we do not know it from induction variable. For now we handle only simple case where there is exit condition just before the latch block and the latch block contains no statements with side effect that may otherwise terminate the execution of loop (such as by EH or by terminating the program or longjmp). In the general case we may want to cancel the paths leading to statements loop-niter identified as having undefined effect in the last iteration. The other cases are hopefully rare and will be cleaned up later. */ static edge loop_edge_to_cancel (struct loop *loop) { vec<edge> exits; unsigned i; edge edge_to_cancel; gimple_stmt_iterator gsi; /* We want only one predecestor of the loop. */ if (EDGE_COUNT (loop->latch->preds) > 1) return NULL; exits = get_loop_exit_edges (loop); FOR_EACH_VEC_ELT (exits, i, edge_to_cancel) { /* Find the other edge than the loop exit leaving the conditoinal. */ if (EDGE_COUNT (edge_to_cancel->src->succs) != 2) continue; if (EDGE_SUCC (edge_to_cancel->src, 0) == edge_to_cancel) edge_to_cancel = EDGE_SUCC (edge_to_cancel->src, 1); else edge_to_cancel = EDGE_SUCC (edge_to_cancel->src, 0); /* We only can handle conditionals. */ if (!(edge_to_cancel->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE))) continue; /* We should never have conditionals in the loop latch. */ gcc_assert (edge_to_cancel->dest != loop->header); /* Check that it leads to loop latch. */ if (edge_to_cancel->dest != loop->latch) continue; exits.release (); /* Verify that the code in loop latch does nothing that may end program execution without really reaching the exit. This may include non-pure/const function calls, EH statements, volatile ASMs etc. */ for (gsi = gsi_start_bb (loop->latch); !gsi_end_p (gsi); gsi_next (&gsi)) if (gimple_has_side_effects (gsi_stmt (gsi))) return NULL; return edge_to_cancel; } exits.release (); return NULL; } /* Remove all tests for exits that are known to be taken after LOOP was peeled NPEELED times. Put gcc_unreachable before every statement known to not be executed. */ static bool remove_exits_and_undefined_stmts (struct loop *loop, unsigned int npeeled) { struct nb_iter_bound *elt; bool changed = false; for (elt = loop->bounds; elt; elt = elt->next) { /* If statement is known to be undefined after peeling, turn it into unreachable (or trap when debugging experience is supposed to be good). */ if (!elt->is_exit && wi::ltu_p (elt->bound, npeeled)) { gimple_stmt_iterator gsi = gsi_for_stmt (elt->stmt); gcall *stmt = gimple_build_call (builtin_decl_implicit (BUILT_IN_UNREACHABLE), 0); gimple_set_location (stmt, gimple_location (elt->stmt)); gsi_insert_before (&gsi, stmt, GSI_NEW_STMT); split_block (gimple_bb (stmt), stmt); changed = true; if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "Forced statement unreachable: "); print_gimple_stmt (dump_file, elt->stmt, 0, 0); } } /* If we know the exit will be taken after peeling, update. */ else if (elt->is_exit && wi::leu_p (elt->bound, npeeled)) { basic_block bb = gimple_bb (elt->stmt); edge exit_edge = EDGE_SUCC (bb, 0); if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "Forced exit to be taken: "); print_gimple_stmt (dump_file, elt->stmt, 0, 0); } if (!loop_exit_edge_p (loop, exit_edge)) exit_edge = EDGE_SUCC (bb, 1); gcc_checking_assert (loop_exit_edge_p (loop, exit_edge)); gcond *cond_stmt = as_a <gcond *> (elt->stmt); if (exit_edge->flags & EDGE_TRUE_VALUE) gimple_cond_make_true (cond_stmt); else gimple_cond_make_false (cond_stmt); update_stmt (cond_stmt); changed = true; } } return changed; } /* Remove all exits that are known to be never taken because of the loop bound discovered. */ static bool remove_redundant_iv_tests (struct loop *loop) { struct nb_iter_bound *elt; bool changed = false; if (!loop->any_upper_bound) return false; for (elt = loop->bounds; elt; elt = elt->next) { /* Exit is pointless if it won't be taken before loop reaches upper bound. */ if (elt->is_exit && loop->any_upper_bound && wi::ltu_p (loop->nb_iterations_upper_bound, elt->bound)) { basic_block bb = gimple_bb (elt->stmt); edge exit_edge = EDGE_SUCC (bb, 0); struct tree_niter_desc niter; if (!loop_exit_edge_p (loop, exit_edge)) exit_edge = EDGE_SUCC (bb, 1); /* Only when we know the actual number of iterations, not just a bound, we can remove the exit. */ if (!number_of_iterations_exit (loop, exit_edge, &niter, false, false) || !integer_onep (niter.assumptions) || !integer_zerop (niter.may_be_zero) || !niter.niter || TREE_CODE (niter.niter) != INTEGER_CST || !wi::ltu_p (loop->nb_iterations_upper_bound, wi::to_widest (niter.niter))) continue; if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "Removed pointless exit: "); print_gimple_stmt (dump_file, elt->stmt, 0, 0); } gcond *cond_stmt = as_a <gcond *> (elt->stmt); if (exit_edge->flags & EDGE_TRUE_VALUE) gimple_cond_make_false (cond_stmt); else gimple_cond_make_true (cond_stmt); update_stmt (cond_stmt); changed = true; } } return changed; } /* Stores loops that will be unlooped after we process whole loop tree. */ static vec<loop_p> loops_to_unloop; static vec<int> loops_to_unloop_nunroll; /* Cancel all fully unrolled loops by putting __builtin_unreachable on the latch edge. We do it after all unrolling since unlooping moves basic blocks across loop boundaries trashing loop closed SSA form as well as SCEV info needed to be intact during unrolling. IRRED_INVALIDATED is used to bookkeep if information about irreducible regions may become invalid as a result of the transformation. LOOP_CLOSED_SSA_INVALIDATED is used to bookkepp the case when we need to go into loop closed SSA form. */ static void unloop_loops (bitmap loop_closed_ssa_invalidated, bool *irred_invalidated) { while (loops_to_unloop.length ()) { struct loop *loop = loops_to_unloop.pop (); int n_unroll = loops_to_unloop_nunroll.pop (); basic_block latch = loop->latch; edge latch_edge = loop_latch_edge (loop); int flags = latch_edge->flags; location_t locus = latch_edge->goto_locus; gcall *stmt; gimple_stmt_iterator gsi; remove_exits_and_undefined_stmts (loop, n_unroll); /* Unloop destroys the latch edge. */ unloop (loop, irred_invalidated, loop_closed_ssa_invalidated); /* Create new basic block for the latch edge destination and wire it in. */ stmt = gimple_build_call (builtin_decl_implicit (BUILT_IN_UNREACHABLE), 0); latch_edge = make_edge (latch, create_basic_block (NULL, NULL, latch), flags); latch_edge->probability = 0; latch_edge->count = 0; latch_edge->flags |= flags; latch_edge->goto_locus = locus; latch_edge->dest->loop_father = current_loops->tree_root; latch_edge->dest->count = 0; latch_edge->dest->frequency = 0; set_immediate_dominator (CDI_DOMINATORS, latch_edge->dest, latch_edge->src); gsi = gsi_start_bb (latch_edge->dest); gsi_insert_after (&gsi, stmt, GSI_NEW_STMT); } loops_to_unloop.release (); loops_to_unloop_nunroll.release (); } /* Tries to unroll LOOP completely, i.e. NITER times. UL determines which loops we are allowed to unroll. EXIT is the exit of the loop that should be eliminated. MAXITER specfy bound on number of iterations, -1 if it is not known or too large for HOST_WIDE_INT. The location LOCUS corresponding to the loop is used when emitting a summary of the unroll to the dump file. */ static bool try_unroll_loop_completely (struct loop *loop, edge exit, tree niter, enum unroll_level ul, HOST_WIDE_INT maxiter, location_t locus) { unsigned HOST_WIDE_INT n_unroll = 0, ninsns, unr_insns; struct loop_size size; bool n_unroll_found = false; edge edge_to_cancel = NULL; int report_flags = MSG_OPTIMIZED_LOCATIONS | TDF_RTL | TDF_DETAILS; /* See if we proved number of iterations to be low constant. EXIT is an edge that will be removed in all but last iteration of the loop. EDGE_TO_CACNEL is an edge that will be removed from the last iteration of the unrolled sequence and is expected to make the final loop not rolling. If the number of execution of loop is determined by standard induction variable test, then EXIT and EDGE_TO_CANCEL are the two edges leaving from the iv test. */ if (tree_fits_uhwi_p (niter)) { n_unroll = tree_to_uhwi (niter); n_unroll_found = true; edge_to_cancel = EDGE_SUCC (exit->src, 0); if (edge_to_cancel == exit) edge_to_cancel = EDGE_SUCC (exit->src, 1); } /* We do not know the number of iterations and thus we can not eliminate the EXIT edge. */ else exit = NULL; /* See if we can improve our estimate by using recorded loop bounds. */ if (maxiter >= 0 && (!n_unroll_found || (unsigned HOST_WIDE_INT)maxiter < n_unroll)) { n_unroll = maxiter; n_unroll_found = true; /* Loop terminates before the IV variable test, so we can not remove it in the last iteration. */ edge_to_cancel = NULL; } if (!n_unroll_found) return false; if (n_unroll > (unsigned) PARAM_VALUE (PARAM_MAX_COMPLETELY_PEEL_TIMES)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Not unrolling loop %d " "(--param max-completely-peeled-times limit reached).\n", loop->num); return false; } if (!edge_to_cancel) edge_to_cancel = loop_edge_to_cancel (loop); if (n_unroll) { sbitmap wont_exit; edge e; unsigned i; bool large; vec<edge> to_remove = vNULL; if (ul == UL_SINGLE_ITER) return false; large = tree_estimate_loop_size (loop, exit, edge_to_cancel, &size, PARAM_VALUE (PARAM_MAX_COMPLETELY_PEELED_INSNS)); ninsns = size.overall; if (large) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Not unrolling loop %d: it is too large.\n", loop->num); return false; } unr_insns = estimated_unrolled_size (&size, n_unroll); if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, " Loop size: %d\n", (int) ninsns); fprintf (dump_file, " Estimated size after unrolling: %d\n", (int) unr_insns); } /* If the code is going to shrink, we don't need to be extra cautious on guessing if the unrolling is going to be profitable. */ if (unr_insns /* If there is IV variable that will become constant, we save one instruction in the loop prologue we do not account otherwise. */ <= ninsns + (size.constant_iv != false)) ; /* We unroll only inner loops, because we do not consider it profitable otheriwse. We still can cancel loopback edge of not rolling loop; this is always a good idea. */ else if (ul == UL_NO_GROWTH) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Not unrolling loop %d: size would grow.\n", loop->num); return false; } /* Outer loops tend to be less interesting candidates for complete unrolling unless we can do a lot of propagation into the inner loop body. For now we disable outer loop unrolling when the code would grow. */ else if (loop->inner) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Not unrolling loop %d: " "it is not innermost and code would grow.\n", loop->num); return false; } /* If there is call on a hot path through the loop, then there is most probably not much to optimize. */ else if (size.num_non_pure_calls_on_hot_path) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Not unrolling loop %d: " "contains call and code would grow.\n", loop->num); return false; } /* If there is pure/const call in the function, then we can still optimize the unrolled loop body if it contains some other interesting code than the calls and code storing or cumulating the return value. */ else if (size.num_pure_calls_on_hot_path /* One IV increment, one test, one ivtmp store and one useful stmt. That is about minimal loop doing pure call. */ && (size.non_call_stmts_on_hot_path <= 3 + size.num_pure_calls_on_hot_path)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Not unrolling loop %d: " "contains just pure calls and code would grow.\n", loop->num); return false; } /* Complette unrolling is major win when control flow is removed and one big basic block is created. If the loop contains control flow the optimization may still be a win because of eliminating the loop overhead but it also may blow the branch predictor tables. Limit number of branches on the hot path through the peeled sequence. */ else if (size.num_branches_on_hot_path * (int)n_unroll > PARAM_VALUE (PARAM_MAX_PEEL_BRANCHES)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Not unrolling loop %d: " " number of branches on hot path in the unrolled sequence" " reach --param max-peel-branches limit.\n", loop->num); return false; } else if (unr_insns > (unsigned) PARAM_VALUE (PARAM_MAX_COMPLETELY_PEELED_INSNS)) { if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Not unrolling loop %d: " "(--param max-completely-peeled-insns limit reached).\n", loop->num); return false; } dump_printf_loc (report_flags, locus, "loop turned into non-loop; it never loops.\n"); initialize_original_copy_tables (); wont_exit = sbitmap_alloc (n_unroll + 1); bitmap_ones (wont_exit); bitmap_clear_bit (wont_exit, 0); if (!gimple_duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop), n_unroll, wont_exit, exit, &to_remove, DLTHE_FLAG_UPDATE_FREQ | DLTHE_FLAG_COMPLETTE_PEEL)) { free_original_copy_tables (); free (wont_exit); if (dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Failed to duplicate the loop\n"); return false; } FOR_EACH_VEC_ELT (to_remove, i, e) { bool ok = remove_path (e); gcc_assert (ok); } to_remove.release (); free (wont_exit); free_original_copy_tables (); } /* Remove the conditional from the last copy of the loop. */ if (edge_to_cancel) { gcond *cond = as_a <gcond *> (last_stmt (edge_to_cancel->src)); if (edge_to_cancel->flags & EDGE_TRUE_VALUE) gimple_cond_make_false (cond); else gimple_cond_make_true (cond); update_stmt (cond); /* Do not remove the path. Doing so may remove outer loop and confuse bookkeeping code in tree_unroll_loops_completelly. */ } /* Store the loop for later unlooping and exit removal. */ loops_to_unloop.safe_push (loop); loops_to_unloop_nunroll.safe_push (n_unroll); if (dump_enabled_p ()) { if (!n_unroll) dump_printf_loc (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, locus, "loop turned into non-loop; it never loops\n"); else { dump_printf_loc (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, locus, "loop with %d iterations completely unrolled", (int) (n_unroll + 1)); if (profile_info) dump_printf (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, " (header execution count %d)", (int)loop->header->count); dump_printf (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, "\n"); } } if (dump_file && (dump_flags & TDF_DETAILS)) { if (exit) fprintf (dump_file, "Exit condition of peeled iterations was " "eliminated.\n"); if (edge_to_cancel) fprintf (dump_file, "Last iteration exit edge was proved true.\n"); else fprintf (dump_file, "Latch of last iteration was marked by " "__builtin_unreachable ().\n"); } return true; } /* Return number of instructions after peeling. */ static unsigned HOST_WIDE_INT estimated_peeled_sequence_size (struct loop_size *size, unsigned HOST_WIDE_INT npeel) { return MAX (npeel * (HOST_WIDE_INT) (size->overall - size->eliminated_by_peeling), 1); } /* If the loop is expected to iterate N times and is small enough, duplicate the loop body N+1 times before the loop itself. This way the hot path will never enter the loop. Parameters are the same as for try_unroll_loops_completely */ static bool try_peel_loop (struct loop *loop, edge exit, tree niter, HOST_WIDE_INT maxiter) { int npeel; struct loop_size size; int peeled_size; sbitmap wont_exit; unsigned i; vec<edge> to_remove = vNULL; edge e; /* If the iteration bound is known and large, then we can safely eliminate the check in peeled copies. */ if (TREE_CODE (niter) != INTEGER_CST) exit = NULL; if (!flag_peel_loops || PARAM_VALUE (PARAM_MAX_PEEL_TIMES) <= 0) return false; /* Peel only innermost loops. */ if (loop->inner) { if (dump_file) fprintf (dump_file, "Not peeling: outer loop\n"); return false; } if (!optimize_loop_for_speed_p (loop)) { if (dump_file) fprintf (dump_file, "Not peeling: cold loop\n"); return false; } /* Check if there is an estimate on the number of iterations. */ npeel = estimated_loop_iterations_int (loop); if (npeel < 0) { if (dump_file) fprintf (dump_file, "Not peeling: number of iterations is not " "estimated\n"); return false; } if (maxiter >= 0 && maxiter <= npeel) { if (dump_file) fprintf (dump_file, "Not peeling: upper bound is known so can " "unroll completely\n"); return false; } /* We want to peel estimated number of iterations + 1 (so we never enter the loop on quick path). Check against PARAM_MAX_PEEL_TIMES and be sure to avoid overflows. */ if (npeel > PARAM_VALUE (PARAM_MAX_PEEL_TIMES) - 1) { if (dump_file) fprintf (dump_file, "Not peeling: rolls too much " "(%i + 1 > --param max-peel-times)\n", npeel); return false; } npeel++; /* Check peeled loops size. */ tree_estimate_loop_size (loop, exit, NULL, &size, PARAM_VALUE (PARAM_MAX_PEELED_INSNS)); if ((peeled_size = estimated_peeled_sequence_size (&size, npeel)) > PARAM_VALUE (PARAM_MAX_PEELED_INSNS)) { if (dump_file) fprintf (dump_file, "Not peeling: peeled sequence size is too large " "(%i insns > --param max-peel-insns)", peeled_size); return false; } /* Duplicate possibly eliminating the exits. */ initialize_original_copy_tables (); wont_exit = sbitmap_alloc (npeel + 1); bitmap_ones (wont_exit); bitmap_clear_bit (wont_exit, 0); if (!gimple_duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop), npeel, wont_exit, exit, &to_remove, DLTHE_FLAG_UPDATE_FREQ | DLTHE_FLAG_COMPLETTE_PEEL)) { free_original_copy_tables (); free (wont_exit); return false; } FOR_EACH_VEC_ELT (to_remove, i, e) { bool ok = remove_path (e); gcc_assert (ok); } free (wont_exit); free_original_copy_tables (); if (dump_file && (dump_flags & TDF_DETAILS)) { fprintf (dump_file, "Peeled loop %d, %i times.\n", loop->num, npeel); } if (loop->any_upper_bound) loop->nb_iterations_upper_bound -= npeel; loop->nb_iterations_estimate = 0; /* Make sure to mark loop cold so we do not try to peel it more. */ scale_loop_profile (loop, 1, 0); loop->header->count = 0; return true; } /* Adds a canonical induction variable to LOOP if suitable. CREATE_IV is true if we may create a new iv. UL determines which loops we are allowed to completely unroll. If TRY_EVAL is true, we try to determine the number of iterations of a loop by direct evaluation. Returns true if cfg is changed. */ static bool canonicalize_loop_induction_variables (struct loop *loop, bool create_iv, enum unroll_level ul, bool try_eval) { edge exit = NULL; tree niter; HOST_WIDE_INT maxiter; bool modified = false; location_t locus = UNKNOWN_LOCATION; niter = number_of_latch_executions (loop); exit = single_exit (loop); if (TREE_CODE (niter) == INTEGER_CST) locus = gimple_location (last_stmt (exit->src)); else { /* If the loop has more than one exit, try checking all of them for # of iterations determinable through scev. */ if (!exit) niter = find_loop_niter (loop, &exit); /* Finally if everything else fails, try brute force evaluation. */ if (try_eval && (chrec_contains_undetermined (niter) || TREE_CODE (niter) != INTEGER_CST)) niter = find_loop_niter_by_eval (loop, &exit); if (exit) locus = gimple_location (last_stmt (exit->src)); if (TREE_CODE (niter) != INTEGER_CST) exit = NULL; } /* We work exceptionally hard here to estimate the bound by find_loop_niter_by_eval. Be sure to keep it for future. */ if (niter && TREE_CODE (niter) == INTEGER_CST) { record_niter_bound (loop, wi::to_widest (niter), exit == single_likely_exit (loop), true); } /* Force re-computation of loop bounds so we can remove redundant exits. */ maxiter = max_loop_iterations_int (loop); if (dump_file && (dump_flags & TDF_DETAILS) && TREE_CODE (niter) == INTEGER_CST) { fprintf (dump_file, "Loop %d iterates ", loop->num); print_generic_expr (dump_file, niter, TDF_SLIM); fprintf (dump_file, " times.\n"); } if (dump_file && (dump_flags & TDF_DETAILS) && maxiter >= 0) { fprintf (dump_file, "Loop %d iterates at most %i times.\n", loop->num, (int)maxiter); } /* Remove exits that are known to be never taken based on loop bound. Needs to be called after compilation of max_loop_iterations_int that populates the loop bounds. */ modified |= remove_redundant_iv_tests (loop); if (try_unroll_loop_completely (loop, exit, niter, ul, maxiter, locus)) return true; if (create_iv && niter && !chrec_contains_undetermined (niter) && exit && just_once_each_iteration_p (loop, exit->src)) create_canonical_iv (loop, exit, niter); if (ul == UL_ALL) modified |= try_peel_loop (loop, exit, niter, maxiter); return modified; } /* The main entry point of the pass. Adds canonical induction variables to the suitable loops. */ unsigned int canonicalize_induction_variables (void) { struct loop *loop; bool changed = false; bool irred_invalidated = false; bitmap loop_closed_ssa_invalidated = BITMAP_ALLOC (NULL); free_numbers_of_iterations_estimates (); estimate_numbers_of_iterations (); FOR_EACH_LOOP (loop, LI_FROM_INNERMOST) { changed |= canonicalize_loop_induction_variables (loop, true, UL_SINGLE_ITER, true); } gcc_assert (!need_ssa_update_p (cfun)); unloop_loops (loop_closed_ssa_invalidated, &irred_invalidated); if (irred_invalidated && loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS)) mark_irreducible_loops (); /* Clean up the information about numbers of iterations, since brute force evaluation could reveal new information. */ scev_reset (); if (!bitmap_empty_p (loop_closed_ssa_invalidated)) { gcc_checking_assert (loops_state_satisfies_p (LOOP_CLOSED_SSA)); rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa); } BITMAP_FREE (loop_closed_ssa_invalidated); if (changed) return TODO_cleanup_cfg; return 0; } /* Propagate constant SSA_NAMEs defined in basic block BB. */ static void propagate_constants_for_unrolling (basic_block bb) { /* Look for degenerate PHI nodes with constant argument. */ for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi); ) { gphi *phi = gsi.phi (); tree result = gimple_phi_result (phi); tree arg = gimple_phi_arg_def (phi, 0); if (! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (result) && gimple_phi_num_args (phi) == 1 && TREE_CODE (arg) == INTEGER_CST) { replace_uses_by (result, arg); gsi_remove (&gsi, true); release_ssa_name (result); } else gsi_next (&gsi); } /* Look for assignments to SSA names with constant RHS. */ for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi); ) { gimple stmt = gsi_stmt (gsi); tree lhs; if (is_gimple_assign (stmt) && gimple_assign_rhs_code (stmt) == INTEGER_CST && (lhs = gimple_assign_lhs (stmt), TREE_CODE (lhs) == SSA_NAME) && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs)) { replace_uses_by (lhs, gimple_assign_rhs1 (stmt)); gsi_remove (&gsi, true); release_ssa_name (lhs); } else gsi_next (&gsi); } } /* Process loops from innermost to outer, stopping at the innermost loop we unrolled. */ static bool tree_unroll_loops_completely_1 (bool may_increase_size, bool unroll_outer, vec<loop_p, va_heap>& father_stack, struct loop *loop) { struct loop *loop_father; bool changed = false; struct loop *inner; enum unroll_level ul; /* Process inner loops first. */ for (inner = loop->inner; inner != NULL; inner = inner->next) changed |= tree_unroll_loops_completely_1 (may_increase_size, unroll_outer, father_stack, inner); /* If we changed an inner loop we cannot process outer loops in this iteration because SSA form is not up-to-date. Continue with siblings of outer loops instead. */ if (changed) return true; /* Don't unroll #pragma omp simd loops until the vectorizer attempts to vectorize those. */ if (loop->force_vectorize) return false; /* Try to unroll this loop. */ loop_father = loop_outer (loop); if (!loop_father) return false; if (may_increase_size && optimize_loop_nest_for_speed_p (loop) /* Unroll outermost loops only if asked to do so or they do not cause code growth. */ && (unroll_outer || loop_outer (loop_father))) ul = UL_ALL; else ul = UL_NO_GROWTH; if (canonicalize_loop_induction_variables (loop, false, ul, !flag_tree_loop_ivcanon)) { /* If we'll continue unrolling, we need to propagate constants within the new basic blocks to fold away induction variable computations; otherwise, the size might blow up before the iteration is complete and the IR eventually cleaned up. */ if (loop_outer (loop_father) && !loop_father->aux) { father_stack.safe_push (loop_father); loop_father->aux = loop_father; } return true; } return false; } /* Unroll LOOPS completely if they iterate just few times. Unless MAY_INCREASE_SIZE is true, perform the unrolling only if the size of the code does not increase. */ unsigned int tree_unroll_loops_completely (bool may_increase_size, bool unroll_outer) { auto_vec<loop_p, 16> father_stack; bool changed; int iteration = 0; bool irred_invalidated = false; do { changed = false; bitmap loop_closed_ssa_invalidated = NULL; if (loops_state_satisfies_p (LOOP_CLOSED_SSA)) loop_closed_ssa_invalidated = BITMAP_ALLOC (NULL); free_numbers_of_iterations_estimates (); estimate_numbers_of_iterations (); changed = tree_unroll_loops_completely_1 (may_increase_size, unroll_outer, father_stack, current_loops->tree_root); if (changed) { struct loop **iter; unsigned i; /* Be sure to skip unlooped loops while procesing father_stack array. */ FOR_EACH_VEC_ELT (loops_to_unloop, i, iter) (*iter)->aux = NULL; FOR_EACH_VEC_ELT (father_stack, i, iter) if (!(*iter)->aux) *iter = NULL; unloop_loops (loop_closed_ssa_invalidated, &irred_invalidated); /* We can not use TODO_update_ssa_no_phi because VOPS gets confused. */ if (loop_closed_ssa_invalidated && !bitmap_empty_p (loop_closed_ssa_invalidated)) rewrite_into_loop_closed_ssa (loop_closed_ssa_invalidated, TODO_update_ssa); else update_ssa (TODO_update_ssa); /* Propagate the constants within the new basic blocks. */ FOR_EACH_VEC_ELT (father_stack, i, iter) if (*iter) { unsigned j; basic_block *body = get_loop_body_in_dom_order (*iter); for (j = 0; j < (*iter)->num_nodes; j++) propagate_constants_for_unrolling (body[j]); free (body); (*iter)->aux = NULL; } father_stack.truncate (0); /* This will take care of removing completely unrolled loops from the loop structures so we can continue unrolling now innermost loops. */ if (cleanup_tree_cfg ()) update_ssa (TODO_update_ssa_only_virtuals); /* Clean up the information about numbers of iterations, since complete unrolling might have invalidated it. */ scev_reset (); #ifdef ENABLE_CHECKING if (loops_state_satisfies_p (LOOP_CLOSED_SSA)) verify_loop_closed_ssa (true); #endif } if (loop_closed_ssa_invalidated) BITMAP_FREE (loop_closed_ssa_invalidated); } while (changed && ++iteration <= PARAM_VALUE (PARAM_MAX_UNROLL_ITERATIONS)); father_stack.release (); if (irred_invalidated && loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS)) mark_irreducible_loops (); return 0; } /* Canonical induction variable creation pass. */ namespace { const pass_data pass_data_iv_canon = { GIMPLE_PASS, /* type */ "ivcanon", /* name */ OPTGROUP_LOOP, /* optinfo_flags */ TV_TREE_LOOP_IVCANON, /* tv_id */ ( PROP_cfg | PROP_ssa ), /* properties_required */ 0, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ 0, /* todo_flags_finish */ }; class pass_iv_canon : public gimple_opt_pass { public: pass_iv_canon (gcc::context *ctxt) : gimple_opt_pass (pass_data_iv_canon, ctxt) {} /* opt_pass methods: */ virtual bool gate (function *) { return flag_tree_loop_ivcanon != 0; } virtual unsigned int execute (function *fun); }; // class pass_iv_canon unsigned int pass_iv_canon::execute (function *fun) { if (number_of_loops (fun) <= 1) return 0; return canonicalize_induction_variables (); } } // anon namespace gimple_opt_pass * make_pass_iv_canon (gcc::context *ctxt) { return new pass_iv_canon (ctxt); } /* Complete unrolling of loops. */ namespace { const pass_data pass_data_complete_unroll = { GIMPLE_PASS, /* type */ "cunroll", /* name */ OPTGROUP_LOOP, /* optinfo_flags */ TV_COMPLETE_UNROLL, /* tv_id */ ( PROP_cfg | PROP_ssa ), /* properties_required */ 0, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ 0, /* todo_flags_finish */ }; class pass_complete_unroll : public gimple_opt_pass { public: pass_complete_unroll (gcc::context *ctxt) : gimple_opt_pass (pass_data_complete_unroll, ctxt) {} /* opt_pass methods: */ virtual unsigned int execute (function *); }; // class pass_complete_unroll unsigned int pass_complete_unroll::execute (function *fun) { if (number_of_loops (fun) <= 1) return 0; return tree_unroll_loops_completely (flag_unroll_loops || flag_peel_loops || optimize >= 3, true); } } // anon namespace gimple_opt_pass * make_pass_complete_unroll (gcc::context *ctxt) { return new pass_complete_unroll (ctxt); } /* Complete unrolling of inner loops. */ namespace { const pass_data pass_data_complete_unrolli = { GIMPLE_PASS, /* type */ "cunrolli", /* name */ OPTGROUP_LOOP, /* optinfo_flags */ TV_COMPLETE_UNROLL, /* tv_id */ ( PROP_cfg | PROP_ssa ), /* properties_required */ 0, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ 0, /* todo_flags_finish */ }; class pass_complete_unrolli : public gimple_opt_pass { public: pass_complete_unrolli (gcc::context *ctxt) : gimple_opt_pass (pass_data_complete_unrolli, ctxt) {} /* opt_pass methods: */ virtual bool gate (function *) { return optimize >= 2; } virtual unsigned int execute (function *); }; // class pass_complete_unrolli unsigned int pass_complete_unrolli::execute (function *fun) { unsigned ret = 0; loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS); if (number_of_loops (fun) > 1) { scev_initialize (); ret = tree_unroll_loops_completely (optimize >= 3, false); free_numbers_of_iterations_estimates (); scev_finalize (); } loop_optimizer_finalize (); return ret; } } // anon namespace gimple_opt_pass * make_pass_complete_unrolli (gcc::context *ctxt) { return new pass_complete_unrolli (ctxt); }
atomic-14.c
/* PR middle-end/45423 */ /* { dg-do compile } */ /* { dg-options "-fopenmp -Wno-deprecated" } */ /* { dg-skip-if "invalid in C++17" { c++17 } } */ #ifdef __cplusplus bool *baz (); #else _Bool *baz (); #endif int *bar (); int foo (void) { #pragma omp barrier #pragma omp atomic (*bar ())++; #pragma omp barrier #pragma omp atomic ++(*bar ()); #pragma omp barrier #pragma omp atomic (*bar ())--; #pragma omp barrier #pragma omp atomic --(*bar ()); #pragma omp barrier #pragma omp atomic (*baz ())++; #pragma omp barrier #pragma omp atomic ++(*baz ()); #ifndef __cplusplus #pragma omp barrier #pragma omp atomic (*baz ())--; #pragma omp barrier #pragma omp atomic --(*baz ()); #pragma omp barrier #endif return 0; }
GB_AxB_saxpy3_template.c
//------------------------------------------------------------------------------ // GB_AxB_saxpy3_template: C=A*B, C<M>=A*B, or C<!M>=A*B via saxpy3 method //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // GB_AxB_saxpy3_template.c computes C=A*B for any semiring and matrix types. // It is #include'd in GB_AxB_saxpy3 to construct the generic method (for // arbitary user-defined operators and/or typecasting), and in the hard-coded // GB_Asaxpy3B* workers in the Generated/ folder. #include "GB_unused.h" //------------------------------------------------------------------------------ // template code for C=A*B via the saxpy3 method //------------------------------------------------------------------------------ { //-------------------------------------------------------------------------- // get the chunk size //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; //-------------------------------------------------------------------------- // get M, A, B, and C //-------------------------------------------------------------------------- int64_t *GB_RESTRICT Cp = C->p ; // const int64_t *GB_RESTRICT Ch = C->h ; const int64_t cvlen = C->vlen ; const int64_t cnvec = C->nvec ; const int64_t *GB_RESTRICT Bp = B->p ; const int64_t *GB_RESTRICT Bh = B->h ; const int64_t *GB_RESTRICT Bi = B->i ; const GB_BTYPE *GB_RESTRICT Bx = (GB_BTYPE *) (B_is_pattern ? NULL : B->x) ; // const int64_t bvlen = B->vlen ; // const int64_t bnvec = B->nvec ; // const bool B_is_hyper = B->is_hyper ; const int64_t *GB_RESTRICT Ap = A->p ; const int64_t *GB_RESTRICT Ah = A->h ; const int64_t *GB_RESTRICT Ai = A->i ; const int64_t anvec = A->nvec ; const bool A_is_hyper = GB_IS_HYPER (A) ; const GB_ATYPE *GB_RESTRICT Ax = (GB_ATYPE *) (A_is_pattern ? NULL : A->x) ; const int64_t *GB_RESTRICT Mp = NULL ; const int64_t *GB_RESTRICT Mh = NULL ; const int64_t *GB_RESTRICT Mi = NULL ; const GB_void *GB_RESTRICT Mx = NULL ; size_t msize = 0 ; int64_t mnvec = 0 ; bool M_is_hyper = false ; if (M != NULL) { Mp = M->p ; Mh = M->h ; Mi = M->i ; Mx = (GB_void *) (Mask_struct ? NULL : (M->x)) ; msize = M->type->size ; mnvec = M->nvec ; M_is_hyper = M->is_hyper ; } // 3 cases: // M not present and Mask_comp false: compute C=A*B // M present and Mask_comp false: compute C<M>=A*B // M present and Mask_comp true : compute C<!M>=A*B // If M is NULL on input, then Mask_comp is also false on input. bool mask_is_M = (M != NULL && !Mask_comp) ; //========================================================================== // phase2: numeric work for fine tasks //========================================================================== // Coarse tasks: nothing to do in phase2. // Fine tasks: compute nnz (C(:,j)), and values in Hx via atomics. int taskid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (taskid = 0 ; taskid < nfine ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- int64_t kk = TaskList [taskid].vector ; int64_t hash_size = TaskList [taskid].hsize ; bool use_Gustavson = (hash_size == cvlen) ; int64_t pB = TaskList [taskid].start ; int64_t pB_end = TaskList [taskid].end + 1 ; int64_t pleft = 0, pright = anvec-1 ; #if !GB_IS_ANY_PAIR_SEMIRING GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ; #endif #if GB_IS_PLUS_FC32_MONOID float *GB_RESTRICT Hx_real = (float *) Hx ; float *GB_RESTRICT Hx_imag = Hx_real + 1 ; #elif GB_IS_PLUS_FC64_MONOID double *GB_RESTRICT Hx_real = (double *) Hx ; double *GB_RESTRICT Hx_imag = Hx_real + 1 ; #endif if (use_Gustavson) { //------------------------------------------------------------------ // phase2: fine Gustavson task //------------------------------------------------------------------ // Hf [i] == 0: unlocked, i has not been seen in C(:,j). // Hx [i] is not initialized. // M(i,j) is 0, or M is not present. // if M: Hf [i] stays equal to 0 (or 3 if locked) // if !M, or no M: C(i,j) is a new entry seen for 1st time // Hf [i] == 1: unlocked, i has not been seen in C(:,j). // Hx [i] is not initialized. M is present. // M(i,j) is 1. (either M or !M case) // if M: C(i,j) is a new entry seen for the first time. // if !M: Hf [i] stays equal to 1 (or 3 if locked) // Hf [i] == 2: unlocked, i has been seen in C(:,j). // Hx [i] is initialized. This case is independent of M. // Hf [i] == 3: locked. Hx [i] cannot be accessed. int8_t *GB_RESTRICT Hf = (int8_t *GB_RESTRICT) TaskList [taskid].Hf; if (M == NULL) { //-------------------------------------------------------------- // phase2: fine Gustavson task, C=A*B //-------------------------------------------------------------- // Hf [i] is initially 0. // 0 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j) int8_t f ; #if GB_IS_ANY_MONOID GB_ATOMIC_READ f = Hf [i] ; // grab the entry if (f == 2) continue ; // check if already updated GB_ATOMIC_WRITE Hf [i] = 2 ; // flag the entry GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t #else #if GB_HAS_ATOMIC GB_ATOMIC_READ f = Hf [i] ; // grab the entry if (f == 2) // if true, update C(i,j) { GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t continue ; // C(i,j) has been updated } #endif do // lock the entry { // do this atomically: // { f = Hf [i] ; Hf [i] = 3 ; } GB_ATOMIC_CAPTURE_INT8 (f, Hf [i], 3) ; } while (f == 3) ; // lock owner gets f=0 or 2 if (f == 0) { // C(i,j) is a new entry GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t } else // f == 2 { // C(i,j) already appears in C(:,j) GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t } GB_ATOMIC_WRITE Hf [i] = 2 ; // unlock the entry #endif } } } else if (mask_is_M) { //-------------------------------------------------------------- // phase2: fine Gustavson task, C<M>=A*B //-------------------------------------------------------------- // Hf [i] is 0 if M(i,j) not present or M(i,j)=0. // 0 -> 1 : has already been done in phase0 if M(i,j)=1 // 0 -> 0 : to ignore, if M(i,j)=0 // 1 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen GB_GET_M_j ; // get M(:,j) GB_GET_M_j_RANGE (16) ; // get first and last in M(:,j) for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #if GB_IS_ANY_MONOID #define GB_IKJ \ int8_t f ; \ GB_ATOMIC_READ \ f = Hf [i] ; /* grab the entry */ \ if (f == 0 || f == 2) continue ; \ GB_ATOMIC_WRITE \ Hf [i] = 2 ; /* unlock the entry */ \ GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \ GB_ATOMIC_WRITE_HX (i, t) ; /* Hx [i] = t */ #else #define GB_IKJ \ { \ GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \ int8_t f ; \ GB_ATOMIC_READ \ f = Hf [i] ; /* grab the entry */ \ if (GB_HAS_ATOMIC && (f == 2)) \ { \ /* C(i,j) already seen; update it */ \ GB_ATOMIC_UPDATE_HX (i, t) ; /* Hx [i] += t */ \ continue ; /* C(i,j) has been updated */ \ } \ if (f == 0) continue ; /* M(i,j)=0; ignore C(i,j)*/ \ do /* lock the entry */ \ { \ /* do this atomically: */ \ /* { f = Hf [i] ; Hf [i] = 3 ; } */ \ GB_ATOMIC_CAPTURE_INT8 (f, Hf [i], 3) ; \ } while (f == 3) ; /* lock owner gets f=1 or 2 */ \ if (f == 1) \ { \ /* C(i,j) is a new entry */ \ GB_ATOMIC_WRITE_HX (i, t) ; /* Hx [i] = t */ \ } \ else /* f == 2 */ \ { \ /* C(i,j) already appears in C(:,j) */ \ GB_ATOMIC_UPDATE_HX (i, t) ; /* Hx [i] += t */ \ } \ GB_ATOMIC_WRITE \ Hf [i] = 2 ; /* unlock the entry */ \ } #endif GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ } } else { //-------------------------------------------------------------- // phase2: fine Gustavson task, C<!M>=A*B //-------------------------------------------------------------- // Hf [i] is 0 if M(i,j) not present or M(i,j)=0. // 0 -> 1 : has already been done in phase0 if M(i,j)=1 // 1 -> 1 : to ignore, if M(i,j)=1 // 0 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j) int8_t f ; #if GB_IS_ANY_MONOID GB_ATOMIC_READ f = Hf [i] ; // grab the entry if (f == 1 || f == 2) continue ; GB_ATOMIC_WRITE Hf [i] = 2 ; // unlock the entry GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t #else GB_ATOMIC_READ f = Hf [i] ; // grab the entry #if GB_HAS_ATOMIC if (f == 2) // if true, update C(i,j) { GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t continue ; // C(i,j) has been updated } #endif if (f == 1) continue ; // M(i,j)=1; ignore C(i,j) do // lock the entry { // do this atomically: // { f = Hf [i] ; Hf [i] = 3 ; } GB_ATOMIC_CAPTURE_INT8 (f, Hf [i], 3) ; } while (f == 3) ; // lock owner of gets f=0 or 2 if (f == 0) { // C(i,j) is a new entry GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t } else // f == 2 { // C(i,j) already seen GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t } GB_ATOMIC_WRITE Hf [i] = 2 ; // unlock the entry #endif } } } } else { //------------------------------------------------------------------ // phase2: fine hash task //------------------------------------------------------------------ // Each hash entry Hf [hash] splits into two parts, (h,f). f // is in the 2 least significant bits. h is 62 bits, and is // the 1-based index i of the C(i,j) entry stored at that // location in the hash table. // If M is present (M or !M), and M(i,j)=1, then (i+1,1) // has been inserted into the hash table, in phase0. // Given Hf [hash] split into (h,f) // h == 0, f == 0: unlocked and unoccupied. // note that if f=0, h must be zero too. // h == i+1, f == 1: unlocked, occupied by M(i,j)=1. // C(i,j) has not been seen, or is ignored. // Hx is not initialized. M is present. // if !M: this entry will be ignored in C. // h == i+1, f == 2: unlocked, occupied by C(i,j). // Hx is initialized. M is no longer // relevant. // h == (anything), f == 3: locked. int64_t *GB_RESTRICT Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ; int64_t hash_bits = (hash_size-1) ; if (M == NULL) { //-------------------------------------------------------------- // phase2: fine hash task, C=A*B //-------------------------------------------------------------- // Given Hf [hash] split into (h,f) // h == 0 , f == 0 : unlocked and unoccupied. // h == i+1, f == 2 : unlocked, occupied by C(i,j). // Hx is initialized. // h == ..., f == 3 : locked. // 0 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j) int64_t i1 = i + 1 ; // i1 = one-based index int64_t i_unlocked = (i1 << 2) + 2 ; // (i+1,2) for (GB_HASH (i)) // find i in hash table { int64_t hf ; GB_ATOMIC_READ hf = Hf [hash] ; // grab the entry #if GB_HAS_ATOMIC if (hf == i_unlocked) // if true, update C(i,j) { GB_ATOMIC_UPDATE_HX (hash, t) ;// Hx [.]+=t break ; // C(i,j) has been updated } #endif int64_t h = (hf >> 2) ; if (h == 0 || h == i1) { // h=0: unoccupied, h=i1: occupied by i do // lock the entry { // do this atomically: // { hf = Hf [hash] ; Hf [hash] |= 3 ; } GB_ATOMIC_CAPTURE_INT64_OR (hf,Hf[hash],3) ; } while ((hf & 3) == 3) ; // owner: f=0 or 2 if (hf == 0) // f == 0 { // C(i,j) is a new entry in C(:,j) // Hx [hash] = t GB_ATOMIC_WRITE_HX (hash, t) ; GB_ATOMIC_WRITE Hf [hash] = i_unlocked ; // unlock entry break ; } if (hf == i_unlocked) // f == 2 { // C(i,j) already appears in C(:,j) // Hx [hash] += t GB_ATOMIC_UPDATE_HX (hash, t) ; GB_ATOMIC_WRITE Hf [hash] = i_unlocked ; // unlock entry break ; } // hash table occupied, but not with i GB_ATOMIC_WRITE Hf [hash] = hf ; // unlock with prior value } } } } } else if (mask_is_M) { //-------------------------------------------------------------- // phase2: fine hash task, C<M>=A*B //-------------------------------------------------------------- // Given Hf [hash] split into (h,f) // h == 0 , f == 0 : unlocked, unoccupied. C(i,j) ignored // h == i+1, f == 1 : unlocked, occupied by M(i,j)=1. // C(i,j) has not been seen. // Hx is not initialized. // h == i+1, f == 2 : unlocked, occupied by C(i,j), M(i,j)=1 // Hx is initialized. // h == ..., f == 3 : locked. // 0 -> 0 : to ignore, if M(i,j)=0 // 1 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen GB_GET_M_j ; // get M(:,j) GB_GET_M_j_RANGE (16) ; // get first and last in M(:,j) for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #define GB_IKJ \ { \ GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \ int64_t i1 = i + 1 ; /* i1 = one-based index */ \ int64_t i_unlocked = (i1 << 2) + 2 ; /* (i+1,2) */ \ for (GB_HASH (i)) /* find i in hash table */ \ { \ int64_t hf ; \ GB_ATOMIC_READ \ hf = Hf [hash] ; /* grab the entry */ \ if (GB_HAS_ATOMIC && (hf == i_unlocked)) \ { \ /* Hx [hash] += t */ \ GB_ATOMIC_UPDATE_HX (hash, t) ; \ break ; /* C(i,j) has been updated */ \ } \ if (hf == 0) break ; /* M(i,j)=0; ignore Cij */ \ if ((hf >> 2) == i1) /* if true, i found */ \ { \ do /* lock the entry */ \ { \ /* do this atomically: */ \ /* { hf = Hf [hash] ; Hf [hash] |= 3 ; }*/ \ GB_ATOMIC_CAPTURE_INT64_OR (hf,Hf[hash],3);\ } while ((hf & 3) == 3) ; /* own: f=1,2 */ \ if ((hf & 3) == 1) /* f == 1 */ \ { \ /* C(i,j) is a new entry in C(:,j) */ \ /* Hx [hash] = t */ \ GB_ATOMIC_WRITE_HX (hash, t) ; \ } \ else /* f == 2 */ \ { \ /* C(i,j) already appears in C(:,j) */ \ /* Hx [hash] += t */ \ GB_ATOMIC_UPDATE_HX (hash, t) ; \ } \ GB_ATOMIC_WRITE \ Hf [hash] = i_unlocked ; /* unlock entry */ \ break ; \ } \ } \ } GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ } } else { //-------------------------------------------------------------- // phase2: fine hash task, C<!M>=A*B //-------------------------------------------------------------- // Given Hf [hash] split into (h,f) // h == 0 , f == 0 : unlocked and unoccupied. // h == i+1, f == 1 : unlocked, occupied by M(i,j)=1. // C(i,j) is ignored. // h == i+1, f == 2 : unlocked, occupied by C(i,j). // Hx is initialized. // h == (anything), f == 3: locked. // 1 -> 1 : to ignore, if M(i,j)=1 // 0 -> 3 : to lock, if i seen for first time // 2 -> 3 : to lock, if i seen already // 3 -> 2 : to unlock; now i has been seen for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j) int64_t i1 = i + 1 ; // i1 = one-based index int64_t i_unlocked = (i1 << 2) + 2 ; // (i+1,2) int64_t i_masked = (i1 << 2) + 1 ; // (i+1,1) for (GB_HASH (i)) // find i in hash table { int64_t hf ; GB_ATOMIC_READ hf = Hf [hash] ; // grab the entry #if GB_HAS_ATOMIC if (hf == i_unlocked) // if true, update C(i,j) { GB_ATOMIC_UPDATE_HX (hash, t) ;// Hx [.]+=t break ; // C(i,j) has been updated } #endif if (hf == i_masked) break ; // M(i,j)=1; ignore int64_t h = (hf >> 2) ; if (h == 0 || h == i1) { // h=0: unoccupied, h=i1: occupied by i do // lock the entry { // do this atomically: // { hf = Hf [hash] ; Hf [hash] |= 3 ; } GB_ATOMIC_CAPTURE_INT64_OR (hf,Hf[hash],3) ; } while ((hf & 3) == 3) ; // owner: f=0,1,2 if (hf == 0) // f == 0 { // C(i,j) is a new entry in C(:,j) // Hx [hash] = t GB_ATOMIC_WRITE_HX (hash, t) ; GB_ATOMIC_WRITE Hf [hash] = i_unlocked ; // unlock entry break ; } if (hf == i_unlocked) // f == 2 { // C(i,j) already appears in C(:,j) // Hx [hash] += t GB_ATOMIC_UPDATE_HX (hash, t) ; GB_ATOMIC_WRITE Hf [hash] = i_unlocked ; // unlock entry break ; } // hash table occupied, but not with i, // or with i but M(i,j)=1 so C(i,j) ignored GB_ATOMIC_WRITE Hf [hash] = hf ; // unlock with prior value } } } } } } } //========================================================================== // phase3/phase4: count nnz(C(:,j)) for fine tasks, cumsum of Cp //========================================================================== int64_t cjnz_max = GB_AxB_saxpy3_cumsum (C, TaskList, nfine, chunk, nthreads) ; //========================================================================== // phase5: numeric phase for coarse tasks, gather for fine tasks //========================================================================== // allocate Ci and Cx int64_t cnz = Cp [cnvec] ; GrB_Info info = GB_ix_alloc (C, cnz, true, Context) ; if (info != GrB_SUCCESS) { // out of memory return (GrB_OUT_OF_MEMORY) ; } int64_t *GB_RESTRICT Ci = C->i ; GB_CTYPE *GB_RESTRICT Cx = (GB_CTYPE *) C->x ; #if GB_IS_ANY_PAIR_SEMIRING // ANY_PAIR semiring: result is purely symbolic int64_t pC ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (pC = 0 ; pC < cnz ; pC++) { Cx [pC] = GB_CTYPE_CAST (1, 0) ; } // Just a precaution; these variables are not used below. Any attempt // to access them will lead to a compile error. #define Cx is not used #define Hx is not used // these have been renamed to ANY_PAIR: // EQ_PAIR // LAND_PAIR // LOR_PAIR // MAX_PAIR // MIN_PAIR // TIMES_PAIR #endif #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- #if !GB_IS_ANY_PAIR_SEMIRING GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ; #endif int64_t hash_size = TaskList [taskid].hsize ; bool use_Gustavson = (hash_size == cvlen) ; if (taskid < nfine) { //------------------------------------------------------------------ // fine task: gather pattern and values //------------------------------------------------------------------ int64_t kk = TaskList [taskid].vector ; int team_size = TaskList [taskid].team_size ; int master = TaskList [taskid].master ; int my_teamid = taskid - master ; int64_t pC = Cp [kk] ; if (use_Gustavson) { //-------------------------------------------------------------- // phase5: fine Gustavson task, C=A*B, C<M>=A*B, or C<!M>=A*B //-------------------------------------------------------------- // Hf [i] == 2 if C(i,j) is an entry in C(:,j) int8_t *GB_RESTRICT Hf = (int8_t *GB_RESTRICT) TaskList [taskid].Hf ; int64_t cjnz = Cp [kk+1] - pC ; int64_t istart, iend ; GB_PARTITION (istart, iend, cvlen, my_teamid, team_size) ; if (cjnz == cvlen) { // C(:,j) is dense for (int64_t i = istart ; i < iend ; i++) { Ci [pC + i] = i ; } #if !GB_IS_ANY_PAIR_SEMIRING // copy Hx [istart:iend-1] into Cx [pC+istart:pC+iend-1] GB_CIJ_MEMCPY (pC + istart, istart, iend - istart) ; #endif } else { // C(:,j) is sparse pC += TaskList [taskid].my_cjnz ; for (int64_t i = istart ; i < iend ; i++) { if (Hf [i] == 2) { #if !GB_IS_ANY_PAIR_SEMIRING GB_CIJ_GATHER (pC, i) ; // Cx [pC] = Hx [i] #endif Ci [pC++] = i ; } } } } else { //-------------------------------------------------------------- // phase5: fine hash task, C=A*B, C<M>=A*B, C<!M>=A*B //-------------------------------------------------------------- // (Hf [hash] & 3) == 2 if C(i,j) is an entry in C(:,j), // and the index i of the entry is (Hf [hash] >> 2) - 1. int64_t *GB_RESTRICT Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ; int64_t mystart, myend ; GB_PARTITION (mystart, myend, hash_size, my_teamid, team_size) ; pC += TaskList [taskid].my_cjnz ; for (int64_t hash = mystart ; hash < myend ; hash++) { int64_t hf = Hf [hash] ; if ((hf & 3) == 2) { int64_t i = (hf >> 2) - 1 ; // found C(i,j) in hash Ci [pC++] = i ; } } } } else { //------------------------------------------------------------------ // numeric coarse task: compute C(:,kfirst:klast) //------------------------------------------------------------------ int64_t *GB_RESTRICT Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ; int64_t kfirst = TaskList [taskid].start ; int64_t klast = TaskList [taskid].end ; int64_t nk = klast - kfirst + 1 ; int64_t mark = 2*nk + 1 ; if (use_Gustavson) { //-------------------------------------------------------------- // phase5: coarse Gustavson task //-------------------------------------------------------------- if (M == NULL) { //---------------------------------------------------------- // phase5: coarse Gustavson task, C=A*B //---------------------------------------------------------- for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_B_j ; // get B(:,j) mark++ ; if (cjnz == cvlen) // C(:,j) is dense { GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j) } else if (bjnz == 1) // C(:,j) = A(:,k)*B(k,j) { GB_COMPUTE_C_j_WHEN_NNZ_B_j_IS_ONE ; } else if (16 * cjnz > cvlen) // C(:,j) is not very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j) if (Hf [i] != mark) { // C(i,j) = A(i,k) * B(k,j) Hf [i] = mark ; GB_HX_WRITE (i, t) ; // Hx [i] = t } else { // C(i,j) += A(i,k) * B(k,j) GB_HX_UPDATE (i, t) ; // Hx [i] += t } } } GB_GATHER_ALL_C_j(mark) ; // gather into C(:,j) } else // C(:,j) is very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j) if (Hf [i] != mark) { // C(i,j) = A(i,k) * B(k,j) Hf [i] = mark ; GB_HX_WRITE (i, t) ; // Hx [i] = t Ci [pC++] = i ; } else { // C(i,j) += A(i,k) * B(k,j) GB_HX_UPDATE (i, t) ; // Hx [i] += t } } } GB_SORT_AND_GATHER_C_j ; // gather into C(:,j) } } } else if (mask_is_M) { //---------------------------------------------------------- // phase5: coarse Gustavson task, C<M>=A*B //---------------------------------------------------------- // Initially, Hf [...] < mark for all of Hf. // Hf [i] < mark : M(i,j)=0, C(i,j) is ignored. // Hf [i] == mark : M(i,j)=1, and C(i,j) not yet seen. // Hf [i] == mark+1 : M(i,j)=1, and C(i,j) has been seen. for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_B_j ; // get B(:,j) if (cjnz == cvlen) // C(:,j) is dense { GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j) continue ; // no need to examine M(:,j) } GB_GET_M_j ; // get M(:,j) GB_GET_M_j_RANGE (64) ; // get first and last in M(:,j) mark += 2 ; int64_t mark1 = mark+1 ; // scatter M(:,j) GB_SCATTER_M_j (pM_start, pM_end, mark) ; if (16 * cjnz > cvlen) // C(:,j) is not very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #define GB_IKJ \ { \ int64_t hf = Hf [i] ; \ if (hf == mark) \ { \ /* C(i,j) = A(i,k) * B(k,j) */ \ Hf [i] = mark1 ; /* mark as seen */\ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ GB_HX_WRITE (i, t) ; /* Hx [i] = t */ \ } \ else if (hf == mark1) \ { \ /* C(i,j) += A(i,k) * B(k,j) */ \ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ GB_HX_UPDATE (i, t) ;/* Hx [i] += t */ \ } \ } GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ } GB_GATHER_ALL_C_j(mark1) ; // gather into C(:,j) } else // C(:,j) is very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #define GB_IKJ \ { \ int64_t hf = Hf [i] ; \ if (hf == mark) \ { \ /* C(i,j) = A(i,k) * B(k,j) */ \ Hf [i] = mark1 ; /* mark as seen */\ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ GB_HX_WRITE (i, t) ; /* Hx [i] = t */ \ Ci [pC++] = i ; /* C(:,j) pattern */ \ } \ else if (hf == mark1) \ { \ /* C(i,j) += A(i,k) * B(k,j) */ \ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ GB_HX_UPDATE (i, t) ;/* Hx [i] += t */ \ } \ } GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ } GB_SORT_AND_GATHER_C_j ; // gather into C(:,j) } } } else { //---------------------------------------------------------- // phase5: coarse Gustavson task, C<!M>=A*B //---------------------------------------------------------- // if !M: // Hf [i] < mark : M(i,j)=0, C(i,j) is not yet seen. // Hf [i] == mark : M(i,j)=1, so C(i,j) is ignored. // Hf [i] == mark+1 : M(i,j)=0, and C(i,j) has been seen. for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_B_j ; // get B(:,j) if (cjnz == cvlen) // C(:,j) is dense { GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j) continue ; // no need to examine M(:,j) } GB_GET_M_j ; // get M(:,j) mark += 2 ; int64_t mark1 = mark+1 ; // scatter M(:,j) GB_SCATTER_M_j (pM_start, pM_end, mark) ; if (16 * cjnz > cvlen) // C(:,j) is not very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) int64_t hf = Hf [i] ; if (hf < mark) { // C(i,j) = A(i,k) * B(k,j) Hf [i] = mark1 ; // mark as seen GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j) GB_HX_WRITE (i, t) ; // Hx [i] = t } else if (hf == mark1) { // C(i,j) += A(i,k) * B(k,j) GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j) GB_HX_UPDATE (i, t) ;// Hx [i] += t } } } GB_GATHER_ALL_C_j(mark1) ; // gather into C(:,j) } else // C(:,j) is very sparse { for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) int64_t hf = Hf [i] ; if (hf < mark) { // C(i,j) = A(i,k) * B(k,j) Hf [i] = mark1 ; // mark as seen GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j) GB_HX_WRITE (i, t) ; // Hx [i] = t Ci [pC++] = i ; // create C(:,j) pattern } else if (hf == mark1) { // C(i,j) += A(i,k) * B(k,j) GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j) GB_HX_UPDATE (i, t) ; // Hx [i] += t } } } GB_SORT_AND_GATHER_C_j ; // gather into C(:,j) } } } } else { //-------------------------------------------------------------- // phase5: coarse hash task //-------------------------------------------------------------- int64_t *GB_RESTRICT Hi = TaskList [taskid].Hi ; int64_t hash_bits = (hash_size-1) ; if (M == NULL) { //---------------------------------------------------------- // phase5: coarse hash task, C=A*B //---------------------------------------------------------- // Initially, Hf [...] < mark for all of Hf. // Let f = Hf [hash] and h = Hi [hash] // f < mark : unoccupied. // h == i, f == mark : occupied with C(i,j) for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_B_j ; // get B(:,j) if (bjnz == 1) // C(:,j) = A(:,k)*B(k,j) { GB_COMPUTE_C_j_WHEN_NNZ_B_j_IS_ONE ; continue ; } mark++ ; for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j) for (GB_HASH (i)) // find i in hash table { if (Hf [hash] == mark) { // hash entry is occupied if (Hi [hash] == i) { // i already in the hash table // Hx [hash] += t ; GB_HX_UPDATE (hash, t) ; break ; } } else { // hash entry is not occupied Hf [hash] = mark ; Hi [hash] = i ; GB_HX_WRITE (hash, t) ;// Hx[hash]=t Ci [pC++] = i ; break ; } } } } // found i if: Hf [hash] == mark and Hi [hash] == i GB_SORT_AND_GATHER_HASHED_C_j (mark, Hi [hash] == i) } } else if (mask_is_M) { //---------------------------------------------------------- // phase5: coarse hash task, C<M>=A*B //---------------------------------------------------------- // Initially, Hf [...] < mark for all of Hf. // Let h = Hi [hash] and f = Hf [hash]. // f < mark : M(i,j)=0, C(i,j) is ignored. // h == i, f == mark : M(i,j)=1, and C(i,j) not yet seen. // h == i, f == mark+1 : M(i,j)=1, and C(i,j) has been seen. for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_M_j ; // get M(:,j) GB_GET_M_j_RANGE (64) ; // get 1st & last in M(:,j) mark += 2 ; int64_t mark1 = mark+1 ; GB_HASH_M_j ; // hash M(:,j) GB_GET_B_j ; // get B(:,j) for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) GB_SKIP_IF_A_k_DISJOINT_WITH_M_j ; GB_GET_B_kj ; // bkj = B(k,j) #define GB_IKJ \ { \ for (GB_HASH (i)) /* find i in hash */ \ { \ int64_t f = Hf [hash] ; \ if (f < mark) break ; /* M(i,j)=0, ignore*/\ if (Hi [hash] == i) \ { \ GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \ if (f == mark) /* if true, i is new */ \ { \ /* C(i,j) is new */ \ Hf [hash] = mark1 ; /* mark seen */\ GB_HX_WRITE (hash, t) ;/*Hx[.]=t */\ Ci [pC++] = i ; \ } \ else \ { \ /* C(i,j) has been seen; update */ \ GB_HX_UPDATE (hash, t) ; \ } \ break ; \ } \ } \ } GB_SCAN_M_j_OR_A_k ; #undef GB_IKJ } // found i if: Hf [hash] == mark1 and Hi [hash] == i GB_SORT_AND_GATHER_HASHED_C_j (mark1, Hi [hash] == i) ; } } else { //---------------------------------------------------------- // phase5: coarse hash task, C<!M>=A*B //---------------------------------------------------------- // Initially, Hf [...] < mark for all of Hf. // Let h = Hi [hash] and f = Hf [hash]. // f < mark: unoccupied, M(i,j)=0, and C(i,j) not yet seen. // h == i, f == mark : M(i,j)=1. C(i,j) ignored. // h == i, f == mark+1 : M(i,j)=0, and C(i,j) has been seen. for (int64_t kk = kfirst ; kk <= klast ; kk++) { int64_t pC = Cp [kk] ; int64_t cjnz = Cp [kk+1] - pC ; if (cjnz == 0) continue ; // nothing to do GB_GET_M_j ; // get M(:,j) mark += 2 ; int64_t mark1 = mark+1 ; GB_HASH_M_j ; // hash M(:,j) GB_GET_B_j ; // get B(:,j) for ( ; pB < pB_end ; pB++) // scan B(:,j) { int64_t k = Bi [pB] ; // get B(k,j) GB_GET_A_k ; // get A(:,k) if (aknz == 0) continue ; GB_GET_B_kj ; // bkj = B(k,j) // scan A(:,k) for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; // get A(i,k) for (GB_HASH (i)) // find i in hash { int64_t f = Hf [hash] ; if (f < mark) // if true, i is new { // C(i,j) is new Hf [hash] = mark1 ; // mark C(i,j) seen Hi [hash] = i ; GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j) GB_HX_WRITE (hash, t) ; // Hx [hash] = t Ci [pC++] = i ; break ; } if (Hi [hash] == i) { if (f == mark1) { // C(i,j) has been seen; update it. GB_MULT_A_ik_B_kj ;//t=A(i,k)*B(k,j) GB_HX_UPDATE (hash, t) ;//Hx[ ] += t } break ; } } } } // found i if: Hf [hash] == mark1 and Hi [hash] == i GB_SORT_AND_GATHER_HASHED_C_j (mark1, Hi [hash] == i) ; } } } } } //========================================================================== // phase6: final gather phase for fine hash tasks //========================================================================== if (cjnz_max > 0) { int64_t *GB_RESTRICT W = NULL ; int nthreads_msort = GB_MSORT_NTHREADS (nthreads) ; if (cjnz_max <= GB_BASECASE) nthreads_msort = 1 ; if (nthreads_msort > 1) { // allocate workspace for parallel mergesort W = GB_MALLOC (cjnz_max, int64_t) ; if (W == NULL) { // out of memory return (GrB_OUT_OF_MEMORY) ; } } for (taskid = 0 ; taskid < nfine ; taskid++) { int64_t hash_size = TaskList [taskid].hsize ; bool use_Gustavson = (hash_size == cvlen) ; if (!use_Gustavson && taskid == TaskList [taskid].master) { //-------------------------------------------------------------- // phase6: fine hash task, C=A*B, C<M>=A*B, C<!M>=A*B //-------------------------------------------------------------- // (Hf [hash] & 3) == 2 if C(i,j) is an entry in C(:,j), // and the index i of the entry is (Hf [hash] >> 2) - 1. int64_t kk = TaskList [taskid].vector ; int64_t hash_bits = (hash_size-1) ; int64_t *GB_RESTRICT Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ; int64_t cjnz = Cp [kk+1] - Cp [kk] ; // sort the pattern of C(:,j) int nth = GB_nthreads (cjnz, chunk, nthreads_msort) ; GB_msort_1 (Ci + Cp [kk], W, cjnz, nth) ; #if !GB_IS_ANY_PAIR_SEMIRING GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ; // gather the values of C(:,j) int64_t pC ; #pragma omp parallel for num_threads(nth) schedule(static) for (pC = Cp [kk] ; pC < Cp [kk+1] ; pC++) { int64_t i = Ci [pC] ; // get C(i,j) int64_t i1 = i + 1 ; for (GB_HASH (i)) // find i in hash table { int64_t hf = Hf [hash] ; if ((hf & 3) == 2 && (hf >> 2) == i1) { // found i in the hash table GB_CIJ_GATHER (pC, hash) ; // Cx[pC] = Hx[hash] break ; } } } #endif } } // free workspace GB_FREE (W) ; } } #undef Cx #undef Hx
linalg.h
/** * Copyright (c) 2015, Jozef Stefan Institute, Quintelligence d.o.o. and contributors * All rights reserved. * * This source code is licensed under the FreeBSD license found in the * LICENSE file in the root directory of this source tree. */ #ifndef LINALG_H #define LINALG_H /////////////////////////////////////////////////////////////////////// // Blas Support #ifdef BLAS #define MKL_Complex8 std::complex<float> #define MKL_Complex16 std::complex<double> #define lapack_complex_float std::complex<float> #define lapack_complex_double std::complex<double> #define LAPACK_COMPLEX_CPP #ifdef AMD #include "acml.h" #elif INTEL #undef small #include "mkl.h" //#include "mkl_scalapack.h" #else #include "cblas.h" #ifdef LAPACKE #include "lapacke.h" #endif #endif #endif #include "base.h" namespace TypeCheck { template<typename T1> struct is_float { static const bool value = false; }; template<> struct is_float<float> { static const bool value = true; }; template<> struct is_float<TNum<float> > { static const bool value = true; }; template<typename T1> struct is_double { static const bool value = false; }; template<> struct is_double<double> { static const bool value = true; }; template<> struct is_double<TNum<double> > { static const bool value = true; }; template<typename T1> struct is_complex_float { static const bool value = false; }; template<> struct is_complex_float< std::complex<float> > { static const bool value = true; }; template<> struct is_complex_float< TNum<std::complex<float> > > { static const bool value = true; }; template<typename T1> struct is_complex_double { static const bool value = false; }; template<> struct is_complex_double< std::complex<double> > { static const bool value = true; }; template<> struct is_complex_double< TNum<std::complex<double> > > { static const bool value = true; }; } // the matrix dimension classificator for the (Dim parameter) enum TMatDim { mdCols = 1, mdRows = 2 }; /////////////////////////////////////////////////////////////////////// // forward declarations class TLinAlg; ////////////////////////////////////////////////////////////////////// // Miscellaneous linear algebra functions class TLAMisc { public: //Sort double array #ifdef SCALAPACK template<class TSizeTy> static void Sort(TVec<TFlt, TSizeTy> & Vec, TVec<TSizeTy, TSizeTy>& Index, const TBool& DecreseP); #endif // Dumps vector to file so Excel can read it static void SaveCsvTFltV(const TFltV& Vec, TSOut& SOut); // Dumps sparse vector to file so Matlab can read it static void SaveMatlabTFltIntKdV(const TIntFltKdV& SpV, const int& ColN, TSOut& SOut); /// Dumps sparse matrix to file so Matlab can read it static void SaveMatlabSpMat(const TVec<TIntFltKdV>& SpMat, TSOut& SOut); /// Dumps sparse matrix to file so Matlab can read it static void SaveMatlabSpMat(const TTriple<TIntV, TIntV, TFltV>& SpMat, TSOut& SOut); // Dumps vector to file so Matlab can read it static void SaveMatlabTFltV(const TFltV& m, const TStr& FName); // Dumps vector to file so Matlab can read it static void SaveMatlabTIntV(const TIntV& m, const TStr& FName); // Dumps column ColId from m to file so Matlab can read it static void SaveMatlabTFltVVCol(const TFltVV& m, int ColId, const TStr& FName); // Dumps matrix to file so Matlab can read it static void SaveMatlabTFltVV(const TFltVV& m, const TStr& FName); // Dumps matrix to the output stream so Matlab can read it static void SaveMatlabTFltVV(const TFltVV& m, TSOut& SOut); // Dumps main minor rowN x colN to file so Matlab can read it static void SaveMatlabTFltVVMjrSubMtrx(const TFltVV& m, int rowN, int colN, const TStr& FName); // loads matlab full matrix static void LoadMatlabTFltVV(const TStr& FNm, TVec<TFltV>& ColV); // loads matlab full matrix static void LoadMatlabTFltVV(const TStr& FNm, TFltVV& MatrixVV); // loads matlab full matrix static void LoadMatlabTFltVV(TVec<TFltV>& ColV, TSIn& SIn); // loads matlab full matrix static void LoadMatlabTFltVV(TFltVV& MatrixVV, TSIn& SIn); // prints vector to screen static void PrintTFltV(const TFltV& Vec, const TStr& VecNm); // print matrix to string static void PrintTFltVVToStr(const TFltVV& A, TStr& Out); // print matrixt to screen static void PrintTFltVV(const TFltVV& A, const TStr& MatrixNm); // print sparse matrix to screen static void PrintSpMat(const TTriple<TIntV, TIntV, TFltV>& A, const TStr& MatrixNm); // print sparse matrix to screen static void PrintSpMat(const TVec<TIntFltKdV>& A, const TStr& MatrixNm); // prints vector to screen static void PrintTIntV(const TIntV& Vec, const TStr& VecNm); // fills vector with random numbers static void FillRnd(TFltV& Vec) { TRnd Rnd(0); FillRnd(Vec.Len(), Vec, Rnd); } static void FillRnd(TFltV& Vec, TRnd& Rnd) { FillRnd(Vec.Len(), Vec, Rnd); } static void FillRnd(TFltVV& Mat) { TRnd Rnd(0); FillRnd(Mat, Rnd); } static void FillRnd(TFltVV& Mat, TRnd& Rnd) { FillRnd(Mat.Get1DVec(), Rnd); } static void FillRnd(const int& Len, TFltV& Vec, TRnd& Rnd); // set all components static void Fill(TFltVV& M, const double& Val); static void Fill(TFltV& M, const double& Val); // sets all compnents to zero static void FillZero(TFltV& Vec) { Vec.PutAll(0.0); } static void FillZero(TFltVV& M) { Fill(M, 0.0); } // set matrix to identity static void FillIdentity(TFltVV& M); static void FillIdentity(TFltVV& M, const double& Elt); // set vector to range static void FillRange(const int& Vals, TFltV& Vec); static void FillRange(const int& Vals, TIntV& Vec); template <class TVal, class TTSizeTyTy = int> static void FillRangeS(const TTSizeTyTy& Vals, TVec<TVal, TTSizeTyTy>& Vec); // sums elements in vector static int SumVec(const TIntV& Vec); static double SumVec(const TFltV& Vec); // converts full vector to sparse static void ToSpVec(const TFltV& Vec, TIntFltKdV& SpVec, const double& CutWordWgtSumPrc = 0.0); // converts sparse vector to full static void ToVec(const TIntFltKdV& SpVec, TFltV& Vec, const int& VecLen); // creates a diagonal matrix static void Diag(const TFltV& Vec, TFltVV& Mat); // creates a diagonal matrix static void Diag(const TFltV& Vec, TVec<TIntFltKdV>& Mat); // gets the maximal index of a sparse vector static int GetMaxDimIdx(const TIntFltKdV& SpVec); // gets the maximal row index of a sparse column matrix static int GetMaxDimIdx(const TVec<TIntFltKdV>& SpMat); // returns the index of the minimum element static int GetMinIdx(const TFltV& Vec); // returns a vector with a sequence starting at Min and ending at Max static void RangeV(const int& Min, const int& Max, TIntV& Res); // returns the mean value of Vec. static double Mean(const TFltV& Vec); // returns the mean value along the dimension (Dim) of Mat. See Matlab documentation - mean(). static void Mean(const TFltVV& Mat, TFltV& Vec, const TMatDim& Dim = TMatDim::mdCols); // returns standard deviation. See Matlab documentation - std(). static void Std(const TFltVV& Mat, TFltV& Vec, const int& Flag = 0, const TMatDim& Dim = TMatDim::mdCols); // returns the z-score for each element of X such that columns of X are centered to have mean 0 and scaled to have standard deviation 1. static void ZScore(const TFltVV& Mat, TFltVV& Vec, const int& Flag = 0, const TMatDim& Dim = TMatDim::mdCols); }; #ifdef SCALAPACK template<class TSizeTy> void TLAMisc::Sort(TVec<TFlt, TSizeTy> & Vec, TVec<TSizeTy, TSizeTy>& Index, const TBool& DecreseP) { if (Index.Empty()) { TLAMisc::FillRange(Vec.Len(), index); } char* id = DecreseP ? "D" : "I"; TSizeTy n = Vec.Len(); TSizeTy info; dlasrt2(id, &n, &Vec[0].Val, &Index[0], &info); } #endif template <class TVal, class TTSizeTyTy> void TLAMisc::FillRangeS(const TTSizeTyTy& Vals, TVec<TVal, TTSizeTyTy>& Vec) { //Added by Andrej if (Vec.Len() != Vals){ Vec.Gen(Vals); } for (int i = 0; i < Vals; i++){ Vec[i] = i; } }; ////////////////////////////////////////////////////////////////////// // Linear Algebra Utilities class TLAUtil { public: // generates a vector of ones with dimension dim template <class TVal, class TSizeTy> static void Ones(const int& Dim, TVec<TVal, TSizeTy>& OnesV) { if (OnesV.Len() != Dim) { OnesV.Gen(Dim); } for (int i = 0; i < Dim; i++) { OnesV[i] = 1; } } // generates a vector with i on index i template <class TVal, class TSizeTy> static void Range(const int& Dim, TVec<TVal, TSizeTy>& RangeV) { if (RangeV.Len() != Dim) { RangeV.Gen(Dim); } for (TSizeTy i = 0; i < Dim; i++) { RangeV[i] = TVal(i); } } template <class TType, class TSizeTy, bool ColMajor> static void Identity(const TSizeTy& Dim, TVVec<TType, TSizeTy, ColMajor>& X) { if (X.Empty()) { X.Gen(Dim, Dim); } EAssert(X.GetRows() == Dim && X.GetCols() == Dim); for (TSizeTy i = 0; i < Dim; i++) { X(i,i) = 1; } } // returns a sub matrix of the input matrix in range [StartRow, EndRow) x [StartCol, EndCol) template <class TType, class TSizeTy, bool ColMajor> static void SubMat(const TVVec<TType, TSizeTy, ColMajor>& Mat, const TSizeTy& StartRow, const TSizeTy& EndRow, const TSizeTy& StartCol, const TSizeTy& EndCol, TVVec<TType, TSizeTy, ColMajor>& SubMat) { EAssert(StartRow >= 0 && StartCol >= 0); EAssert(EndRow < Mat.GetRows() && EndCol < Mat.GetCols()); if (SubMat.GetRows() != EndRow - StartRow || SubMat.GetCols() != EndCol - StartCol) { SubMat.Gen(EndRow - StartRow, EndCol - StartCol); } for (TSizeTy i = StartRow; i < EndRow; i++) { for (TSizeTy j = StartCol; j < EndCol; j++) { SubMat.PutXY(i - StartRow, j - StartCol, Mat(i,j)); } } } template <class TType, class TVecVal, class TSizeTy, bool ColMajor> static void SubMat(const TVVec<TType, TSizeTy, ColMajor>& Mat, const TVec<TVecVal, TSizeTy>& ColIdxV, TVVec<TType, TSizeTy, ColMajor>& SubMat) { if (SubMat.Empty()) { SubMat.Gen(Mat.GetRows(), ColIdxV.Len()); } EAssert(SubMat.GetRows() == Mat.GetRows() && SubMat.GetCols() == ColIdxV.Len()); TVec<TType, TSizeTy> ColV; for (TSizeTy i = 0; i < ColIdxV.Len(); i++) { const TSizeTy& ColN = ColIdxV[i]; EAssert(0 <= ColN && ColN < Mat.GetCols()); Mat.GetCol(ColN, ColV); SubMat.SetCol(i, ColV); } } template <class TType, class TSizeTy, bool ColMajor> static void GetRow(const TVVec<TType, TSizeTy, ColMajor>& Mat, const TSizeTy& RowN, TVec<TType, TSizeTy>& RowV) { EAssert(0 <= RowN && RowN < Mat.GetRows()); const TSizeTy Cols = Mat.GetCols(); if (RowV.Len() != Mat.GetCols()) { RowV.Gen(Cols); } for (TSizeTy ColN = 0; ColN < Cols; ColN++) { RowV[ColN] = Mat(RowN, ColN); } } template <class TVal, class TSizeTy> static TSizeTy GetMaxIdx(const TVec<TVal, TSizeTy>& Vec) { if (Vec.Empty()) { return -1; } TSizeTy MxIdx = 0; TVal MxVal = Vec[0]; for (TSizeTy i = 1; i < Vec.Len(); i++ ) { if (Vec[i] > MxVal) { MxVal = Vec[i]; MxIdx = i; } } return MxIdx; } template <class TType, class TSizeTy, bool ColMajor> static void CenterRows(TVVec<TType, TSizeTy, ColMajor>& X) { const TSizeTy Rows = X.GetRows(); const TSizeTy Cols = X.GetCols(); #pragma omp parallel for for (TSizeTy RowIdx = 0; RowIdx < Rows; RowIdx++) { TType RowMean = 0; for (TSizeTy ColIdx = 0; ColIdx < Cols; ColIdx++) { RowMean += X(RowIdx, ColIdx); } RowMean /= Cols; for (int ColIdx = 0; ColIdx < Cols; ColIdx++) { X(RowIdx, ColIdx) -= RowMean; } } } }; ////////////////////////////////////////////////////////////////////// // Template-ised Sparse Operations template <class TKey, class TDat> class TSparseOps { public: /// Transform sparse matrix from (row,col,val) triplets to a vector of sparse columns static void CoordinateCreateSparseColMatrix(const TVec<TKey>& RowIdxV, const TVec<TKey>& ColIdxV, const TVec<TDat>& ValV, TVec<TVec<TKeyDat<TKey, TDat> > >& ColMatrix, const TKey& Cols); /// Merge given sparse vectors using +operator on KeyDat elements with same Key value static void SparseMerge(const TVec<TKeyDat<TKey, TDat> >& SrcV1, const TVec<TKeyDat<TKey, TDat> >& SrcV2, TVec<TKeyDat<TKey, TDat> >& DstV); /// Construct sparse linear combination (DstV = p*SrcV1 + q*SrcV2) static void SparseLinComb(const double& p, const TVec<TKeyDat<TKey, TDat> >& SrcV1, const double& q, const TVec<TKeyDat<TKey, TDat> >& SrcV2, TVec<TKeyDat<TKey, TDat> >& DstV); }; typedef TSparseOps<TInt, TFlt> TSparseOpsIntFlt; template <class TKey, class TDat> void TSparseOps<TKey, TDat>::CoordinateCreateSparseColMatrix(const TVec<TKey>& RowIdxV, const TVec<TKey>& ColIdxV, const TVec<TDat>& ValV, TVec<TVec<TKeyDat<TKey, TDat> > >& ColMatrix, const TKey& Cols) { ColMatrix.Gen(Cols); EAssert(RowIdxV.Len() == ColIdxV.Len() && RowIdxV.Len() == ValV.Len()); TKey Els = RowIdxV.Len(); for (TKey ElN = 0; ElN < Els; ElN++) { ColMatrix[ColIdxV[ElN]].Add(TKeyDat<TKey, TDat>(RowIdxV[ElN], ValV[ElN])); } for (TKey ColN = 0; ColN < Cols; ColN++) { ColMatrix[ColN].Sort(); } } template <class TKey, class TDat> void TSparseOps<TKey, TDat>::SparseMerge(const TVec<TKeyDat<TKey, TDat> >& SrcV1, const TVec<TKeyDat<TKey, TDat> >& SrcV2, TVec<TKeyDat<TKey, TDat> >& DstV) { DstV.Clr(); const int Src1Len = SrcV1.Len(); const int Src2Len = SrcV2.Len(); int Src1N = 0, Src2N = 0; while (Src1N < Src1Len && Src2N < Src2Len) { if (SrcV1[Src1N].Key < SrcV2[Src2N].Key) { DstV.Add(SrcV1[Src1N]); Src1N++; } else if (SrcV1[Src1N].Key > SrcV2[Src2N].Key) { DstV.Add(SrcV2[Src2N]); Src2N++; } else { DstV.Add(TKeyDat<TKey, TDat>(SrcV1[Src1N].Key, SrcV1[Src1N].Dat + SrcV2[Src2N].Dat)); Src1N++; Src2N++; } } while (Src1N < Src1Len) { DstV.Add(SrcV1[Src1N]); Src1N++; } while (Src2N < Src2Len) { DstV.Add(SrcV2[Src2N]); Src2N++; } } template <class TKey, class TDat> void TSparseOps<TKey, TDat>::SparseLinComb(const double& p, const TVec<TKeyDat<TKey, TDat> >& SrcV1, const double& q, const TVec<TKeyDat<TKey, TDat> >& SrcV2, TVec<TKeyDat<TKey, TDat> >& DstV) { DstV.Clr(); const int Src1Len = SrcV1.Len(); const int Src2Len = SrcV2.Len(); int Src1N = 0, Src2N = 0; while (Src1N < Src1Len && Src2N < Src2Len) { if (SrcV1[Src1N].Key < SrcV2[Src2N].Key) { DstV.Add(TKeyDat<TKey, TDat>(SrcV1[Src1N].Key, p * SrcV1[Src1N].Dat)); Src1N++; } else if (SrcV1[Src1N].Key > SrcV2[Src2N].Key) { DstV.Add(TKeyDat<TKey, TDat>(SrcV2[Src2N].Key, q * SrcV2[Src2N].Dat)); Src2N++; } else { DstV.Add(TKeyDat<TKey, TDat>(SrcV1[Src1N].Key, p * SrcV1[Src1N].Dat + q * SrcV2[Src2N].Dat)); Src1N++; Src2N++; } } while (Src1N < Src1Len) { DstV.Add(TKeyDat<TKey, TDat>(SrcV1[Src1N].Key, p * SrcV1[Src1N].Dat)); Src1N++; } while (Src2N < Src2Len) { DstV.Add(TKeyDat<TKey, TDat>(SrcV2[Src2N].Key, q * SrcV2[Src2N].Dat)); Src2N++; } } /////////////////////////////////////////////////////////////////////// /// Matrix. Class for matrix-vector and matrix-matrix operations class TMatrix { private: bool Transposed; protected: virtual void PMultiply(const TFltVV& B, int ColId, TFltV& Result) const = 0; virtual void PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const = 0; virtual void PMultiply(const TFltV& Vec, TFltV& Result) const = 0; virtual void PMultiplyT(const TFltV& Vec, TFltV& Result) const = 0; virtual void PMultiply(const TFltVV& B, TFltVV& Result) const { FailR("TMatrix PMultiply(const TFltVV& B, TFltVV& Result) not implemented"); } virtual void PMultiplyT(const TFltVV& B, TFltVV& Result) const { FailR("TMatrix PMultiplyT(const TFltVV& B, TFltVV& Result) not implemented"); } virtual int PGetRows() const = 0; virtual int PGetCols() const = 0; public: TMatrix() : Transposed(false) {} virtual ~TMatrix() { } // Result = A * B(:,ColId) void Multiply(const TFltVV& B, int ColId, TFltV& Result) const { if (Transposed) { PMultiplyT(B, ColId, Result); } else { PMultiply(B, ColId, Result); } } // Result = A' * B(:,ColId) void MultiplyT(const TFltVV& B, int ColId, TFltV& Result) const { if (Transposed) { PMultiply(B, ColId, Result); } else { PMultiplyT(B, ColId, Result); } } // Result = A * Vec void Multiply(const TFltV& Vec, TFltV& Result) const { if (Transposed) { PMultiplyT(Vec, Result); } else { PMultiply(Vec, Result); } } // Result = A' * Vec void MultiplyT(const TFltV& Vec, TFltV& Result) const{ if (Transposed) { PMultiply(Vec, Result); } else { PMultiplyT(Vec, Result); } } // Result = A * B void Multiply(const TFltVV& B, TFltVV& Result) const { if (Transposed) { PMultiplyT(B, Result); } else { PMultiply(B, Result); } } // Result = A' * B void MultiplyT(const TFltVV& B, TFltVV& Result) const { if (Transposed) { PMultiply(B, Result); } else { PMultiplyT(B, Result); } } // number of rows int GetRows() const { return Transposed ? PGetCols() : PGetRows(); } // number of columns int GetCols() const { return Transposed ? PGetRows() : PGetCols(); } virtual void Transpose() { Transposed = !Transposed; } void Save(TSOut& SOut) const { TBool(Transposed).Save(SOut); } void Load(TSIn& SIn) { Transposed = TBool(SIn); } }; /////////////////////////////////////////////////////////////////////// // Sparse-Column-Matrix // matrix is given with columns as sparse vectors class TSparseColMatrix : public TMatrix { public: // number of rows and columns of matrix TInt RowN, ColN; // vector of sparse columns TVec<TIntFltKdV> ColSpVV; protected: // Result = A * B(:,ColId) virtual void PMultiply(const TFltVV& B, int ColId, TFltV& Result) const; // Result = A * Vec virtual void PMultiply(const TFltV& Vec, TFltV& Result) const; // Result = A' * B(:,ColId) virtual void PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const; // Result = A' * Vec virtual void PMultiplyT(const TFltV& Vec, TFltV& Result) const; // Result = A * B virtual void PMultiply(const TFltVV& B, TFltVV& Result) const; // Result = A' * B virtual void PMultiplyT(const TFltVV& B, TFltVV& Result) const; void Init(); int PGetRows() const { return RowN; } int PGetCols() const { return ColN; } public: TSparseColMatrix(): TMatrix() {} TSparseColMatrix(const int& _RowN, const int& _ColN): RowN(_RowN), ColN(_ColN), ColSpVV() {} TSparseColMatrix(const TVec<TIntFltKdV>& _ColSpVV): TMatrix(), ColSpVV(_ColSpVV) { Init(); } TSparseColMatrix(const TVec<TIntFltKdV>& _ColSpVV, const int& _RowN, const int& _ColN) : TMatrix(), RowN(_RowN), ColN(_ColN), ColSpVV(_ColSpVV) {} void Save(TSOut& SOut) { RowN.Save(SOut); ColN.Save(SOut); ColSpVV.Save(SOut); } void Load(TSIn& SIn) { RowN.Load(SIn); ColN.Load(SIn); ColSpVV = TVec<TIntFltKdV>(SIn); } }; /////////////////////////////////////////////////////////////////////// // Sparse-Row-Matrix // matrix is given with rows as sparse vectors class TSparseRowMatrix : public TMatrix { public: // number of rows and columns of matrix TInt RowN, ColN; // vector of sparse rows TVec<TIntFltKdV> RowSpVV; protected: // Result = A * B(:,ColId) virtual void PMultiply(const TFltVV& B, int ColId, TFltV& Result) const; // Result = A * Vec virtual void PMultiply(const TFltV& Vec, TFltV& Result) const; // Result = A' * B(:,ColId) virtual void PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const; // Result = A' * Vec virtual void PMultiplyT(const TFltV& Vec, TFltV& Result) const; // Result = A * B virtual void PMultiply(const TFltVV& B, TFltVV& Result) const { FailR("Not implemented yet"); } // TODO // Result = A' * B virtual void PMultiplyT(const TFltVV& B, TFltVV& Result) const { FailR("Not implemented yet"); } // TODO void Init(); int PGetRows() const { return RowN; } int PGetCols() const { return ColN; } public: TSparseRowMatrix(): TMatrix() {} TSparseRowMatrix(const TVec<TIntFltKdV>& _RowSpVV): TMatrix(), RowSpVV(_RowSpVV) { Init(); } TSparseRowMatrix(const TVec<TIntFltKdV>& _RowSpVV, const int& _RowN, const int& _ColN): TMatrix(), RowN(_RowN), ColN(_ColN), RowSpVV(_RowSpVV) {} // loads Matlab sparse matrix format: row, column, value. // Indexes start with 1. TSparseRowMatrix(const TStr& MatlabMatrixFNm); void Save(TSOut& SOut) { RowN.Save(SOut); ColN.Save(SOut); RowSpVV.Save(SOut); } void Load(TSIn& SIn) { RowN.Load(SIn); ColN.Load(SIn); RowSpVV = TVec<TIntFltKdV>(SIn); } }; /////////////////////////////////////////////////////////////////////// // Full-Col-Matrix // matrix is given with columns of full vectors class TFullColMatrix : public TMatrix { public: // number of rows and columns of matrix TInt RowN, ColN; // vector of sparse columns TVec<TFltV> ColV; protected: // Result = A * B(:,ColId) virtual void PMultiply(const TFltVV& B, int ColId, TFltV& Result) const; // Result = A * Vec virtual void PMultiply(const TFltV& Vec, TFltV& Result) const; // Result = A' * B(:,ColId) virtual void PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const; // Result = A' * Vec virtual void PMultiplyT(const TFltV& Vec, TFltV& Result) const; // Result = A * B virtual void PMultiply(const TFltVV& B, TFltVV& Result) const { FailR("Not implemented yet"); } // TODO // Result = A' * B virtual void PMultiplyT(const TFltVV& B, TFltVV& Result) const { FailR("Not implemented yet"); } // TODO int PGetRows() const { return RowN; } int PGetCols() const { return ColN; } public: TFullColMatrix(): TMatrix() {} // loads matrix saved in matlab with command: // save -ascii Matrix.dat M TFullColMatrix(const TStr& MatlabMatrixFNm); TFullColMatrix(TVec<TFltV>& RowVV); void Save(TSOut& SOut) { RowN.Save(SOut); ColN.Save(SOut); ColV.Save(SOut); } void Load(TSIn& SIn) { RowN.Load(SIn); ColN.Load(SIn); ColV.Load(SIn); } }; /////////////////////////////////////////////////////////////////////// // Structured-Covariance-Matrix // matrix is a product of two sparse matrices X Y' (column examples, row features), // which are centered implicitly by using two dense mean vectors class TStructuredCovarianceMatrix : public TMatrix { private: // number of rows and columns of matrix int XRows, YRows; int Samples; // mean vectors TFltV MeanX; TFltV MeanY; TTriple<TIntV, TIntV, TFltV> X; TTriple<TIntV, TIntV, TFltV> Y; protected: // Result = A * B(:,ColId) virtual void PMultiply(const TFltVV& B, int ColId, TFltV& Result) const; // Result = A * B virtual void PMultiply(const TFltVV& B, TFltVV& Result) const; // Result = A * Vec virtual void PMultiply(const TFltV& Vec, TFltV& Result) const; // Result = A' * B(:,ColId) virtual void PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const; // Result = A' * B virtual void PMultiplyT(const TFltVV& B, TFltVV& Result) const; // Result = A' * Vec virtual void PMultiplyT(const TFltV& Vec, TFltV& Result) const; int PGetRows() const { return XRows; } int PGetCols() const { return YRows; } public: TStructuredCovarianceMatrix() : TMatrix() {} TStructuredCovarianceMatrix(const int XRowN_, const int YRowN_, const int SampleN_, const TFltV& MeanX_, const TFltV& MeanY_, const TTriple<TIntV, TIntV, TFltV>& X_, const TTriple<TIntV, TIntV, TFltV>& Y_) : TMatrix(), XRows(XRowN_), YRows(YRowN_), Samples(SampleN_), MeanX(MeanX_), MeanY(MeanY_), X(X_), Y(Y_) {}; void Save(TSOut& SOut) { SOut.Save(XRows); SOut.Save(YRows); SOut.Save(Samples); MeanX.Save(SOut); MeanY.Save(SOut); X.Save(SOut); Y.Save(SOut); } void Load(TSIn& SIn) { SIn.Load(XRows); SIn.Load(YRows); SIn.Load(Samples); MeanX.Load(SIn); MeanY.Load(SIn); X.Load(SIn); Y.Load(SIn); } }; /////////////////////////////////////////////////////////////////////// // Basic Linear Algebra operations class TLinAlg { public: /// Result = <x, y> template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double DotProduct(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y); /// Result = <X(:,ColId), y> inline static double DotProduct(const TVec<TFltV>& X, int ColId, const TFltV& y); /// Result = <X[ColId], y> inline static double DotProduct(const TVec<TIntFltKdV>& X, int ColId, const TFltV& y); /// Result = <X(:,ColId), Y(:,ColId)> template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double DotProduct(const TVVec<TType, TSizeTy, ColMajor>& X, int ColIdX, const TVVec<TType, TSizeTy, ColMajor>& Y, int ColIdY); /// Result = <X(:,ColId), y> template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double DotProduct(const TVVec<TType, TSizeTy, ColMajor>& X, int ColId, const TVec<TType, TSizeTy>& y); /// Result = <x, y> inline static double DotProduct(const TIntFltKdV& x, const TIntFltKdV& y); /// Result = <x, y> template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double DotProduct(const TVec<TType, TSizeTy>& x, const TVec<TIntFltKd>& y); /// Result = <X(:,ColId), y> template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double DotProduct(const TVVec<TType, TSizeTy, ColMajor>& X, int ColId, const TIntFltKdV& y); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void OuterProduct(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y, TVVec<TType, TSizeTy, ColMajor>& Z); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void LinComb(const double& p, const TVec<TType, TSizeTy>& x, const double& q, const TVec<TType, TSizeTy>& y, TVec<TType, TSizeTy>& z); //TODO this will work only for glib type TFlt template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void LinCombInPlace(const TType& alpha, const TVec<TNum<TType>, TSizeTy>& x, const TType& beta, TVec<TNum<TType>, TSizeTy>& y); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void LinComb(const double& p, const TVVec<TType, TSizeTy, ColMajor>& X, const double& q, const TVVec<TType, TSizeTy, ColMajor>& Y, TVVec<TType, TSizeTy, ColMajor>& Z); // z = p * x + q * y inline static void LinComb(const double& p, const TIntFltKdV& x, const double& q, const TIntFltKdV& y, TIntFltKdV& z); inline static void LinComb(const double& p, const TFltVV& X, int ColId, const double& q, const TFltV& y, TFltV& z); inline static void LinComb(const double& p, const TFltVV& X, int DimId, const double& q, const TFltV& y, TFltV& z, int Dim); inline static void LinComb(const double& p, const TFltVV& X, const double& q, const TFltVV& Y, TFltVV& Z); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void ConvexComb(const double& p, const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y, TVec<TType, TSizeTy>& z); //this will fail if TType != TFlt, Specialization should be used #ifdef BLAS template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void AddVec(const TType& k, const TVec<TNum<TType>, TSizeTy>& x, TVec<TNum<TType>, TSizeTy>& y); #endif template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void AddVec(const double& k, const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y, TVec<TType, TSizeTy>& z); inline static void AddVec(const double& k, const TVec<TFltV>& X, int ColId, const TFltV& y, TFltV& z); inline static void AddVec(const double& k, const TFltVV& X, int ColId, const TFltV& y, TFltV& z); // z := x + y template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void AddVec(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y, TVec<TType, TSizeTy>& z); inline static void AddVec(const double& k, const TIntFltKdV& x, const TFltV& y, TFltV& z); // z := k * X[ColId] + y inline static void AddVec(const double& k, const TVec<TIntFltKdV>& X, int ColId, const TFltV& y, TFltV& z); inline static void AddVec(const double& k, const TIntFltKdV& x, TFltV& y); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void AddVec(double k, const TVVec<TType, TSizeTy, ColMajor>& X, TSizeTy ColIdX, TVVec<TType, TSizeTy, ColMajor>& Y, TSizeTy ColIdY); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void AddVec(const double& k, const TVec<TType, TSizeTy>& x, TVVec<TType, TSizeTy, ColMajor>& Y, const TSizeTy& ColIdY); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void AddVec(double k, const TVVec<TType, TSizeTy, ColMajor>& X, int ColId, TVec<TType, TSizeTy>& Result); // z = x + y template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void AddVec(const TIntFltKdV& x, const TIntFltKdV& y, TIntFltKdV& z); template <class TType, class TSizeTy = int> inline static double SumVec(const TVec<TType, TSizeTy>& x); inline static double SumVec(const TIntFltKdV& x); template <class TType, class TSizeTy = int> inline static double SumVec(double k, const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y); // Result = ||x-y||^2 (Euclidian); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double EuclDist2(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y); // Result = ||x-y||^2 (Euclidian); inline static double EuclDist2(const TFltPr& x, const TFltPr& y); template <class TType, class TSizeTy = int> inline static double EuclDist(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y); inline static double EuclDist(const TFltPr& x, const TFltPr& y); // Result = ||A||_F (Frobenious); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static TType Frob(const TVVec<TNum<TType>, TSizeTy, ColMajor> &A); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double FrobDist2(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double FrobDist2(const TVec<TType, TSizeTy>& A, const TVec<TType, TSizeTy>& B); template <class TType, class TSizeTy = int, bool ColMajor = false, class IndexType = TInt> inline static void Sparse(const TVVec<TType, TSizeTy, ColMajor>& A, TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& B); template <class TType, class TSizeTy = int, bool ColMajor = false, class IndexType = TInt> inline static void Sparse(const TVVec<TType, TSizeTy, ColMajor>& A, TVec<TIntFltKdV>& B); template <class TType, class TSizeTy = int, bool ColMajor = false, class IndexType = TInt> inline static void Full(const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& A, TVVec<TType, TSizeTy, ColMajor>& B, const int Rows, const int Cols); // Sparse to dense transform template <class TType, class TSizeTy = int, bool ColMajor = false, class IndexType = TInt> inline static void Full(const TVec<TIntFltKdV, TSizeTy>& A, TVVec<TType, TSizeTy, ColMajor>& B, TSizeTy Rows); template <class TType, class TSizeTy = int, bool ColMajor = false, class IndexType = TInt> inline static void Transpose(const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& A, TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& At); inline static void Transpose(const TVec<TIntFltKdV>& A, TVec<TIntFltKdV>& At, int Rows = -1); // Sign inline static void Sign(const TVec<TIntFltKdV>& Mat, TVec<TIntFltKdV>& Mat2); inline static void Convert(const TVec<TPair<TIntV, TFltV>>& A, TTriple<TIntV, TIntV, TFltV>& B); inline static void Convert(const TVec<TIntFltKdV>& A, TTriple<TIntV, TIntV, TFltV>&B); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Sum(const TVVec<TType, TSizeTy, ColMajor>& X, TVec<TType, TSizeTy>& y, const int Dimension = 1); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double SumRow(const TVVec<TType, TSizeTy, ColMajor>& X, const int& RowN); template <class TType, class TSizeTy = int, bool ColMajor = false, class IndexType = TInt> inline static void Sum(const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& X, TVec<TType, TSizeTy>& y, const int Dimension = 1); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double Norm2(const TVec<TType, TSizeTy>& x); // ||x|| (Euclidian); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double Norm(const TVec<TType, TSizeTy>& x); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double Normalize(TVec<TType, TSizeTy>& x); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void NormalizeColumn(TVVec<TType, TSizeTy, ColMajor>& X, const TSizeTy& ColId); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void NormalizeColumns(TVVec<TType, TSizeTy, ColMajor>& X); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void NormalizeRows(TVVec<TType, TSizeTy, ColMajor>& X); #ifdef INTEL // TEST template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void NormalizeColumns(TVVec<TType, TSizeTy, ColMajor>& X, TBool ColumnMajor); #endif template <class TType, class TSizeTy = int, bool ColMajor = false, class IndexType = TInt> inline static void NormalizeColumns(TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& X); // Normalize the columns of X template<class TSizeTy = int> inline static void NormalizeColumns(TVec<TIntFltKdV, TSizeTy>& X); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double FrobNorm2(const TVVec<TType, TSizeTy, ColMajor>& X); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double FrobNorm(const TVVec<TType, TSizeTy, ColMajor>& X); // ||x||^2 (Euclidian), x is sparse template<class TSizeTy = int> inline static double Norm2(const TVec<TIntFltKdV, TSizeTy>& x); // ||x|| (Euclidian), x is sparse template<class TSizeTy = int> inline static double Norm(const TVec<TIntFltKdV, TSizeTy>& x); // ||X(:, ColId)|| (Euclidian), x is sparse template<class TSizeTy = int> inline static double Norm(const TVec<TIntFltKdV, TSizeTy>& x, const int& ColId); // x := x / ||x||, x is sparse template<class TSizeTy = int, TSizeTy> inline static void Normalize(TVec<TIntFltKdV>& x); // ||X(:,ColId)||^2 (Euclidian); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double Norm2(const TVVec<TType, TSizeTy, ColMajor>& X, int ColId); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static double Norm(const TVVec<TType, TSizeTy, ColMajor>& X, int ColId); // L1 norm of x (Sum[|xi|, i = 1..n]); template <class TType, class TSizeTy = int> inline static double NormL1(const TVec<TType, TSizeTy>& x); template <class TType, class TSizeTy = int> inline static double NormL1(double k, const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y); // L1 norm of x (Sum[|xi|, i = 1..n]); inline static double NormL1(const TIntFltKdV& x); template <class TType, class TSizeTy = int> inline static void NormalizeL1(TVec<TType, TSizeTy>& x); // x := x / ||x||_1 inline static void NormalizeL1(TIntFltKdV& x); template <class TType, class TSizeTy = int> inline static double NormLinf(const TVec<TType, TSizeTy>& x); // Linf norm of x (Max{|xi|, i = 1..n}); inline static double NormLinf(const TIntFltKdV& x); template <class TType, class TSizeTy = int> inline static void NormalizeLinf(TVec<TType, TSizeTy>& x); // x := x / ||x||_inf, , x is sparse inline static void NormalizeLinf(TIntFltKdV& x); inline static void GetColNormV(const TFltVV& X, TFltV& ColNormV); // stores the norm of all the columns into the output vector inline static void GetColNorm2V(const TFltVV& X, TFltV& ColNormV); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static int GetRowMaxIdx(const TVVec<TType, TSizeTy, ColMajor>& X, const TSizeTy& RowN); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static int GetColMaxIdx(const TVVec<TType, TSizeTy, ColMajor>& X, const int& ColN); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void GetRowMaxIdxV(const TVVec<TType, TSizeTy, ColMajor>& X, TVec<TInt, TSizeTy>& IdxV); // find the index of maximum elements for each col of X template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void GetColMaxIdxV(const TVVec<TType, TSizeTy, ColMajor>& X, TVec<TInt, TSizeTy>& IdxV); template <class TType, class TSizeTy = int> inline static void MultiplyScalar(const double& k, TVec<TType, TSizeTy>& x); // find the index of maximum elements for a given each col of X inline static int GetColMinIdx(const TFltVV& X, const int& ColN); // find the index of maximum elements for each col of X inline static void GetColMinIdxV(const TFltVV& X, TIntV& IdxV); template <class TVal> inline static TVal GetColMin(const TVVec<TVal>& X, const int& ColN); template <class TVal> inline static void GetColMinV(const TVVec<TVal>& X, TVec<TVal>& ValV); template <class TType, class TSizeTy = int> inline static void MultiplyScalar(const double& k, const TVec<TType, TSizeTy>& x, TVec<TType, TSizeTy>& y); // y := k * x inline static void MultiplyScalar(const double& k, const TIntFltKdV& x, TIntFltKdV& y); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void MultiplyScalar(const double& k, const TVVec<TType, TSizeTy, ColMajor>& X, TVVec<TType, TSizeTy, ColMajor>& Y); // Y := k * X template <class TSizeTy = int> inline static void MultiplyScalar(const double& k, const TVec<TIntFltKdV, TSizeTy>& X, TVec<TIntFltKdV, TSizeTy>& Y); // y := A * x template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVec<TType, TSizeTy>& x, TVec<TType, TSizeTy>& y); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVec<TType, TSizeTy>& x, TVVec<TType, TSizeTy, ColMajor>& C, TSizeTy ColId); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, int ColId, TVec<TType, TSizeTy>& y); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, int ColIdB, TVVec<TType, TSizeTy, ColMajor>& C, int ColIdC); //LAPACKE stuff #ifdef LAPACKE // Tested in other function //A is rewritten in place with orthogonal matrix Q template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void QRbasis(TVVec<TType, TSizeTy, ColMajor>& A); template <class TType, class TSizeTy, bool ColMajor> inline static void QRbasis(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& Q); // Tested in other function //A is rewritten in place with orthogonal matrix Q (column pivoting to improve stability); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void QRcolpbasis(TVVec<TType, TSizeTy, ColMajor>& A); // TEST template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void QRcolpbasis(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& Q); // TEST //S S option ensures that A is not modified template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void thinSVD(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& U, TVec<TType, TSizeTy>& S, TVVec<TType, TSizeTy, ColMajor>& VT); static void SVDFactorization(const TFltVV& A, TFltVV& U, TFltV& Sing, TFltVV& VT) { // data used for factorization int NumOfRows_Matrix = A.GetRows(); int NumOfCols_Matrix = A.GetCols(); // handle edge cases where the factorization is trivial. Double and float only! if (NumOfRows_Matrix == 1) { U.Gen(1, 1); U(0, 0) = 1; VT = A; Sing.Gen(1); // normalize VT and set Sing[0] = oldnorm(VT) TFltV& RawV = VT.Get1DVec(); Sing[0] = TLinAlg::Normalize(RawV); return; } else if (NumOfCols_Matrix == 1) { VT.Gen(1, 1); VT(0, 0) = 1; U = A; Sing.Gen(1); // normalize U and set Sing[0] = oldnorm(U) TFltV& RawV = U.Get1DVec(); Sing[0] = TLinAlg::Normalize(RawV); return; } int LeadingDimension_Matrix = NumOfCols_Matrix; int Matrix_Layout = LAPACK_ROW_MAJOR; // preperation for factorization Sing.Gen(MIN(NumOfRows_Matrix, NumOfCols_Matrix)); TFltV UpDiag, TauQ, TauP; UpDiag.Gen(MIN(NumOfRows_Matrix, NumOfCols_Matrix) - 1); TauQ.Gen(MIN(NumOfRows_Matrix, NumOfCols_Matrix)); TauP.Gen(MIN(NumOfRows_Matrix, NumOfCols_Matrix)); // bidiagonalization of Matrix TFltVV M = A; LAPACKE_dgebrd(Matrix_Layout, NumOfRows_Matrix, NumOfCols_Matrix, &M(0, 0).Val, LeadingDimension_Matrix, &Sing[0].Val, &UpDiag[0].Val, &TauQ[0].Val, &TauP[0].Val); // matrix U used in the SVD factorization U = M; LAPACKE_dorgbr(Matrix_Layout, 'Q', NumOfRows_Matrix, MIN(NumOfRows_Matrix, NumOfCols_Matrix), NumOfCols_Matrix, &U(0, 0).Val, LeadingDimension_Matrix, &TauQ[0].Val); // matrix VT used in the SVD factorization VT = M; LAPACKE_dorgbr(Matrix_Layout, 'P', MIN(NumOfRows_Matrix, NumOfCols_Matrix), NumOfCols_Matrix, NumOfRows_Matrix, &VT(0, 0).Val, LeadingDimension_Matrix, &TauP[0].Val); // factorization TFltVV C(U.GetCols(), 1); char UpperLower = NumOfRows_Matrix >= NumOfCols_Matrix ? 'U' : 'L'; int LeadingDimension_VT = VT.GetCols(); int LeadingDimension_U = U.GetCols(); LAPACKE_dbdsqr(Matrix_Layout, UpperLower, Sing.Len(), VT.GetCols(), U.GetRows(), 0, &Sing[0].Val, &UpDiag[0].Val, &VT(0, 0).Val, LeadingDimension_VT, &U(0, 0).Val, LeadingDimension_U, &C(0, 0).Val, 1); } static void SVDSolve(const TFltVV& A, TFltV& x, const TFltV& b, const double& EpsSing) { Assert(A.GetRows() == b.Len()); // data used for solution int NumOfRows_Matrix = A.GetRows(); int NumOfCols_Matrix = A.GetCols(); // generating the SVD factorization TFltVV U, VT, M = A; TFltV Sing; SVDFactorization(M, U, Sing, VT); // generating temporary solution x.Gen(NumOfCols_Matrix); TLAMisc::FillZero(x); TFltV ui; ui.Gen(U.GetRows()); TFltV vi; vi.Gen(VT.GetCols()); double Scalar; int i = 0; while (i < MIN(NumOfRows_Matrix, NumOfCols_Matrix) && Sing[i].Val > EpsSing*Sing[0]) { U.GetCol(i, ui); VT.GetRow(i, vi); Scalar = TLinAlg::DotProduct(ui, b) / Sing[i].Val; TLinAlg::AddVec(Scalar, vi, x); i++; } } #endif static int ComputeThinSVD(const TMatrix& X, const int& k, TFltVV& U, TFltV& s, TFltVV& V, const int Iters = 2, const double Tol = 1e-6); #ifdef INTEL template <class TType, class TSizeTy, bool ColMajor = false> inline static void MultiplySF(const TTriple<TVec<TNum<TSizeTy>, TSizeTy>, TVec<TNum<TSizeTy>, TSizeTy>, TVec<TType, TSizeTy>>& A, const TVVec<TType, TSizeTy, false>& B, TVVec<TType, TSizeTy, ColMajor>& C, const TStr& transa = TStr("N"), const int& format = 0); template <class IndexType = TInt, class TType, class TSizeTy = int, bool ColMajor = false> inline static void MultiplyFS(TVVec<TType, TSizeTy, ColMajor>& B, const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& A, TVVec<TType, TSizeTy, ColMajor>& C); #endif // y := A * x template <class IndexType = TInt, class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TPair<TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& x, TVec<TType, TSizeTy>& y); //y := x' * A ... row data!! template <class IndexType = TInt, class TType, class TSizeTy = int, bool ColMajor = false> inline static void MultiplyT(const TPair<TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& x, const TVVec<TType, TSizeTy, ColMajor>& A, TVec<TType, TSizeTy>& y); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void MultiplyT(const TVVec<TNum<TType>, TSizeTy, ColMajor>& A, const TVec<TNum<TType>, TSizeTy>& x, TVec<TNum<TType>, TSizeTy>& y); #ifdef BLAS typedef enum { NOTRANS = 0, TRANS = 1 } TLinAlgBlasTranspose; template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TVVec<TNum<TType>, TSizeTy, ColMajor>& A, const TVVec<TNum<TType>, TSizeTy, ColMajor>& B, TVVec<TNum<TType>, TSizeTy, ColMajor>& C, const int& BlasTransposeFlagA, const int& BlasTransposeFlagB); #endif #ifdef BLAS template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TVVec<TNum<TType>, TSizeTy, ColMajor>& A, const TVec<TNum<TType>, TSizeTy>& x, TVec<TNum<TType>, TSizeTy>& y, const int& BlasTransposeFlagA, TType alpha = 1.0, TType beta = 0.0); #endif template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, TVVec<TType, TSizeTy, ColMajor>& C); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void MultiplyT(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, TVVec<TType, TSizeTy, ColMajor>& C); template <class IndexType = TInt, class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& B, TVVec<TType, TSizeTy, ColMajor>& C); template <class IndexType = TInt, class TType, class TSizeTy = int, bool ColMajor = false> inline static void MultiplyT(const TVVec<TType, TSizeTy, ColMajor>& A, const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& B, TVVec<TType, TSizeTy, ColMajor>& C); //#if !defined(INTEL) || defined(INDEX_64); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Multiply(const TTriple<TVec<TNum<TSizeTy>, TSizeTy>, TVec<TNum<TSizeTy>, TSizeTy>, TVec<TType, TSizeTy>>& A, const TVVec<TType, TSizeTy, ColMajor>& B, TVVec<TType, TSizeTy, ColMajor>& C); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void MultiplyT(const TTriple<TVec<TNum<TSizeTy>, TSizeTy>, TVec<TNum<TSizeTy>, TSizeTy>, TVec<TType, TSizeTy>>& A, const TVVec<TType, TSizeTy, ColMajor>& B, TVVec<TType, TSizeTy, ColMajor>& C); inline static void Multiply(const TFltVV& A, const TVec<TIntFltKdV>& B, TFltVV& C); // C:= A' * B template <class IndexType = TInt, class TType, class TSizeTy = int, bool ColMajor = false> inline static void MultiplyT(const TVVec<TType, TSizeTy, ColMajor>& A, const TVec<TVec<TKeyDat<IndexType, TType>, TSizeTy>, TSizeTy>& B, TVVec<TType, TSizeTy, ColMajor>& C); inline static void Multiply(const TVec<TIntFltKdV>& A, const TFltVV& B, TFltVV& C, const int RowsA = -1); inline static void MultiplyT(const TVec<TIntFltKdV>& A, const TFltVV& B, TFltVV& C); inline static void Multiply(const TVec<TIntFltKdV>& A, const TVec<TIntFltKdV>& B, TFltVV& C, const int RowsA = -1); inline static void MultiplyT(const TVec<TIntFltKdV>& A, const TVec<TIntFltKdV>& B, TFltVV& C); typedef enum { GEMM_NO_T = 0, GEMM_A_T = 1, GEMM_B_T = 2, GEMM_C_T = 4 } TLinAlgGemmTranspose; template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Gemm(const double& Alpha, const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, const double& Beta, const TVVec<TType, TSizeTy, ColMajor>& C, TVVec<TType, TSizeTy, ColMajor>& D, const int& TransposeFlags); typedef enum { DECOMP_SVD } TLinAlgInverseType; template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Inverse(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor >& B, const TLinAlgInverseType& DecompType); // subtypes of finding an inverse (works only for TFltVV, cuz of TSvd); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void InverseSVD(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& B, const double& tol); // subtypes of finding an inverse (works only for TFltVV, cuz of TSvd); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void InverseSVD(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& B); // transpose matrix - B = A' template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Transpose(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& B); // performes Gram-Schmidt ortogonalization on elements of Q template <class TSizeTy = int> inline static void GS(TVec<TVec<TFlt, TSizeTy>, TSizeTy>& Q); template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void GS(TVVec<TType, TSizeTy, ColMajor>& Q); // Modified Gram-Schmidt on columns of matrix Q inline static void MGS(TFltVV& Q); // QR based on Modified Gram-Schmidt decomposition. inline static void QR(const TFltVV& X, TFltVV& Q, TFltVV& R, const TFlt& Tol); // rotates vector (OldX,OldY) for angle Angle (in radians!); inline static void Rotate(const double& OldX, const double& OldY, const double& Angle, double& NewX, double& NewY); // checks if set of vectors is ortogonal template <class TSizeTy = int> inline static void AssertOrtogonality(const TVec<TVec<TFlt, TSizeTy>, TSizeTy>& Vecs, const double& Threshold); //ColMajor oriented data for optimal result template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void AssertOrtogonality(const TVVec<TType, TSizeTy, ColMajor>& Vecs, const double& Threshold); inline static bool IsOrthonormal(const TFltVV& Vecs, const double& Threshold); inline static bool IsZero(const TFltV& Vec); // returns the k-th power of the given matrix // negative values of k are allowed template <class TType, class TSizeTy = int, bool ColMajor = false> inline static void Pow(const TVVec<TType, TSizeTy, ColMajor>& Mat, const int& k, TVVec<TType, TSizeTy, ColMajor>& PowVV); }; ////////////////////////////////////////////////////////////////////// // Basic Linear Algebra Operations //class TLinAlg { //public: // <x,y> // TEST template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::DotProduct(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y) { EAssertR(x.Len() == y.Len(), TStr::Fmt("%d != %d", x.Len(), y.Len())); TType result = 0.0; const TSizeTy Len = x.Len(); for (TSizeTy i = 0; i < Len; i++) result += x[i] * y[i]; return result; } double TLinAlg::DotProduct(const TVec<TFltV>& X, int ColId, const TFltV& y) { EAssert(0 <= ColId && ColId < X.Len()); return DotProduct(X[ColId], y); } double TLinAlg::DotProduct(const TVec<TIntFltKdV>& X, int ColId, const TFltV& y) { EAssert(0 <= ColId && ColId < X.Len()); return DotProduct(y, X[ColId]); } // TEST // <X(:,ColIdX), Y(:,ColIdY)> template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::DotProduct(const TVVec<TType, TSizeTy, ColMajor>& X, int ColIdX, const TVVec<TType, TSizeTy, ColMajor>& Y, int ColIdY) { EAssert(X.GetRows() == Y.GetRows()); TType result = 0.0; const TSizeTy len = X.GetRows(); for (TSizeTy i = 0; i < len; i++) result = result + X(i, ColIdX) * Y(i, ColIdY); return result; } // TEST // <X(:,ColId), Vec> template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::DotProduct(const TVVec<TType, TSizeTy, ColMajor>& X, int ColId, const TVec<TType, TSizeTy>& Vec) { EAssert(X.GetRows() == Vec.Len()); TType result = 0.0; const TSizeTy len = X.GetRows(); for (TSizeTy i = 0; i < len; i++) result += X(i, ColId) * Vec[i]; return result; } // sparse dot products: // <x,y> where x AND y are sparse //TODO TIntFltKdV indexing and is TInt enough? double TLinAlg::DotProduct(const TIntFltKdV& x, const TIntFltKdV& y) { const int xLen = x.Len(), yLen = y.Len(); double Res = 0.0; int i1 = 0, i2 = 0; while (i1 < xLen && i2 < yLen) { if (x[i1].Key < y[i2].Key) i1++; else if (x[i1].Key > y[i2].Key) i2++; else { Res += x[i1].Dat * y[i2].Dat; i1++; i2++; } } return Res; } // <x,y> where only y is sparse //TODO TIntFltKdV indexing and is TInt enough? template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::DotProduct(const TVec<TType, TSizeTy>& x, const TVec<TIntFltKd>& y) { double Res = 0.0; const int xLen = x.Len(), yLen = y.Len(); for (TSizeTy i = 0; i < yLen; i++) { const TSizeTy key = y[i].Key; if (key < xLen) Res += y[i].Dat * x[key]; } return Res; } // <X(:,ColId),y> where only y is sparse template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::DotProduct(const TVVec<TType, TSizeTy, ColMajor>& X, int ColId, const TIntFltKdV& y) { TType Res = 0.0; const TSizeTy n = X.GetRows(), yLen = y.Len(); for (TSizeTy i = 0; i < yLen; i++) { const TSizeTy key = y[i].Key; if (key < n) Res += y[i].Dat * X(key, ColId); } return Res; } // TEST // z = x * y' template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::OuterProduct(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y, TVVec<TType, TSizeTy, ColMajor>& Z) { EAssert(Z.GetRows() == x.Len() && Z.GetCols() == y.Len()); const TSizeTy XLen = x.Len(); const TSizeTy YLen = y.Len(); for (TSizeTy i = 0; i < XLen; i++) { for (TSizeTy j = 0; j < YLen; j++) { Z(i, j) = x[i] * y[j]; } } } // z := p * x + q * y //TODO should double be TType? template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::LinComb(const double& p, const TVec<TType, TSizeTy>& x, const double& q, const TVec<TType, TSizeTy>& y, TVec<TType, TSizeTy>& z) { EAssert(x.Len() == y.Len() && y.Len() == z.Len()); const TSizeTy Len = x.Len(); for (TSizeTy i = 0; i < Len; i++) { z[i] = p * x[i] + q * y[i]; } } //TODO this will work only for glib type TFlt template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::LinCombInPlace(const TType& alpha, const TVec<TNum<TType>, TSizeTy>& x, const TType& beta, TVec<TNum<TType>, TSizeTy>& y) { #ifdef BLAS if (TypeCheck::is_double<TType>::value == true){ typedef double Loc; cblas_daxpby(x.Len(), *((Loc *)&alpha), (Loc *)&x[0].Val, 1, *((Loc *)&beta), (Loc *)&y[0].Val, 1); } else if (TypeCheck::is_float<TType>::value == true){ typedef float Loc; cblas_saxpby(x.Len(), *((Loc *)&alpha), (Loc *)&x[0].Val, 1, *((Loc *)&beta), (Loc *)&y[0].Val, 1); } else if (TypeCheck::is_complex_double<TType>::value == true){ typedef double Loc; //std::complex<double> alpha_(alpha); std::complex<double> beta_(beta); cblas_zaxpby(x.Len(), (const Loc*)&alpha, (const Loc*)&x[0].Val, 1, (const Loc*)&beta, (Loc*)&y[0].Val, 1); } else if (TypeCheck::is_complex_float<TType>::value == true){ typedef float Loc; //std::complex<float> alpha_((float)alpha); std::complex<float> beta_((float)beta); cblas_caxpby(x.Len(), (const Loc*)&alpha, (const Loc*)&x[0].Val, 1, (const Loc*)&beta, (Loc*)&y[0].Val, 1); } #else LinComb(alpha, x, beta, y, y); #endif } // TEST // Z := p * X + q * Y //TODO double or type? template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::LinComb(const double& p, const TVVec<TType, TSizeTy, ColMajor>& X, const double& q, const TVVec<TType, TSizeTy, ColMajor>& Y, TVVec<TType, TSizeTy, ColMajor>& Z) { EAssert(X.GetRows() == Y.GetRows() && X.GetCols() == Y.GetCols() && X.GetRows() == Z.GetRows() && X.GetCols() == Z.GetCols()); TSizeTy Rows = X.GetRows(); TSizeTy Cols = X.GetCols(); for (TSizeTy RowN = 0; RowN < Rows; RowN++) { for (TSizeTy ColN = 0; ColN < Cols; ColN++) { Z.At(RowN, ColN) = p*X.At(RowN, ColN) + q*Y.At(RowN, ColN); } } } // z = p * x + q * y void TLinAlg::LinComb(const double& p, const TIntFltKdV& x, const double& q, const TIntFltKdV& y, TIntFltKdV& z) { TSparseOpsIntFlt::SparseLinComb(p, x, q, y, z); } void TLinAlg::LinComb(const double& p, const TFltVV& X, int ColId, const double& q, const TFltV& y, TFltV& z) { if (z.Empty()) z.Gen(X.GetRows()); EAssert(X.GetRows() == y.Len() && y.Len() == z.Len()); const int len = z.Len(); for (int i = 0; i < len; i++) { z[i] = p * X(i, ColId) + q * y[i]; } } void TLinAlg::LinComb(const double& p, const TFltVV& X, int DimId, const double& q, const TFltV& y, TFltV& z, int Dim) { EAssertR(Dim == 1 || Dim == 2, "TLinAlg::LinComb: Invalid value of argument Dim."); if (Dim == 1) { if (z.Empty()) z.Gen(X.GetRows()); EAssert(X.GetRows() == y.Len() && y.Len() == z.Len()); const int len = z.Len(); for (int i = 0; i < len; i++) { z[i] = p * X(i, DimId) + q * y[i]; } } else if (Dim == 2) { if (z.Empty()) z.Gen(X.GetCols()); EAssert(X.GetCols() == y.Len() && y.Len() == z.Len()); const int len = z.Len(); for (int i = 0; i < len; i++) { z[i] = p * X(DimId, i) + q * y[i]; } } } void TLinAlg::LinComb(const double& p, const TFltVV& X, const double& q, const TFltVV& Y, TFltVV& Z) { if (Z.Empty()) Z.Gen(X.GetRows(), X.GetCols()); EAssert(X.GetRows() == Y.GetRows() && X.GetCols() == Y.GetCols() && X.GetRows() == Z.GetRows() && X.GetCols() == Z.GetCols()); int Rows = X.GetRows(); int Cols = X.GetCols(); for (int RowN = 0; RowN < Rows; RowN++) { for (int ColN = 0; ColN < Cols; ColN++) { Z.At(RowN, ColN) = p*X.At(RowN, ColN) + q*Y.At(RowN, ColN); } } } // TEST // z := p * x + (1 - p) * y template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::ConvexComb(const double& p, const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y, TVec<TType, TSizeTy>& z) { AssertR(0.0 <= p && p <= 1.0, TFlt::GetStr(p)); TLinAlg::LinComb(p, x, 1.0 - p, y, z); } //this will fail if TType != TFlt, Specialization should be used #ifdef BLAS // TEST //y = k * x + y template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(const TType& k, const TVec<TNum<TType>, TSizeTy>& x, TVec<TNum<TType>, TSizeTy>& y) { if (TypeCheck::is_double<TType>::value == true){ typedef double Loc; cblas_daxpy(x.Len(), *((Loc *)&k), (Loc *)&x[0].Val, 1, (Loc *)&y[0].Val, 1); } else if (TypeCheck::is_float<TType>::value == true){ typedef float Loc; cblas_saxpy(x.Len(), *((Loc *)&k), (Loc *)&x[0].Val, 1, (Loc *)&y[0].Val, 1); } else if (TypeCheck::is_complex_double<TType>::value == true){ typedef double Loc; cblas_zaxpy(x.Len(), (const Loc *)&k, (const Loc*)&x[0].Val, 1, (Loc *)&y[0].Val, 1); } else if (TypeCheck::is_complex_float<TType>::value == true){ typedef float Loc; cblas_caxpy(x.Len(), (const Loc *)&k, (const Loc *)&x[0].Val, 1, (Loc *)&y[0].Val, 1); } //cblas_daxpy(x.Len(), k, &x[0].Val, 1, &y[0].Val, 1); } #endif // TEST // z := k * x + y template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(const double& k, const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y, TVec<TType, TSizeTy>& z) { TLinAlg::LinComb(k, x, 1.0, y, z); } // z := k * X[ColId] + y //Andrej template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(const double& k, const TVec<TFltV>& X, int ColId, const TFltV& y, TFltV& z) { EAssert(0 <= ColId && ColId < X.Len()); AddVec(k, X[ColId], y, z); } // z := k * X(:,ColId) + y //Andrej template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(const double& k, const TFltVV& X, int ColId, const TFltV& y, TFltV& z) { EAssert(X.GetRows() == y.Len()); EAssert(y.Len() == z.Len()); const int len = z.Len(); for (int i = 0; i < len; i++) { z[i] = y[i] + k * X(i, ColId); } } // z := x + y template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y, TVec<TType, TSizeTy>& z) { TLinAlg::LinComb(1.0, x, 1.0, y, z); } // z := k * x + y //template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(const double& k, const TIntFltKdV& x, const TFltV& y, TFltV& z) { EAssert(y.Len() == z.Len()); z = y; // first we set z to be y // and than we add x to z (==y) const int xLen = x.Len(), yLen = y.Len(); for (int i = 0; i < xLen; i++) { const int ii = x[i].Key; if (ii < yLen) { z[ii] = k * x[i].Dat + y[ii]; } } } // z := k * X[ColId] + y void TLinAlg::AddVec(const double& k, const TVec<TIntFltKdV>& X, int ColId, const TFltV& y, TFltV& z) { EAssert(0 <= ColId && ColId < X.Len()); AddVec(k, X[ColId], y, z); } // y := k * x + y //template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(const double& k, const TIntFltKdV& x, TFltV& y) { const int xLen = x.Len(), yLen = y.Len(); for (int i = 0; i < xLen; i++) { const int ii = x[i].Key; if (ii < yLen) { y[ii] += k * x[i].Dat; } } } // TEST // Y(:,Col) += k * X(:,Col) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(double k, const TVVec<TType, TSizeTy, ColMajor>& X, TSizeTy ColIdX, TVVec<TType, TSizeTy, ColMajor>& Y, TSizeTy ColIdY) { EAssert(X.GetRows() == Y.GetRows()); const TSizeTy len = Y.GetRows(); for (TSizeTy i = 0; i < len; i++) { Y(i, ColIdY) = Y(i, ColIdY) + k * X(i, ColIdX); } } // TEST // Y(:,ColIdY) += k * x template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(const double& k, const TVec<TType, TSizeTy>& x, TVVec<TType, TSizeTy, ColMajor>& Y, const TSizeTy& ColIdY) { EAssert(x.Len() == Y.GetRows()); EAssert(ColIdY >= 0 && ColIdY < x.Len()); for (TSizeTy RowN = 0; RowN < Y.GetRows(); RowN++) { Y.At(RowN, ColIdY) += k*x[RowN]; } } // TEST // Result += k * X(:,Col) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(double k, const TVVec<TType, TSizeTy, ColMajor>& X, int ColId, TVec<TType, TSizeTy>& Result) { EAssert(X.GetRows() == Result.Len()); const TSizeTy len = Result.Len(); for (TSizeTy i = 0; i < len; i++) { Result[i] = Result[i] + k * X(i, ColId); } } // z = x + y template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AddVec(const TIntFltKdV& x, const TIntFltKdV& y, TIntFltKdV& z) { TSparseOpsIntFlt::SparseMerge(x, y, z); } // TEST // Result = SUM(x) template <class TType, class TSizeTy> double TLinAlg::SumVec(const TVec<TType, TSizeTy>& x) { const TSizeTy len = x.Len(); double Res = 0.0; for (int i = 0; i < len; i++) { Res += x[i]; } return Res; } // Result = SUM(x) //template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::SumVec(const TIntFltKdV& x) { const int len = x.Len(); double Res = 0.0; for (int i = 0; i < len; i++) { Res += x[i].Dat; } return Res; } // TEST // Result = SUM(k*x + y) template <class TType, class TSizeTy> double TLinAlg::SumVec(double k, const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y) { EAssert(x.Len() == y.Len()); const TSizeTy len = x.Len(); double Res = 0.0; for (TSizeTy i = 0; i < len; i++) { Res += k * x[i] + y[i]; } return Res; } // Result = ||x-y||^2 (Euclidian) template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::EuclDist2(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y) { EAssert(x.Len() == y.Len()); const TSizeTy len = x.Len(); double Res = 0.0; for (TSizeTy i = 0; i < len; i++) { Res += TMath::Sqr(x[i] - y[i]); } return Res; } // Result = ||x-y||^2 (Euclidian) double TLinAlg::EuclDist2(const TFltPr& x, const TFltPr& y) { return TMath::Sqr(x.Val1 - y.Val1) + TMath::Sqr(x.Val2 - y.Val2); } // TEST // Result = ||x-y|| (Euclidian) template <class TType, class TSizeTy> double TLinAlg::EuclDist(const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y) { return sqrt(TLinAlg::EuclDist2(x, y)); } // Result = ||x-y|| (Euclidian) //template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::EuclDist(const TFltPr& x, const TFltPr& y) { return sqrt(TLinAlg::EuclDist2(x, y)); } // Result = ||A||_F (Frobenious) template <class TType, class TSizeTy, bool ColMajor> TType TLinAlg::Frob(const TVVec<TNum<TType>, TSizeTy, ColMajor> &A) { TType frob = 0; for (int RowN = 0; RowN < A.GetRows(); RowN++) { for (int ColN = 0; ColN < A.GetCols(); ColN++) { frob += A.At(RowN, ColN)*A.At(RowN, ColN); } } return sqrt(frob); } // TEST // Result = ||A - B||_F (Frobenious) template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::FrobDist2(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B) { double frob = 0; TVec<TType, TSizeTy> Apom = (const_cast<TVVec<TType, TSizeTy, ColMajor> &>(A)).Get1DVec(); TVec<TType, TSizeTy> Bpom = (const_cast<TVVec<TType, TSizeTy, ColMajor> &>(B)).Get1DVec(); frob = TLinAlg::EuclDist2(Apom, Bpom); /*for (int RowN = 0; RowN < A.GetRows(); RowN++) { for (int ColN = 0; ColN < A.GetCols(); ColN++) { frob += (A.At(RowN, ColN) - B.At(RowN, ColN))*(A.At(RowN, ColN) - B.At(RowN, ColN)); } }*/ return frob; } // TEST // Result = ||A - B||_F (Frobenious) template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::FrobDist2(const TVec<TType, TSizeTy>& A, const TVec<TType, TSizeTy>& B) { double frob = 0; frob = TLinAlg::EuclDist2(A, B); /*for (int RowN = 0; RowN < A.Len(); RowN++) { frob += (A[RowN] - B[RowN])*(A[RowN] - B[RowN]); }*/ return frob; } // Dense to sparse transform // TEST // Dense to sparse transform template <class TType, class TSizeTy, bool ColMajor, class IndexType> void TLinAlg::Sparse(const TVVec<TType, TSizeTy, ColMajor>& A, TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& B){ B.Val1.Gen(0); B.Val2.Gen(0); B.Val3.Gen(0); for (TSizeTy RowN = 0; RowN < A.GetRows(); RowN++) { for (TSizeTy ColN = 0; ColN < A.GetCols(); ColN++) { if (A.At(RowN, ColN) != 0.0) { B.Val1.Add(RowN); B.Val2.Add(ColN); B.Val3.Add(A.At(RowN, ColN)); } } } } // Dense to sparse transform //TODO fix TVec<TIntFltKdV> indexing and type template <class TType, class TSizeTy, bool ColMajor, class IndexType> void TLinAlg::Sparse(const TVVec<TType, TSizeTy, ColMajor>& A, TVec<TIntFltKdV>& B){ TSizeTy Cols = A.GetCols(); TSizeTy Rows = A.GetRows(); B.Gen(Cols); for (TSizeTy ColN = 0; ColN < Cols; ColN++) { B[ColN].Gen(0); for (TSizeTy RowN = 0; RowN < Rows; RowN++) { if (A.At(RowN, ColN) != 0.0) { B[ColN].Add(TIntFltKd(RowN, A.At(RowN, ColN))); } } } } // TEST // Sparse to dense transform template <class TType, class TSizeTy, bool ColMajor, class IndexType> void TLinAlg::Full(const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& A, TVVec<TType, TSizeTy, ColMajor>& B, const int Rows, const int Cols) { B.Gen(Rows, Cols); B.PutAll(0.0); TSizeTy nnz = A.Val1.Len(); for (TSizeTy ElN = 0; ElN < nnz; ElN++) { B.At(A.Val1[ElN], A.Val2[ElN]) = A.Val3[ElN]; } } // Sparse to dense transform template <class TType, class TSizeTy, bool ColMajor, class IndexType> void TLinAlg::Full(const TVec<TIntFltKdV, TSizeTy>& A, TVVec<TType, TSizeTy, ColMajor>& B, TSizeTy Rows){ TSizeTy Cols = A.Len(); B.Gen(Rows, Cols); B.PutAll(0.0); for (TSizeTy ColN = 0; ColN < Cols; ColN++) { TSizeTy Els = A[ColN].Len(); for (TSizeTy ElN = 0; ElN < Els; ElN++) { B.At(A[ColN][ElN].Key, ColN) = A[ColN][ElN].Dat; } } } // TEST // Transpose template <class TType, class TSizeTy, bool ColMajor, class IndexType> void TLinAlg::Transpose(const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& A, TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& At) { TSizeTy nnz = A.Val1.Len(); At.Val1.Gen(nnz, 0); At.Val2.Gen(nnz, 0); At.Val3.Gen(nnz, 0); TVec<TSizeTy, TSizeTy> index; TIntV::SortGetPerm(A.Val2, At.Val1, index); for (TSizeTy ElN = 0; ElN < nnz; ElN++) { //At.Val1.Add(A.Val2[ElN]); At.Val2.Add(A.Val1[index[ElN]]); At.Val3.Add(A.Val3[index[ElN]]); } } // Transpose //TODO Index template void TLinAlg::Transpose(const TVec<TIntFltKdV>& A, TVec<TIntFltKdV>& At, int Rows){ // A is a sparse col matrix: int Cols = A.Len(); // find number of rows if (Rows == -1) { for (int ColN = 0; ColN < Cols; ColN++) { int Els = A[ColN].Len(); for (int ElN = 0; ElN < Els; ElN++) { Rows = MAX(Rows, A[ColN][ElN].Key.Val); } } Rows = Rows + 1; } At.Gen(Rows); // transpose for (int ColN = 0; ColN < Cols; ColN++) { int Els = A[ColN].Len(); for (int ElN = 0; ElN < Els; ElN++) { At[A[ColN][ElN].Key].Add(TIntFltKd(ColN, A[ColN][ElN].Dat)); } } // sort for (int ColN = 0; ColN < Rows; ColN++) { At[ColN].Sort(); } } // Sign void TLinAlg::Sign(const TVec<TIntFltKdV>& Mat, TVec<TIntFltKdV>& Mat2) { Mat2 = Mat; int Cols = Mat2.Len(); for (int ColN = 0; ColN < Cols; ColN++) { int Els = Mat2[ColN].Len(); for (int ElN = 0; ElN < Els; ElN++) { Mat2[ColN][ElN].Dat = TMath::Sign(Mat2[ColN][ElN].Dat); } } } // Vector of sparse vectors to sparse matrix (coordinate representation) //TODO Index template void TLinAlg::Convert(const TVec<TPair<TIntV, TFltV>>& A, TTriple<TIntV, TIntV, TFltV>& B) { B.Val1.Clr(); B.Val2.Clr(); B.Val3.Clr(); int Cols = A.Len(); for (int ColN = 0; ColN < Cols; ColN++) { int Nnz = A[ColN].Val1.Len(); for (int ElN = 0; ElN < Nnz; ElN++) { B.Val1.Add(A[ColN].Val1[ElN]); B.Val2.Add(ColN); B.Val3.Add(A[ColN].Val2[ElN]); } } } // Vector of sparse vectors to sparse matrix (coordinate representation) //TODO Index template void TLinAlg::Convert(const TVec<TIntFltKdV>& A, TTriple<TIntV, TIntV, TFltV>&B) { int Cols = A.Len(); int TotalNnz = 0; for (int ColN = 0; ColN < Cols; ColN++) { TotalNnz += A[ColN].Len(); } B.Val1.Gen(TotalNnz, 0); B.Val2.Gen(TotalNnz, 0); B.Val3.Gen(TotalNnz, 0); for (int ColN = 0; ColN < Cols; ColN++) { int Nnz = A[ColN].Len(); for (int ElN = 0; ElN < Nnz; ElN++) { B.Val1.Add(A[ColN][ElN].Key); B.Val2.Add(ColN); B.Val3.Add(A[ColN][ElN].Dat); } } } // TEST // sum columns (Dimension = 1) or rows (Dimension = 2) and store them in vector y template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Sum(const TVVec<TType, TSizeTy, ColMajor>& X, TVec<TType, TSizeTy>& y, const int Dimension){ TSizeTy Cols = X.GetCols(); TSizeTy Rows = X.GetRows(); if (Dimension == 1) { y.Gen(Cols); for (TSizeTy ColN = 0; ColN < Cols; ColN++) { for (TSizeTy RowN = 0; RowN < Rows; RowN++) { y[ColN] += X.At(RowN, ColN); } } } else if (Dimension == 2) { y.Gen(Rows); for (TSizeTy ColN = 0; ColN < Cols; ColN++) { for (TSizeTy RowN = 0; RowN < Rows; RowN++) { y[RowN] += X.At(RowN, ColN); } } } else FailR("Dimension should be 1 or 2"); } template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::SumRow(const TVVec<TType, TSizeTy, ColMajor>& X, const int& RowN) { EAssertR(RowN < X.GetRows(), "Row index exceeds the number of rows!"); const int Cols = X.GetCols(); double Sum = 0; for (int ColN = 0; ColN < Cols; ColN++) { Sum += X(RowN, ColN); } return Sum; } // TEST // sum columns (Dimesnion = 2) or rows (Dimension = 1) and store them in vector y template <class TType, class TSizeTy, bool ColMajor, class IndexType> void TLinAlg::Sum(const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& X, TVec<TType, TSizeTy>& y, const int Dimension) { TSizeTy Cols = X.Val2.GetMxVal() + 1; TSizeTy Rows = X.Val1.GetMxVal() + 1; TSizeTy Els = X.Val1.Len(); if (Dimension == 1) { y.Gen(Cols); for (TSizeTy ElN = 0; ElN < Els; ElN++) { //int RowN = X.Val1[ElN]; TSizeTy ColN = X.Val2[ElN]; y[ColN] += X.Val3[ElN]; } } else if (Dimension == 2) { y.Gen(Rows); for (TSizeTy ElN = 0; ElN < Els; ElN++) { TSizeTy RowN = X.Val1[ElN]; //int ColN = X.Val2[ElN]; y[RowN] += X.Val3[ElN]; } } else FailR("Dimension should be 1 or 2"); } // TEST // ||x||^2 (Euclidian) template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::Norm2(const TVec<TType, TSizeTy>& x) { return TLinAlg::DotProduct(x, x); } // ||x|| (Euclidian) template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::Norm(const TVec<TType, TSizeTy>& x) { return sqrt(TLinAlg::Norm2(x)); } //Andrej switch this to TNum<TType> // TEST // x := x / ||x|| template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::Normalize(TVec<TType, TSizeTy>& x) { const double xNorm = TLinAlg::Norm(x); if (xNorm > 0.0) { TLinAlg::MultiplyScalar(1 / xNorm, x, x); } return xNorm; } // TEST // Normalize X(:,ColId) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::NormalizeColumn(TVVec<TType, TSizeTy, ColMajor>& X, const TSizeTy& ColId) { double nX = TLinAlg::Norm(X, ColId); if (nX > 0.0) { for (TSizeTy RowN = 0; RowN < X.GetRows(); RowN++) { X.At(RowN, ColId) /= nX; } } } // TEST // Normalize the columns of X template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::NormalizeColumns(TVVec<TType, TSizeTy, ColMajor>& X) { for (TSizeTy ColN = 0; ColN < X.GetCols(); ColN++) { TLinAlg::NormalizeColumn(X, ColN); } } template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::NormalizeRows(TVVec<TType, TSizeTy, ColMajor>& X) { for (TSizeTy RowN = 0; RowN < X.GetRows(); RowN++) { TVec<TType> Row; X.GetRowPtr(RowN, Row); Normalize(Row); } } #ifdef INTEL // TEST template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::NormalizeColumns(TVVec<TType, TSizeTy, ColMajor>& X, TBool ColumnMajor) { const TSizeTy m = X.GetXDim(); const TSizeTy n = X.GetYDim(); TVVec<TType, TSizeTy, ColMajor> sqrX(m, n); vdSqr(m*n, &X(0, 0).Val, &sqrX(0, 0).Val); printf("Squaring of elements done!\n"); TVec<TType, TSizeTy> enke(m); TVec<TType, TSizeTy> sumsqr(n); TVec<TType, TSizeTy> norme(n); TLAMisc::Fill(enke, 1.0); TLinAlg::MultiplyT(sqrX, enke, sumsqr); printf("Summing elemnents done!\n"); vdInvSqrt(n, &sumsqr[0].Val, &norme[0].Val); printf("Summing and inverting elemnents done!\n"); // added code if (ColMajor) { TVVec<TType, TSizeTy, ColMajor> B; B.Gen(n, m); TLinAlg::Transpose(X, B); for (TSizeTy i = 0; i < m; i++) { vdMul(n, &norme[0].Val, &B(0, i).Val, &B(0, i).Val); } TLinAlg::Transpose(B, X); } else { for (TSizeTy i = 0; i < m; i++){ vdMul(n, &norme[0].Val, &X(i, 0).Val, &X(i, 0).Val); } } //TLAMisc::PrintTFltVV(X, "Normalizirana"); } #endif // Normalize the columns of X //TODO what to do when number //MARK template <class TType, class TSizeTy, bool ColMajor, class IndexType> void TLinAlg::NormalizeColumns(TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& X) { if (X.Val2.Len() == 0) return; EAssert(X.Val2.IsSorted(true)); //int? int Cols = X.Val2.GetMxVal() + 1; TVec<TType, TSizeTy> InvColNorms(Cols); //get the last element colN and set the number of elements TSizeTy Els = X.Val1.Len(); for (TSizeTy ElN = 0; ElN < Els; ElN++) { InvColNorms[X.Val2[ElN]] += X.Val3[ElN] * X.Val3[ElN]; } for (TSizeTy ColN = 0; ColN < Cols; ColN++) { if (InvColNorms[ColN] > 0.0) { InvColNorms[ColN] = 1.0 / TMath::Sqrt(InvColNorms[ColN]); } } for (TSizeTy ElN = 0; ElN < Els; ElN++) { X.Val3[ElN] *= InvColNorms[X.Val2[ElN]]; } } // Normalize the columns of X template<class TSizeTy> void TLinAlg::NormalizeColumns(TVec<TIntFltKdV, TSizeTy>& X) { TSizeTy Cols = X.Len(); for (TSizeTy ElN = 0; ElN < Cols; ElN++) { TLinAlg::Normalize(X[ElN]); } } // Frobenius norm of matrix A // TEST template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::FrobNorm2(const TVVec<TType, TSizeTy, ColMajor>& X) { return TLinAlg::Norm2((const_cast<TVVec<TType, TSizeTy, ColMajor> &>(X)).Get1DVec()); } template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::FrobNorm(const TVVec<TType, TSizeTy, ColMajor>& X) { return sqrt(TLinAlg::FrobNorm2(X)); } // ||x||^2 (Euclidian), x is sparse template<class TSizeTy> double TLinAlg::Norm2(const TVec<TIntFltKdV, TSizeTy>& x) { double Result = 0; for (TSizeTy i = 0; i < x.Len(); i++) { Result += TMath::Sqr(x[i].Dat); } return Result; } // ||x|| (Euclidian), x is sparse template<class TSizeTy> double TLinAlg::Norm(const TVec<TIntFltKdV, TSizeTy>& x) { return sqrt(Norm2(x)); } template<class TSizeTy> double TLinAlg::Norm(const TVec<TIntFltKdV, TSizeTy>& x, const int& ColId) { return Norm(x[ColId]); } // x := x / ||x||, x is sparse template<class TSizeTy, TSizeTy> void TLinAlg::Normalize(TVec<TIntFltKdV>& x) { double Normx = TLinAlg::Norm(x); if (Normx > 0) { TLinAlg::MultiplyScalar(1 / Normx, x, x); } } // ||X(:,ColId)||^2 (Euclidian) template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::Norm2(const TVVec<TType, TSizeTy, ColMajor>& X, int ColId) { return TLinAlg::DotProduct(X, ColId, X, ColId); } // TEST // ||X(:,ColId)|| (Euclidian) template <class TType, class TSizeTy, bool ColMajor> double TLinAlg::Norm(const TVVec<TType, TSizeTy, ColMajor>& X, int ColId) { return sqrt(TLinAlg::Norm2(X, ColId)); } // L1 norm of x (Sum[|xi|, i = 1..n]) template <class TType, class TSizeTy> double TLinAlg::NormL1(const TVec<TType, TSizeTy>& x) { double norm = 0.0; const TSizeTy Len = x.Len(); for (TSizeTy i = 0; i < Len; i++) norm += TFlt::Abs(x[i]); return norm; } // TEST // L1 norm of k*x+y (Sum[|k*xi+yi|, i = 1..n]) template <class TType, class TSizeTy> double TLinAlg::NormL1(double k, const TVec<TType, TSizeTy>& x, const TVec<TType, TSizeTy>& y) { EAssert(x.Len() == y.Len()); double norm = 0.0; const TSizeTy len = x.Len(); for (TSizeTy i = 0; i < len; i++) { norm += TFlt::Abs(k * x[i] + y[i]); } return norm; } // L1 norm of x (Sum[|xi|, i = 1..n]) double TLinAlg::NormL1(const TIntFltKdV& x) { double norm = 0.0; const int Len = x.Len(); for (int i = 0; i < Len; i++) norm += TFlt::Abs(x[i].Dat); return norm; } // TEST // x := x / ||x||_1 template <class TType, class TSizeTy> void TLinAlg::NormalizeL1(TVec<TType, TSizeTy>& x) { const double xNorm = TLinAlg::NormL1(x); if (xNorm > 0.0) { TLinAlg::MultiplyScalar(1 / xNorm, x, x); } } // x := x / ||x||_1 void TLinAlg::NormalizeL1(TIntFltKdV& x) { const double xNorm = TLinAlg::NormL1(x); if (xNorm > 0.0) { TLinAlg::MultiplyScalar(1 / xNorm, x, x); } } // TEST // Linf norm of x (Max{|xi|, i = 1..n}) template <class TType, class TSizeTy> double TLinAlg::NormLinf(const TVec<TType, TSizeTy>& x) { double norm = 0.0; const TSizeTy Len = x.Len(); for (TSizeTy i = 0; i < Len; i++) norm = TFlt::GetMx(TFlt::Abs(x[i]), norm); return norm; } // Linf norm of x (Max{|xi|, i = 1..n}) double TLinAlg::NormLinf(const TIntFltKdV& x) { double norm = 0.0; const int Len = x.Len(); for (int i = 0; i < Len; i++) norm = TFlt::GetMx(TFlt::Abs(x[i].Dat), norm); return norm; } // TEST // x := x / ||x||_inf template <class TType, class TSizeTy> void TLinAlg::NormalizeLinf(TVec<TType, TSizeTy>& x) { const double xNormLinf = TLinAlg::NormLinf(x); if (xNormLinf > 0.0) { TLinAlg::MultiplyScalar(1.0 / xNormLinf, x, x); } } // x := x / ||x||_inf, , x is sparse void TLinAlg::NormalizeLinf(TIntFltKdV& x) { const double xNormLInf = TLinAlg::NormLinf(x); if (xNormLInf > 0.0) { TLinAlg::MultiplyScalar(1.0 / xNormLInf, x, x); } } // stores the squared norm of all the columns into the output vector void TLinAlg::GetColNormV(const TFltVV& X, TFltV& ColNormV) { const int Cols = X.GetCols(); GetColNorm2V(X, ColNormV); for (int i = 0; i < Cols; i++) { ColNormV[i] = sqrt(ColNormV[i]); } } // stores the norm of all the columns into the output vector void TLinAlg::GetColNorm2V(const TFltVV& X, TFltV& ColNormV) { const int Cols = X.GetCols(); ColNormV.Gen(Cols); #pragma omp parallel for for (int ColN = 0; ColN < Cols; ColN++) { ColNormV[ColN] = Norm2(X, ColN); } } // TEST // find the index of maximum elements for a given row of X template <class TType, class TSizeTy, bool ColMajor> int TLinAlg::GetRowMaxIdx(const TVVec<TType, TSizeTy, ColMajor>& X, const TSizeTy& RowN) { TSizeTy Idx = -1; TSizeTy Cols = X.GetCols(); double MaxVal = TFlt::Mn; for (TSizeTy ColN = 0; ColN < Cols; ColN++) { double Val = X.At(RowN, ColN); if (MaxVal < Val) { MaxVal = Val; Idx = ColN; } } return Idx; } // TEST // find the index of maximum elements for a given each col of X template <class TType, class TSizeTy, bool ColMajor> int TLinAlg::GetColMaxIdx(const TVVec<TType, TSizeTy, ColMajor>& X, const int& ColN) { TSizeTy Idx = -1; TSizeTy Rows = X.GetRows(); double MaxVal = TFlt::Mn; for (TSizeTy RowN = 0; RowN < Rows; RowN++) { double Val = X.At(RowN, ColN); if (MaxVal < Val) { MaxVal = Val; Idx = RowN; } } return Idx; } // TEST // find the index of maximum elements for each row of X template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::GetRowMaxIdxV(const TVVec<TType, TSizeTy, ColMajor>& X, TVec<TInt, TSizeTy>& IdxV) { IdxV.Gen(X.GetRows()); TSizeTy Rows = X.GetRows(); for (TSizeTy RowN = 0; RowN < Rows; RowN++) { IdxV[RowN] = TLinAlg::GetRowMaxIdx(X, RowN); } } // find the index of maximum elements for each col of X template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::GetColMaxIdxV(const TVVec<TType, TSizeTy, ColMajor>& X, TVec<TInt, TSizeTy>& IdxV) { IdxV.Gen(X.GetCols()); TSizeTy Cols = X.GetCols(); for (TSizeTy ColN = 0; ColN < Cols; ColN++) { IdxV[ColN] = TLinAlg::GetColMaxIdx(X, ColN); } } //x := k * x // TEST //x := k * x template <class TType, class TSizeTy> void TLinAlg::MultiplyScalar(const double& k, TVec<TType, TSizeTy>& x) { TSizeTy Len = x.Len(); for (TSizeTy i = 0; i < Len; i++) x[i] = k * x[i]; } // find the index of maximum elements for a given each col of X int TLinAlg::GetColMinIdx(const TFltVV& X, const int& ColN) { const int Rows = X.GetRows(); double MinVal = TFlt::Mx; int MinIdx = -1; for (int RowN = 0; RowN < Rows; RowN++) { double Val = X(RowN, ColN); if (Val < MinVal) { MinVal = Val; MinIdx = RowN; } } return MinIdx; } // find the index of maximum elements for each col of X void TLinAlg::GetColMinIdxV(const TFltVV& X, TIntV& IdxV) { int Cols = X.GetCols(); if (IdxV.Empty()) { IdxV.Gen(Cols); } EAssert(IdxV.Len() == Cols); #pragma omp parallel for for (int ColN = 0; ColN < Cols; ColN++) { IdxV[ColN] = GetColMinIdx(X, ColN); } } //template <class TVal> TVal TLinAlg::GetColMin(const TVVec<TVal>& X, const int& ColN); //template <class TVal> void TLinAlg::GetColMinV(const TVVec<TVal>& X, TVec<TVal>& ValV); // TEST // y := k * x template <class TType, class TSizeTy> void TLinAlg::MultiplyScalar(const double& k, const TVec<TType, TSizeTy>& x, TVec<TType, TSizeTy>& y) { EAssert(x.Len() == y.Len()); TSizeTy Len = x.Len(); for (TSizeTy i = 0; i < Len; i++) y[i] = k * x[i]; } // y := k * x void TLinAlg::MultiplyScalar(const double& k, const TIntFltKdV& x, TIntFltKdV& y) { EAssert(x.Len() == y.Len()); int Len = x.Len(); for (int i = 0; i < Len; i++) { y[i].Key = x[i].Key; y[i].Dat = k * x[i].Dat; } } // TEST // Y := k * X template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::MultiplyScalar(const double& k, const TVVec<TType, TSizeTy, ColMajor>& X, TVVec<TType, TSizeTy, ColMajor>& Y) { EAssert(X.GetRows() == Y.GetRows() && X.GetCols() == Y.GetCols()); const TSizeTy Rows = X.GetRows(); const TSizeTy Cols = X.GetCols(); for (TSizeTy i = 0; i < Rows; i++) { for (TSizeTy j = 0; j < Cols; j++) { Y(i, j) = k*X(i, j); } } } // Y := k * X template <class TSizeTy> void TLinAlg::MultiplyScalar(const double& k, const TVec<TIntFltKdV, TSizeTy>& X, TVec<TIntFltKdV, TSizeTy>& Y) { // sparse column matrix Y = X; TSizeTy Cols = X.Len(); for (TSizeTy ColN = 0; ColN < Cols; ColN++) { TSizeTy Els = X[ColN].Len(); for (int ElN = 0; ElN < Els; ElN++) { Y[ColN][ElN].Dat = k * X[ColN][ElN].Dat; } } } // y := A * x template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVec<TType, TSizeTy>& x, TVec<TType, TSizeTy>& y) { if (y.Empty()) { y.Gen(A.GetRows()); } EAssert(A.GetCols() == x.Len() && A.GetRows() == y.Len()); #ifdef BLAS TLinAlg::Multiply(A, x, y, TLinAlgBlasTranspose::NOTRANS, 1.0, 0.0); #else int n = A.GetRows(), m = A.GetCols(); for (int i = 0; i < n; i++) { y[i] = 0.0; for (int j = 0; j < m; j++) { y[i] += A(i, j) * x[j]; } } #endif } // TEST // C(:, ColId) := A * x template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVec<TType, TSizeTy>& x, TVVec<TType, TSizeTy, ColMajor>& C, TSizeTy ColId) { EAssert(A.GetCols() == x.Len() && A.GetRows() == C.GetRows()); TSizeTy n = A.GetRows(), m = A.GetCols(); for (TSizeTy i = 0; i < n; i++) { C(i, ColId) = 0.0; for (TSizeTy j = 0; j < m; j++) C(i, ColId) += A(i, j) * x[j]; } } // TEST // y := A * B(:, ColId) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, int ColId, TVec<TType, TSizeTy>& y) { EAssert(A.GetCols() == B.GetRows() && A.GetRows() == y.Len()); TSizeTy n = A.GetRows(), m = A.GetCols(); for (TSizeTy i = 0; i < n; i++) { y[i] = 0.0; for (TSizeTy j = 0; j < m; j++) y[i] += A(i, j) * B(j, ColId); } } // TEST // C(:, ColIdC) := A * B(:, ColIdB) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, int ColIdB, TVVec<TType, TSizeTy, ColMajor>& C, int ColIdC) { EAssert(A.GetCols() == B.GetRows() && A.GetRows() == C.GetRows()); TSizeTy n = A.GetRows(), m = A.GetCols(); for (TSizeTy i = 0; i < n; i++) { C(i, ColIdC) = 0.0; for (TSizeTy j = 0; j < m; j++) C(i, ColIdC) += A(i, j) * B(j, ColIdB); } } //LAPACKE stuff #ifdef LAPACKE // Tested in other function //A is rewritten in place with orthogonal matrix Q template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::QRbasis(TVVec<TType, TSizeTy, ColMajor>& A) { TSizeTy m = A.GetRows(); TSizeTy n = A.GetCols(); TSizeTy k = A.GetCols(); TSizeTy lda = ColMajor ? m : n; int Matrix_Layout = ColMajor ? LAPACK_COL_MAJOR : LAPACK_ROW_MAJOR; TVec<TType, TSizeTy> tau; tau.Gen(MAX(1, MIN(m, n))); LAPACKE_dgeqrf(Matrix_Layout, m, n, &A(0, 0).Val, lda, &tau[0].Val); LAPACKE_dorgqr(Matrix_Layout, m, n, k, &A(0, 0).Val, lda, &tau[0].Val); } // TEST template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::QRbasis(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& Q) { Q = A; TLinAlg::QRbasis(Q); } // Tested in other function //A is rewritten in place with orthogonal matrix Q (column pivoting to improve stability) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::QRcolpbasis(TVVec<TType, TSizeTy, ColMajor>& A) { TSizeTy m = A.GetRows(); TSizeTy n = A.GetCols(); TSizeTy k = A.GetCols(); TSizeTy lda = ColMajor ? m : n; TSizeTy Matrix_Layout = ColMajor ? LAPACK_COL_MAJOR : LAPACK_ROW_MAJOR; TVec<TType, TSizeTy> tau(MAX(1, MIN(m, n))); TVec<TInt, TSizeTy> jvpt(MAX(1, n)); LAPACKE_dgeqp3(Matrix_Layout, m, n, &A(0, 0).Val, lda, &jvpt[0].Val, &tau[0].Val); LAPACKE_dorgqr(Matrix_Layout, m, n, k, &A(0, 0).Val, lda, &tau[0].Val); } // TEST template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::QRcolpbasis(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& Q) { Q = A; TLinAlg::QRcolpbasis(Q); } // TEST //S S option ensures that A is not modified template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::thinSVD(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& U, TVec<TType, TSizeTy>& S, TVVec<TType, TSizeTy, ColMajor>& VT) { TSizeTy m = A.GetRows(); TSizeTy n = A.GetCols(); TSizeTy thin_dim = MIN(m, n); S.Gen(thin_dim); U.Gen(m, thin_dim); VT.Gen(thin_dim, n); int lda = ColMajor ? m : n; int ldu = ColMajor ? m : thin_dim; int ldvt = ColMajor ? thin_dim : n; TVec<TType, TSizeTy> superb(MAX(1, MIN(m, n))); int opt = ColMajor ? LAPACK_COL_MAJOR : LAPACK_ROW_MAJOR; /*int lda, ldu, ldvt; if (opt == LAPACK_ROW_MAJOR){ lda = n; ldu = thin_dim; ldvt = n; } else{ lda = m; ldu = m; ldvt = thin_dim; }*/ LAPACKE_dgesvd(opt, 'S', 'S', m, n, const_cast<double *>(&A(0, 0).Val), lda, &S[0].Val, &U(0, 0).Val, ldu, &VT(0, 0).Val, ldvt, &superb[0].Val); } #endif //int TLinAlg::ComputeThinSVD(const TMatrix& X, const int& k, TFltVV& U, TFltV& s, TFltVV& V, const int Iters = 2, const double Tol = 1e-6); //Full matrix times sparse vector //No need to reserve anything outside, functions currently take care of memory managment for safety /*template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(TFltVV& ProjMat, TPair<TIntV, TFltV> &, TFltVV& result) { }; template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TFltVV& ProjMat, const TPair<TIntV, TFltV> &, TFltVV& result) { };*/ //////////////////////////////////////////////////////////////////// // Andrej says: // http://software.intel.com/en-us/node/468598#86F42CD2-6A3C-4E1F-B686-8690FCC03C75 //call mkl_dcoomm(transa, m, n, k, alpha, matdescra, val, rowind, colind, nnz, b, ldb, beta, c, ldc) //if transa=='T' op(A) = A' op(m, k) = m else transa == 'N' op(m, k) = k //A is sparse, B and C are full //m Number of rows of the matrix A. n Number of columns of the matrix C. k Number of columns of the matrix A. //A m x k, B op(m, k) x n, C op(m, k) x n //C := alpha*op(A)*B + beta*C // matdescra[6] ={'G', 'G', 'N', 'C', 'Q', 'Q'}; //General, General, Nonunit diagonal, Zero Based indexing #ifdef INTEL // INTEL //Be careful C should be of the proper size! if not populated (works only for rowmajor!) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::MultiplySF(const TTriple<TVec<TNum<TSizeTy>, TSizeTy>, TVec<TNum<TSizeTy>, TSizeTy>, TVec<TType, TSizeTy>>& A, const TVVec<TType, TSizeTy, false>& B, TVVec<TType, TSizeTy, ColMajor>& C, const TStr& transa, const int& format){ //B is row_major TSizeTy m, n, k, ldb, ldc; //ldb = ColMajor ? B.GetRows() : B.GetCols(); //ldc = ColMajor ? C.GetRows() : C.GetCols(); ldb = B.GetCols(); ldc = C.GetCols(); n = C.GetCols(); if (transa == "N"){ m = C.GetRows(); k = B.GetRows(); } else{ k = C.GetRows(); m = B.GetRows(); } double alpha = 1; double beta = 0; char matdescra[6] = { 'G', 'G', 'N', 'C', 'Q', 'Q' }; TSizeTy nnz = A.Val3.Len(); if (format == 0){ MKL_DCOOMM(const_cast<char *>(transa.CStr()), &m, &n, &k, &alpha, matdescra, const_cast<double *>(&A.Val3[0].Val), const_cast<TSizeTy *>(&A.Val1[0].Val), const_cast<TSizeTy *>(&A.Val2[0].Val), &nnz, const_cast<double *>(&B(0, 0).Val), &ldb, &beta, const_cast<double *>(&C(0, 0).Val), &ldc); } else{ //call mkl_dcsrmm(transa, m, n, k, alpha, matdescra, val, indx, pntrb, pntre, b, ldb, beta, c, ldc) printf("Max row %d, max column %d\n", A.Val1.Len() - 1, A.Val2.Len()); mkl_dcsrmm(const_cast<char *>(transa.CStr()), &m, &n, &k, &alpha, matdescra, const_cast<double *>(&A.Val3[0].Val), const_cast<TSizeTy *>(&A.Val2[0].Val), const_cast<TSizeTy *>(&A.Val1[0].Val), const_cast<TSizeTy *>(&A.Val1[1].Val), const_cast<double *>(&B(0, 0).Val), &ldb, &beta, const_cast<double *>(&C(0, 0).Val), &ldc); } } // TEST //B will not be needed anymore (works only for rowmajor!) //TODO to much hacking template <class IndexType, class TType, class TSizeTy, bool ColMajor> void TLinAlg::MultiplyFS(TVVec<TType, TSizeTy, ColMajor>& B, const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& A, TVVec<TType, TSizeTy, ColMajor>& C){ C.SwitchDim(); TTmStopWatch time; time.Start(); B.Transpose(); time.Stop("In place transpose of B costs: "); time.Start(); MultiplySF(A, B, C, TStr("T"));//Heavy hacking time.Stop("Full times sparse multi costs: "); time.Start(); B.Transpose(); time.Stop("In place transpose of B costs: "); time.Start(); C.Transpose(); time.Stop("In place transpose of C costs: "); } #endif // y := A * x template <class IndexType, class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TPair<TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& x, TVec<TType, TSizeTy>& y) { // Assumptions on x EAssert(x.Val1.Len() == x.Val2.Len()); // Dimensions must match EAssert(A.GetRows() >= (x.Val1.Len() == 0 ? 0 : x.Val1[x.Val1.GetMxValN()] + 1) && A.GetCols() == y.Len()); for (TSizeTy RowN = 0; RowN < A.GetRows(); RowN++) { y[RowN] = 0.0; for (TSizeTy ElN = 0; ElN < x.Val1.Len(); ElN++) { y[RowN] += A.At(RowN, x.Val1[ElN]) * x.Val2[ElN]; } } } //y := x' * A ... row data!! template <class IndexType, class TType, class TSizeTy, bool ColMajor> void TLinAlg::MultiplyT(const TPair<TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& x, const TVVec<TType, TSizeTy, ColMajor>& A, TVec<TType, TSizeTy>& y) { // Assumptions on x EAssert(x.Val1.Len() == x.Val2.Len()); // Dimensions must match EAssert(A.GetCols() >= (x.Val1.Len() == 0 ? 0 : x.Val1[x.Val1.GetMxValN()] + 1) && A.GetRows() == y.Len()); TLAMisc::FillZero(y); int nnz = x.Val1.Len(); for (TSizeTy i = 0; i < nnz; i++) { TVec<TType, TSizeTy> row; (const_cast<TVVec<TType, TSizeTy, ColMajor> &>(A)).GetRowPtr(x.Val1[i], row); //printf("vrstic %d, stolpcev %d\n", A.GetRows(), A.GetCols()); //printf("Row len %d\n", row.Len()); //printf("i je %d, vrstica je %d\n", i, x.Val1[i]); //TLinAlg::LinCombInPlace(x.Val2[i], row, 0.0, y); #ifdef BLAS //y = k * x + y //cblas_daxpy(row.Len(), x.Val2[i].Val, &row[0].Val, 1, &y[0].Val, 1); //cblas_daxpy(x.Len(), k_, (Loc *)&x[0].Val, 1, (Loc *) &y[0].Val, 1); AddVec(x.Val2[i].Val, row, y); #else TLinAlg::LinCombInPlace(x.Val2[i].Val, row, 1.0, y); #endif //printf("Lincomb does not fail\n"); } } // TEST Move to BLAS // y := A' * x template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::MultiplyT(const TVVec<TNum<TType>, TSizeTy, ColMajor>& A, const TVec<TNum<TType>, TSizeTy>& x, TVec<TNum<TType>, TSizeTy>& y) { if (y.Empty()) y.Gen(A.GetCols()); EAssert(A.GetRows() == x.Len() && A.GetCols() == y.Len()); TSizeTy n = A.GetCols(), m = A.GetRows(); for (TSizeTy i = 0; i < n; i++) { y[i] = 0.0; for (TSizeTy j = 0; j < m; j++) y[i] += A(j, i) * x[j]; } } #ifdef BLAS typedef enum { NOTRANS = 0, TRANS = 1 } TLinAlgBlasTranspose; // TEST // C = op(A) * op(B) template <class TType, class TSizeTy, bool ColMajor> inline void TLinAlg::Multiply(const TVVec<TNum<TType>, TSizeTy, ColMajor>& A, const TVVec<TNum<TType>, TSizeTy, ColMajor>& B, TVVec<TNum<TType>, TSizeTy, ColMajor>& C, const int& BlasTransposeFlagA, const int& BlasTransposeFlagB) { //C := alpha*op(A)*op(B) + beta*C, //where: //op(X) is one of op(X) = X, or op(X) = XT, or op(X) = XH, //alpha and beta are scalars, //A, B and C are matrices: //op(A) is an m-by-k matrix, //op(B) is a k-by-n matrix, //C is an m-by-n matrix. TSizeTy m, n, k, lda, ldb, ldc; if (BlasTransposeFlagA == TLinAlg::TLinAlgBlasTranspose::TRANS) { m = A.GetCols(); k = A.GetRows(); lda = ColMajor ? k : m; } else { m = A.GetRows(); k = A.GetCols(); lda = ColMajor ? m : k; } if (BlasTransposeFlagB == TLinAlg::TLinAlgBlasTranspose::TRANS) { EAssert(k == B.GetCols()); n = B.GetRows(); ldb = ColMajor ? n : k; } else { EAssert(k == B.GetRows()); n = B.GetCols(); ldb = ColMajor ? k : n; } EAssert(m == C.GetRows() && n == C.GetCols()); // simplified interface ldc = ColMajor ? m : n; #ifdef BLAS //Standard CBLAS interface CBLAS_TRANSPOSE BlasTransA = (BlasTransposeFlagA == TLinAlgBlasTranspose::TRANS) ? CblasTrans : CblasNoTrans; CBLAS_TRANSPOSE BlasTransB = (BlasTransposeFlagB == TLinAlgBlasTranspose::TRANS) ? CblasTrans : CblasNoTrans; CBLAS_ORDER Matrix_Layout = ColMajor ? CblasColMajor : CblasRowMajor; if (TypeCheck::is_double<TType>::value == true){ typedef double Loc; double alpha = 1.0, beta = 0.0; cblas_dgemm(Matrix_Layout, BlasTransA, BlasTransB, m, n, k, alpha, (Loc *)&A(0, 0).Val, lda, (Loc *)&B(0, 0).Val, ldb, beta, (Loc *)&C(0, 0).Val, ldc); } else if (TypeCheck::is_float<TType>::value == true){ typedef float Loc; float alpha = 1.0f, beta = 0.0f; cblas_sgemm(Matrix_Layout, BlasTransA, BlasTransB, m, n, k, alpha, (Loc *)&A(0, 0).Val, lda, (Loc *)&B(0, 0).Val, ldb, beta, (Loc *)&C(0, 0).Val, ldc); } else if (TypeCheck::is_complex_double<TType>::value == true){ typedef double Loc; std::complex<double> alpha(1.0); std::complex<double> beta(0.0); cblas_zgemm(Matrix_Layout, BlasTransA, BlasTransB, m, n, k, (const Loc *)&alpha, (const Loc *)&A(0, 0).Val, lda, (const Loc *)&B(0, 0).Val, ldb, (const Loc *)&beta, (Loc *)&C(0, 0).Val, ldc); } else if (TypeCheck::is_complex_float<TType>::value == true){ typedef float Loc; std::complex<float> alpha(1.0f); std::complex<float> beta(0.0f); cblas_cgemm(Matrix_Layout, BlasTransA, BlasTransB, m, n, k, (const Loc *)&alpha, (const Loc *)&A(0, 0).Val, lda, (const Loc *)&B(0, 0).Val, ldb, (const Loc *)&beta, (Loc *)&C(0, 0).Val, ldc); } #else //Fortran 77 style interface, all values must be passed by reference! TStr TransposeFlagA = "N"; TStr TransposeFlagB = "N"; if (BlasTransposeFlagA){ TransposeFlagA = "T"; /*lda = k;*/ } if (BlasTransposeFlagB){ TransposeFlagB = "T"; /*ldb = n;*/ } #ifdef AMD DGEMM(TransposeFlagA.CStr(), TransposeFlagB.CStr(), &m, &n, &k, &alpha, &A(0, 0).Val, &lda, &B(0, 0).Val, &ldb, &beta, &C(0, 0).Val, &ldc, TransposeFlagA.Len(), TransposeFlagB.Len()); #else dgemm(TransposeFlagA.CStr(), TransposeFlagB.CStr(), &m, &n, &k, &alpha, &A(0, 0).Val, &lda, &B(0, 0).Val, &ldb, &beta, &C(0, 0).Val, &ldc); #endif #endif } #endif #ifdef BLAS // TEST // y := alpha*op(A)*x + beta*y, where op(A) = A -- N, op(A) = A' -- T, op(A) = conj(A') -- C (only for complex) //Andrej ToDo In the future replace TType with TNum<type> and change double to type template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TVVec<TNum<TType>, TSizeTy, ColMajor>& A, const TVec<TNum<TType>, TSizeTy>& x, TVec<TNum<TType>, TSizeTy>& y, const int& BlasTransposeFlagA, TType alpha, TType beta) { TSizeTy m = A.GetRows(); TSizeTy n = A.GetCols(); //Can we multiply and store in y? if (BlasTransposeFlagA) {//A'*x n*m x m -> n EAssertR(x.Len() == m, "TLinAlg::Multiply: Invalid dimension of input vector!"); if (y.Reserved() != n) { // TODO should I do this here?? Meybe if the length is > n it would also be OK?? y.Gen(n, n); } } else{//A*x m x n * n -> m EAssertR(x.Len() == n, "TLinAlg::Multiply: Invalid dimension of input vector!"); if (y.Reserved() != m) { // TODO should I do this here?? Meybe if the length is > m it would also be OK?? y.Gen(m, m); } } TSizeTy lda = ColMajor ? m : n; TSizeTy incx = /*ColMajor ? x.Len() :*/ 1; TSizeTy incy = /*ColMajor ? y.Len() :*/ 1; CBLAS_ORDER Matrix_Layout = ColMajor ? CblasColMajor : CblasRowMajor; #ifdef BLAS //Standard CBLAS interface CBLAS_TRANSPOSE BlasTransA = BlasTransposeFlagA ? CblasTrans : CblasNoTrans; /*if (BlasTransposeFlagA){ BlasTransA = CblasTrans; }*/ if (TypeCheck::is_double<TType>::value == true){ typedef double Loc; double alpha_ = alpha; double beta_ = beta; cblas_dgemv(Matrix_Layout, BlasTransA, m, n, alpha_, (Loc *)&A(0, 0).Val, lda, (Loc *)&x[0].Val, incx, beta_, (Loc *)&y[0].Val, incy); } else if (TypeCheck::is_float<TType>::value == true){ typedef float Loc; float alpha_ = (float)alpha; float beta_ = (float)beta; cblas_sgemv(Matrix_Layout, BlasTransA, m, n, alpha_, (Loc *)&A(0, 0).Val, lda, (Loc *)&x[0].Val, incx, beta_, (Loc *)&y[0].Val, incy); } else if (TypeCheck::is_complex_double<TType>::value == true){ typedef double Loc; std::complex<double> alpha_(alpha); std::complex<double> beta_(beta); cblas_zgemv(Matrix_Layout, BlasTransA, m, n, (const Loc *)&alpha_, (const Loc *)&A(0, 0).Val, lda, (const Loc *)&x[0].Val, incx, (const Loc *)&beta_, (Loc *)&y[0].Val, incy); } else if (TypeCheck::is_complex_float<TType>::value == true){ typedef float Loc; std::complex<float> alpha_((float)alpha); std::complex<double> beta_((float)beta); cblas_cgemv(Matrix_Layout, BlasTransA, m, n, (const Loc *)&alpha_, (const Loc *)&A(0, 0).Val, lda, (const Loc *)&x[0].Val, incx, (const Loc *)&beta_, (Loc *)&y[0].Val, incy); } #else //Fortran 77 style interface, all values must be passed by reference! TStr TransposeFlag = "N"; if (BlasTransposeFlagA){ TransposeFlag = 'T'; } #ifdef AMD DGEMV(TransposeFlag.CStr(), &m, &n, &alpha, &A(0, 0).Val, &lda, &x[0].Val, &incx, &beta, &y[0].Val, &incy, TransposeFlag.Len()); //DGEMV(char *trans, int *m, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy, int trans_len); #else dgemv(TransposeFlag.CStr(), &m, &n, &alpha, &A(0, 0).Val, &lda, &x[0].Val, &incx, &beta, &y[0].Val, &incy); #endif #endif } #endif // TEST // C = A * B template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, TVVec<TType, TSizeTy, ColMajor>& C) { EAssert(A.GetRows() == C.GetRows() && B.GetCols() == C.GetCols() && A.GetCols() == B.GetRows()); #ifdef BLAS TLinAlg::Multiply(A, B, C, TLinAlgBlasTranspose::NOTRANS, TLinAlgBlasTranspose::NOTRANS); #else TSizeTy RowsA = A.GetRows(); TSizeTy ColsA = A.GetCols(); TSizeTy ColsB = B.GetCols(); C.PutAll(0.0); for (TSizeTy RowN = 0; RowN < RowsA; RowN++) { for (TSizeTy ColAN = 0; ColAN < ColsA; ColAN++) { double Weight = A(RowN, ColAN); for (TSizeTy ColBN = 0; ColBN < ColsB; ColBN++) { C(RowN, ColBN) += Weight * B(ColAN, ColBN); } } } #endif } // TEST // C = A' * B template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::MultiplyT(const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, TVVec<TType, TSizeTy, ColMajor>& C) { if (C.Empty()) { C.Gen(A.GetCols(), B.GetCols()); } EAssert(A.GetCols() == C.GetRows() && B.GetCols() == C.GetCols() && A.GetRows() == B.GetRows()); #ifdef BLAS TLinAlg::Multiply(A, B, C, TLinAlgBlasTranspose::TRANS, TLinAlgBlasTranspose::NOTRANS); #else TSizeTy n = C.GetRows(), m = C.GetCols(), l = A.GetRows(); double sum; for (TSizeTy i = 0; i < n; i++) { for (TSizeTy j = 0; j < m; j++) { sum = 0.0; for (TSizeTy k = 0; k < l; k++) sum += A(k, i)*B(k, j); C(i, j) = sum; } } #endif } ////////////////// // DENSE-SPARSE, SPARSE-DENSE // TEST // C := A * B template <class IndexType, class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TVVec<TType, TSizeTy, ColMajor>& A, const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& B, TVVec<TType, TSizeTy, ColMajor>& C){ // B well defined EAssert(B.Val1.Len() == B.Val2.Len() && B.Val2.Len() == B.Val3.Len()); // Dimensions must match C.PutAll(0.0); if (B.Val1.Len() == 0) { return; } #ifdef INTELS TLinAlg::MultiplyFS(const_cast<TVVec<TType, TSizeTy, ColMajor> &>(A), B, C); #else TSizeTy Nonzeros = B.Val1.Len(); IndexType MaxRowN = B.Val1[B.Val1.GetMxValN()]; IndexType MaxColN = B.Val2[B.Val2.GetMxValN()]; EAssert(A.GetRows() == C.GetRows() && (MaxColN + 1) <= C.GetCols() && (MaxRowN + 1) <= A.GetCols()); for (TSizeTy RowN = 0; RowN < A.GetRows(); RowN++) { for (TSizeTy ElN = 0; ElN < Nonzeros; ElN++) { C.At(RowN, B.Val2[ElN]) += A.At(RowN, B.Val1[ElN]) * B.Val3[ElN]; } } #endif } // TEST // C:= A' * B template <class IndexType, class TType, class TSizeTy, bool ColMajor> void TLinAlg::MultiplyT(const TVVec<TType, TSizeTy, ColMajor>& A, const TTriple<TVec<IndexType, TSizeTy>, TVec<IndexType, TSizeTy>, TVec<TType, TSizeTy>>& B, TVVec<TType, TSizeTy, ColMajor>& C) { // B well defined EAssert(B.Val1.Len() == B.Val2.Len() && B.Val2.Len() == B.Val3.Len()); // Dimensions must match C.PutAll(0.0); if (B.Val1.Len() == 0) { return; } TSizeTy Nonzeros = B.Val1.Len(); IndexType MaxRowN = B.Val1[B.Val1.GetMxValN()]; IndexType MaxColN = B.Val2[B.Val2.GetMxValN()]; EAssert(A.GetCols() == C.GetRows() && (MaxColN + 1) <= C.GetCols() && (MaxRowN + 1) <= A.GetRows()); for (TSizeTy RowN = 0; RowN < A.GetCols(); RowN++) { for (TSizeTy ElN = 0; ElN < Nonzeros; ElN++) { C.At(RowN, B.Val2[ElN]) += A.At(B.Val1[ElN], RowN) * B.Val3[ElN]; } } } // TEST // C := A * B //#if !defined(INTEL) || defined(INDEX_64) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Multiply(const TTriple<TVec<TNum<TSizeTy>, TSizeTy>, TVec<TNum<TSizeTy>, TSizeTy>, TVec<TType, TSizeTy>>& A, const TVVec<TType, TSizeTy, ColMajor>& B, TVVec<TType, TSizeTy, ColMajor>& C) { // A well defined EAssert(A.Val1.Len() == A.Val2.Len() && A.Val2.Len() == A.Val3.Len()); // Dimensions must match C.PutAll(0.0); if (A.Val1.Len() == 0) { return; } #if !defined(INTEL) || defined(INDEX_64) TSizeTy Nonzeros = A.Val1.Len(); TSizeTy MaxRowN = A.Val1[A.Val1.GetMxValN()]; TSizeTy MaxColN = A.Val2[A.Val2.GetMxValN()]; EAssert(B.GetCols() == C.GetCols() && (MaxRowN + 1) <= C.GetRows() && (MaxColN + 1) <= B.GetRows()); for (TSizeTy ColN = 0; ColN < B.GetCols(); ColN++) { for (TSizeTy ElN = 0; ElN < Nonzeros; ElN++) { C.At(A.Val1[ElN], ColN) += A.Val3[ElN] * B.At(A.Val2[ElN], ColN); } } #else TLinAlg::MultiplySF(A, B, C); #endif } // TEST // C:= A' * B template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::MultiplyT(const TTriple<TVec<TNum<TSizeTy>, TSizeTy>, TVec<TNum<TSizeTy>, TSizeTy>, TVec<TType, TSizeTy>>& A, const TVVec<TType, TSizeTy, ColMajor>& B, TVVec<TType, TSizeTy, ColMajor>& C) { // B well defined EAssert(A.Val1.Len() == A.Val2.Len() && A.Val2.Len() == A.Val3.Len()); // Dimensions must match C.PutAll(0.0); if (A.Val1.Len() == 0) { return; } #if !defined(INTEL) || defined(INDEX_64) TSizeTy Nonzeros = A.Val1.Len(); TSizeTy MaxRowN = A.Val1[A.Val1.GetMxValN()]; TSizeTy MaxColN = A.Val2[A.Val2.GetMxValN()]; EAssert(B.GetCols() == C.GetCols() && (MaxColN + 1) <= C.GetRows() && (MaxRowN + 1) <= B.GetRows()); for (TSizeTy ColN = 0; ColN < B.GetCols(); ColN++) { for (TSizeTy ElN = 0; ElN < Nonzeros; ElN++) { C.At(A.Val2[ElN], ColN) += A.Val3[ElN] * B.At(A.Val1[ElN], ColN); } } #else TLinAlg::MultiplySF(A, B, C, "T"); #endif } // DENSE-SPARSECOLMAT, SPARSECOLMAT-DENSE // C := A * B // DENSE-SPARSECOLMAT, SPARSECOLMAT-DENSE // C := A * B //Andrej Urgent //TODO template --- indextype TIntFltKdV ... TInt64 void TLinAlg::Multiply(const TFltVV& A, const TVec<TIntFltKdV>& B, TFltVV& C) { // B = sparse column matrix if (C.Empty()) { C.Gen(A.GetRows(), B.Len()); } else { EAssert(A.GetRows() == C.GetRows() && B.Len() == C.GetCols()); } EAssert(TLAMisc::GetMaxDimIdx(B) < A.GetCols()); int Cols = B.Len(); int Rows = A.GetRows(); C.PutAll(0.0); for (int RowN = 0; RowN < Rows; RowN++) { for (int ColN = 0; ColN < Cols; ColN++) { int Els = B[ColN].Len(); for (int ElN = 0; ElN < Els; ElN++) { C.At(RowN, ColN) += A.At(RowN, B[ColN][ElN].Key) * B[ColN][ElN].Dat; } } } } // C:= A' * B template <class IndexType, class TType, class TSizeTy, bool ColMajor> void TLinAlg::MultiplyT(const TVVec<TType, TSizeTy, ColMajor>& A, const TVec<TVec<TKeyDat<IndexType, TType>, TSizeTy>, TSizeTy>& B, TVVec<TType, TSizeTy, ColMajor>& C) { // C = A' B = (B' A)' #ifdef INTELBETA TTriple<TVec<IndexType, TSizeTy>, TVec<TInt, TSizeTy>, TVec<TType, TSizeTy>> BB; TLinAlg::Convert(B, BB); // convert the matrix to a coordinate form TVVec<TType, TSizeTy, ColMajor> CC(B.Len(), A.GetCols()); TLinAlg::MultiplyT(BB, A, CC); if (C.Empty()) { C.Gen(A.GetCols(), B.Len()); } else { EAssert(C.GetRows() == A.GetCols() && C.GetCols() == B.Len()); } TLinAlg::Transpose(CC, C); #else // B = sparse column matrix if (C.Empty()) { C.Gen(A.GetCols(), B.Len()); } else { EAssert(A.GetCols() == C.GetRows() && B.Len() == C.GetCols()); } EAssert(TLAMisc::GetMaxDimIdx(B) < A.GetRows()); int Cols = B.Len(); int Rows = A.GetCols(); C.PutAll(0.0); for (int RowN = 0; RowN < Rows; RowN++) { for (int ColN = 0; ColN < Cols; ColN++) { int Els = B[ColN].Len(); for (int ElN = 0; ElN < Els; ElN++) { C.At(RowN, ColN) += A.At(B[ColN][ElN].Key, RowN) * B[ColN][ElN].Dat; } } } #endif } // C := A * B //Andrej Urgent //TODO template --- indextype TIntFltKdV ... TInt64 void TLinAlg::Multiply(const TVec<TIntFltKdV>& A, const TFltVV& B, TFltVV& C, const int RowsA) { // A = sparse column matrix EAssert(A.Len() == B.GetRows()); int Rows = RowsA; int ColsB = B.GetCols(); if (RowsA == -1) { Rows = TLAMisc::GetMaxDimIdx(A) + 1; } else { EAssert(TLAMisc::GetMaxDimIdx(A) + 1 <= RowsA); } if (C.Empty()) { C.Gen(Rows, ColsB); } int RowsB = B.GetRows(); C.PutAll(0.0); for (int ColN = 0; ColN < ColsB; ColN++) { for (int RowN = 0; RowN < RowsB; RowN++) { int Els = A[RowN].Len(); for (int ElN = 0; ElN < Els; ElN++) { C.At(A[RowN][ElN].Key, ColN) += A[RowN][ElN].Dat * B.At(RowN, ColN); } } } } // C:= A' * B //Andrej Urgent //TODO template --- indextype TIntFltKdV ... TInt64 TFlt void TLinAlg::MultiplyT(const TVec<TIntFltKdV>& A, const TFltVV& B, TFltVV& C) { // A = sparse column matrix EAssert(TLAMisc::GetMaxDimIdx(A) + 1 <= B.GetRows()); int ColsB = B.GetCols(); //int RowsB = B.GetRows(); int ColsA = A.Len(); if (C.Empty()) { C.Gen(ColsA, ColsB); } else { EAssert(C.GetRows() == ColsA && C.GetCols() == ColsB); } C.PutAll(0.0); for (int RowN = 0; RowN < ColsA; RowN++) { for (int ColN = 0; ColN < ColsB; ColN++) { int Els = A[RowN].Len(); for (int ElN = 0; ElN < Els; ElN++) { C.At(RowN, ColN) += A[RowN][ElN].Dat * B.At(A[RowN][ElN].Key, ColN); } } } } // SPARSECOLMAT-SPARSECOLMAT // C := A * B //Andrej Urgent //TODO template --- indextype TIntFltKdV ... TInt64 //TLAMisc //GetMaxDimIdx void TLinAlg::Multiply(const TVec<TIntFltKdV>& A, const TVec<TIntFltKdV>& B, TFltVV& C, const int RowsA) { //// A,B = sparse column matrix //EAssert(A.Len() == B.GetRows()); int Rows = RowsA; int ColsB = B.Len(); if (RowsA == -1) { Rows = TLAMisc::GetMaxDimIdx(A) + 1; } else { EAssert(TLAMisc::GetMaxDimIdx(A) + 1 <= RowsA); } if (C.Empty()) { C.Gen(Rows, ColsB); } EAssert(TLAMisc::GetMaxDimIdx(B) + 1 <= A.Len()); C.PutAll(0.0); for (int ColN = 0; ColN < ColsB; ColN++) { int ElsB = B[ColN].Len(); for (int ElBN = 0; ElBN < ElsB; ElBN++) { int IdxB = B[ColN][ElBN].Key; double ValB = B[ColN][ElBN].Dat; int ElsA = A[IdxB].Len(); for (int ElAN = 0; ElAN < ElsA; ElAN++) { int IdxA = A[IdxB][ElAN].Key; double ValA = A[IdxB][ElAN].Dat; C.At(IdxA, ColN) += ValA * ValB; } } } } // C:= A' * B //Andrej Urgent //TODO template --- indextype TIntFltKdV ... TInt64 void TLinAlg::MultiplyT(const TVec<TIntFltKdV>& A, const TVec<TIntFltKdV>& B, TFltVV& C) { //// A, B = sparse column matrix int ColsA = A.Len(); int ColsB = B.Len(); if (C.Empty()) { C.Gen(ColsA, ColsB); } else { EAssert(ColsA == C.GetRows() && ColsB == C.GetCols()); } for (int RowN = 0; RowN < ColsA; RowN++) { for (int ColN = 0; ColN < ColsB; ColN++) { C.At(RowN, ColN) = TLinAlg::DotProduct(A[RowN], B[ColN]); } } } //#ifdef INTEL // void TLinAlg::Multiply(const TFltVV & ProjMat, const TPair<TIntV, TFltV> & Doc, TFltV & Result); //#endif // TEST // D = alpha * A(') * B(') + beta * C(') typedef enum { GEMM_NO_T = 0, GEMM_A_T = 1, GEMM_B_T = 2, GEMM_C_T = 4 } TLinAlgGemmTranspose; template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Gemm(const double& Alpha, const TVVec<TType, TSizeTy, ColMajor>& A, const TVVec<TType, TSizeTy, ColMajor>& B, const double& Beta, const TVVec<TType, TSizeTy, ColMajor>& C, TVVec<TType, TSizeTy, ColMajor>& D, const int& TransposeFlags) { bool tA = (TransposeFlags & GEMM_A_T) == GEMM_A_T; bool tB = (TransposeFlags & GEMM_B_T) == GEMM_B_T; bool tC = (TransposeFlags & GEMM_C_T) == GEMM_C_T; // setting dimensions TSizeTy a_i = tA ? A.GetRows() : A.GetCols(); TSizeTy a_j = tA ? A.GetCols() : A.GetRows(); TSizeTy b_i = tB ? B.GetRows() : B.GetCols(); TSizeTy b_j = tB ? B.GetCols() : B.GetRows(); TSizeTy c_i = tC ? C.GetRows() : C.GetCols(); TSizeTy c_j = tC ? C.GetCols() : C.GetRows(); TSizeTy d_i = D.GetCols(); TSizeTy d_j = D.GetRows(); // assertions for dimensions EAssert(a_j == c_j && b_i == c_i && a_i == b_j && c_i == d_i && c_j == d_j); double Aij, Bij, Cij; // rows of D for (TSizeTy j = 0; j < a_j; j++) { // cols of D for (TSizeTy i = 0; i < b_i; i++) { // not optimized for speed - naive algorithm double sum = 0.0; // cols of A for (TSizeTy k = 0; k < a_i; k++) { Aij = tA ? A.At(k, j) : A.At(j, k); Bij = tB ? B.At(i, k) : B.At(k, i); sum += Alpha * Aij * Bij; } Cij = tC ? C.At(i, j) : C.At(j, i); sum += Beta * Cij; D.At(j, i) = sum; } } } // TEST (works only for RowMajor, TSvd uses only TFltVV matrices) // B = A^(-1) typedef enum { DECOMP_SVD } TLinAlgInverseType; template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Inverse(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor >& B, const TLinAlgInverseType& DecompType) { switch (DecompType) { case DECOMP_SVD: TLinAlg::InverseSVD(A, B); } } // subtypes of finding an inverse (works only for TFltVV, cuz of TSvd) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::InverseSVD(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& B, const double& tol) { // create temp matrices TVVec<TType, TSizeTy, ColMajor> U, V; TVec<TType, TSizeTy> E; TSvd SVD; //U.Gen(M.GetRows(), M.GetRows()); //V.Gen(M.GetCols(), M.GetCols()); U.Gen(A.GetRows(), A.GetRows()); V.Gen(A.GetCols(), A.GetCols()); // do the SVD decompostion SVD.Svd(A, U, E, V); // calculate reciprocal values for diagonal matrix = inverse diagonal for (TSizeTy i = 0; i < E.Len(); i++) { if (E[i] > tol) { E[i] = 1 / E[i]; } else { E[i] = 0.0; } } // calculate pseudoinverse: M^(-1) = V * E^(-1) * U' for (TSizeTy i = 0; i < U.GetCols(); i++) { for (TSizeTy j = 0; j < V.GetRows(); j++) { double sum = 0.0; for (TSizeTy k = 0; k < U.GetCols(); k++) { if (E[k] == 0.0) continue; sum += E[k] * V.At(i, k) * U.At(j, k); } B.At(i, j) = sum; } } } // subtypes of finding an inverse (works only for TFltVV, cuz of TSvd) template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::InverseSVD(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& B) { // create temp matrices TVVec<TType, TSizeTy, ColMajor> U, V; TVec<TType, TSizeTy> E; TSvd SVD; //U.Gen(M.GetRows(), M.GetRows()); //V.Gen(M.GetCols(), M.GetCols()); U.Gen(A.GetRows(), A.GetRows()); V.Gen(A.GetCols(), A.GetCols()); // do the SVD decompostion SVD.Svd(A, U, E, V); // http://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse#Singular_value_decomposition_.28SVD.29 double tol = TFlt::Eps * MAX(A.GetRows(), A.GetCols()) * E[E.GetMxValN()]; // calculate reciprocal values for diagonal matrix = inverse diagonal for (TSizeTy i = 0; i < E.Len(); i++) { if (E[i] > tol) { E[i] = 1 / E[i]; } else { E[i] = 0.0; } } // calculate pseudoinverse: M^(-1) = V * E^(-1) * U' for (TSizeTy i = 0; i < U.GetCols(); i++) { for (TSizeTy j = 0; j < V.GetRows(); j++) { double sum = 0; for (TSizeTy k = 0; k < U.GetCols(); k++) { if (E[k] == 0.0) continue; sum += E[k] * V.At(i, k) * U.At(j, k); } B.At(i, j) = sum; } } } // transpose matrix - B = A' template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::Transpose(const TVVec<TType, TSizeTy, ColMajor>& A, TVVec<TType, TSizeTy, ColMajor>& B) { if (B.Empty()) { B.Gen(A.GetCols(), A.GetRows()); } EAssert(B.GetRows() == A.GetCols() && B.GetCols() == A.GetRows()); for (TSizeTy i = 0; i < A.GetCols(); i++) { for (TSizeTy j = 0; j < A.GetRows(); j++) { B.At(i, j) = A.At(j, i); } } } // performes Gram-Schmidt ortogonalization on elements of Q template <class TSizeTy> void TLinAlg::GS(TVec<TVec<TFlt, TSizeTy>, TSizeTy>& Q) { EAssert(Q.Len() > 0); TSizeTy m = Q.Len(); // int n = Q[0].Len(); for (TSizeTy i = 0; i < m; i++) { printf("%d\r", i); for (TSizeTy j = 0; j < i; j++) { double r = TLinAlg::DotProduct(Q[i], Q[j]); TLinAlg::AddVec(-r, Q[j], Q[i], Q[i]); } TLinAlg::Normalize(Q[i]); } printf("\n"); } // TEST // Gram-Schmidt on columns of matrix Q template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::GS(TVVec<TType, TSizeTy, ColMajor>& Q) { TSizeTy m = Q.GetCols(), n = Q.GetRows(); for (TSizeTy i = 0; i < m; i++) { printf("%d\r", i); for (TSizeTy j = 0; j < i; j++) { double r = TLinAlg::DotProduct(Q, i, Q, j); TLinAlg::AddVec(-r, Q, j, Q, i); } double nr = TLinAlg::Norm(Q, i); for (TSizeTy k = 0; k < n; k++) Q(k, i) = Q(k, i) / nr; } printf("\n"); } // Modified Gram-Schmidt on columns of matrix Q void TLinAlg::MGS(TFltVV& Q) { int Cols = Q.GetCols(), Rows = Q.GetRows(); EAssertR(Rows >= Cols, "TLinAlg::MGS: number of rows should be greater or equal to the number of cols"); for (int ColN = 0; ColN < Cols; ColN++) { TLinAlg::NormalizeColumns(Q); for (int ColN2 = ColN + 1; ColN2 < Cols; ColN2++) { double r = TLinAlg::DotProduct(Q, ColN, Q, ColN2); TLinAlg::AddVec(-r, Q, ColN, Q, ColN2); } } } // QR based on Modified Gram-Schmidt decomposition. void TLinAlg::QR(const TFltVV& X, TFltVV& Q, TFltVV& R, const TFlt& Tol) { int Rows = X.GetRows(); int Cols = X.GetCols(); int d = MIN(Rows, Cols); // make a copy of X TFltVV A(X); if (Q.GetRows() != Rows || Q.GetCols() != d) { Q.Gen(Rows, d); } if (R.GetRows() != d || R.GetCols() != Cols) { R.Gen(d, Cols); } TRnd Random; for (int k = 0; k < d; k++) { R(k, k) = TLinAlg::Norm(A, k); // if the remainders norm is too small we construct a random vector (handles rank deficient) if (R(k, k) < Tol) { // random Q(:,k) for (int RowN = 0; RowN < Rows; RowN++) { Q(RowN, k) = Random.GetNrmDev(); } // make it orthonormal on others for (int j = 0; j < k; j++) { TLinAlg::AddVec(-TLinAlg::DotProduct(Q, j, Q, k), Q, j, Q, k); } TLinAlg::NormalizeColumn(Q, k); R(k, k) = 0; } else { // normalize for (int RowN = 0; RowN < Rows; RowN++) { Q(RowN, k) = A(RowN, k) / R(k, k); } } // make the rest of the columns of A orthogonal to the current basis Q for (int j = k + 1; j < Cols; j++) { R(k, j) = TLinAlg::DotProduct(Q, k, A, j); TLinAlg::AddVec(-R(k, j), Q, k, A, j); } } } // rotates vector (OldX,OldY) for angle Angle (in radians!) void TLinAlg::Rotate(const double& OldX, const double& OldY, const double& Angle, double& NewX, double& NewY) { NewX = OldX*cos(Angle) - OldY*sin(Angle); NewY = OldX*sin(Angle) + OldY*cos(Angle); } // checks if set of vectors is ortogonal template <class TSizeTy> void TLinAlg::AssertOrtogonality(const TVec<TVec<TFlt, TSizeTy>, TSizeTy>& Vecs, const double& Threshold) { TSizeTy m = Vecs.Len(); for (TSizeTy i = 0; i < m; i++) { for (TSizeTy j = 0; j < i; j++) { double res = TLinAlg::DotProduct(Vecs[i], Vecs[j]); if (TFlt::Abs(res) > Threshold) printf("<%d,%d> = %.5f", i, j, res); } double norm = TLinAlg::Norm2(Vecs[i]); if (TFlt::Abs(norm - 1) > Threshold) printf("||%d|| = %.5f", i, norm); } } //ColMajor oriented data for optimal result template <class TType, class TSizeTy, bool ColMajor> void TLinAlg::AssertOrtogonality(const TVVec<TType, TSizeTy, ColMajor>& Vecs, const double& Threshold) { TSizeTy m = Vecs.GetCols(); for (TSizeTy i = 0; i < m; i++) { for (TSizeTy j = 0; j < i; j++) { double res = TLinAlg::DotProduct(Vecs, i, Vecs, j); if (TFlt::Abs(res) > Threshold) printf("<%d,%d> = %.5f", i, j, res); } double norm = TLinAlg::Norm2(Vecs, i); if (TFlt::Abs(norm - 1) > Threshold) printf("||%d|| = %.5f", i, norm); } printf("\n"); } bool TLinAlg::IsOrthonormal(const TFltVV& Vecs, const double& Threshold) { int m = Vecs.GetCols(); TFltVV R(m, m); TLinAlg::MultiplyT(Vecs, Vecs, R); for (int i = 0; i < m; i++) { R(i, i) -= 1; } return TLinAlg::Frob(R) < Threshold; } bool TLinAlg::IsZero(const TFltV& Vec) { int Len = Vec.Len(); for (int i = 0; i < Len; i++) { if (Vec[i] != 0.0) { return false; } } return true; } template <class TType, class TSizeTy, bool ColMajor> inline void TLinAlg::Pow(const TVVec<TType, TSizeTy, ColMajor>& Mat, const int& k, TVVec<TType, TSizeTy, ColMajor>& PowVV) { EAssertR(Mat.GetRows() == Mat.GetCols(), "TLinAlg::Pow: Can only compute powers of square matrices!"); const TSizeTy Dim = Mat.GetRows(); if (k == 0) { TLAUtil::Identity(Dim, PowVV); } else if (k < 0) { TVVec<TType, TSizeTy, ColMajor> InverseVV; TLinAlg::Inverse(Mat, InverseVV, TLinAlgInverseType::DECOMP_SVD); Pow(InverseVV, -k, PowVV); } else { PowVV.Gen(Dim, Dim); // we will compute the power using the binary algorithm // we will always hold the newest values in X, so when // finishing the algorithm, the result will be in X // X <- A TVVec<TType, TSizeTy, ColMajor> TempMat(Mat); // temporary matrix // pointers, so swapping is faster TVVec<TType, TSizeTy, ColMajor>* X = &TempMat; TVVec<TType, TSizeTy, ColMajor>* X1 = &PowVV; // use the space already available // temporary variables TVVec<TType, TSizeTy, ColMajor>* Temp; // do the work uint k1 = (uint) k; uint n = (uint) TMath::Log2(k); uint b; for (uint i = 1; i <= n; i++) { b = (k1 >> (n-i)) & 1; // X <- X*X TLinAlg::Multiply(*X, *X, *X1); // swap X and X1 so that X holds the content Temp = X1; X1 = X; X = Temp; if (b == 1) { // X <- X*A TLinAlg::Multiply(*X, Mat, *X1); // swap X and X1 so that X holds the content Temp = X1; X1 = X; X = Temp; } } if (&PowVV != X) { // the values are in X, but we are returning X1 // copy X to PowVV PowVV = *X; } } } //}; template <class TVal> TVal TLinAlg::GetColMin(const TVVec<TVal>& X, const int& ColN) { const int Rows = X.GetRows(); EAssertR(Rows > 0, "Input matrix should have at least one row!"); TVal MinVal = X(0, ColN); for (int RowN = 1; RowN < Rows; RowN++) { TVal Val = X(RowN, ColN); if (Val < MinVal) { MinVal = Val; } } return MinVal; } template <class TVal> void TLinAlg::GetColMinV(const TVVec<TVal>& X, TVec<TVal>& ValV) { const int Cols = X.GetCols(); ValV.Gen(Cols); for (int ColN = 0; ColN < Cols; ColN++) { ValV[ColN] = GetColMin(X, ColN); } } ////////////////////////////////////////////////////////////////////// // Numerical-Recipes-Exception class TNSException : public TExcept { public: TStr Message; public: TNSException(const TStr& Msg) : TExcept(Msg) {} TNSException(const TStr& MsgStr, const TStr& LocStr) : TExcept(MsgStr, LocStr) { } /// Create new numerical exception static PExcept New(const TStr& MsgStr, const TStr& LocStr = TStr()) { return PExcept(new TNSException(MsgStr, LocStr)); } }; ////////////////////////////////////////////////////////////////////// // Numerical-Linear-Algebra (copied from Numerical Recepies) class TNumericalStuff { private: static double sqr(double a); static double sign(double a, double b); // Computes (a^2 + b^2)^(1/2) without // destructive underflow or overflow. static double pythag(double a, double b); //displays error message to screen static void nrerror(const TStr& error_text); public: // Householder reduction of a real, symmetric matrix a[1..n][1..n]. // On output, a is replaced by the orthogonal matrix Q e ecting the // transformation. d[1..n] returns the diagonal elements of the // tridiagonal matrix, and e[1..n] the o -diagonal elements, with // e[1]=0. Several statements, as noted in comments, can be omitted // if only eigenvalues are to be found, in which case a contains no // useful information on output. Otherwise they are to be included. static void SymetricToTridiag(TFltVV& a, int n, TFltV& d, TFltV& e); // QL algorithm with implicit shifts, to determine the eigenvalues // and eigenvectors of a real, symmetric, tridiagonal matrix, or of // a real, symmetric matrix previously reduced by tred2 x11.2. On // input, d[1..n] contains the diagonal elements of the tridiagonal // matrix. On output, it returns the eigenvalues. The vector e[1..n] // inputs the subdiagonal elements of the tridiagonal matrix, with // e[1] arbitrary. On output e is destroyed. When finding only the // eigenvalues, several lines may be omitted, as noted in the comments. // If the eigenvectors of a tridiagonal matrix are desired, the matrix // z[1..n][1..n] is input as the identity matrix. If the eigenvectors // of a matrix that has been reduced by tred2 are required, then z is // input as the matrix output by tred2. In either case, the kth column // of z returns the normalized eigenvector corresponding to d[k]. static void EigSymmetricTridiag(TFltV& d, TFltV& e, int n, TFltVV& z); // Given a positive-dedinite symmetric matrix A(n,n), this routine // constructs its Cholesky decomposition, A = L * L^T . On input, only // the upper triangle of A need be given; it is not modified. The // Cholesky factor L is returned in the lower triangle of A, except for // its diagonal elements which are returned in p(n). static void CholeskyDecomposition(TFltVV& A, TFltV& p); // Solves the set of n linear equations A * x = b, where A is a // positive-definite symmetric matrix. A(n,n) and p[1..n] are input // as the output of the routine choldc. Only the lower triangle of A // is accessed. b(n) is input as the right-hand side vector. The // solution vector is returned in x(n). A and p are not modified and // can be left in place for successive calls with diferent right-hand // sides b. b is not modified unless you identify b and x in the calling // sequence, which is allowed. static void CholeskySolve(const TFltVV& A, const TFltV& p, const TFltV& b, TFltV& x); // Solves system of linear equations A * x = b, where A is symetric // positive-definite matrix. A is first decomposed using // CholeskyDecomposition and after solved using CholeskySolve. Only // upper triangle of A need be given and it is not modified. However, // lower triangle is modified! static void SolveSymetricSystem(TFltVV& A, const TFltV& b, TFltV& x); // solve system A x_i = e_i for i = 1..n, where A and p are output // from CholeskyDecomposition. Result is stored to upper triangule // (possible since inverse of symetric matrix is also symetric! Sigh...) static void InverseSubstitute(TFltVV& A, const TFltV& p); // Calculates inverse of symetric positiv definit matrix // Matrix is given as upper triangule of A, result is stored // in upper triangule of A. Lower triangule is random (actually // it has part of Choleksy decompositon of A) static void InverseSymetric(TFltVV& A); // calcualtes inverse of upper triagonal matrix A // lower triangle is messed up... static void InverseTriagonal(TFltVV& A); // Given a matrix a[1..n][1..n], this routine replaces it by the LU // decomposition of a rowwise permutation of itself. a and n are input. // a is output, arranged as in equation (2.3.14) above; indx[1..n] is // an output vector that records the row permutation efected by the partial // pivoting; d is output as +-1 depending on whether the number of row // interchanges was even or odd, respectively. This routine is used in // combination with lubksb to solve linear equations or invert a matrix. static void LUDecomposition(TFltVV& A, TIntV& indx, double& d); // Solves the set of n linear equations A*X = B. Here a[1..n][1..n] is input, // not as the matrix A but rather as its LU decomposition, determined by the // routine ludcmp. indx[1..n] is input as the permutation vector returned by // ludcmp. b[1..n] is input as the right-hand side vector B, and returns with // the solution vector X. a, n, and indx are not modified by this routine and // can be left in place for successive calls with diferent right-hand sides b. // This routine takes into account the possibility that b will begin with many // zero elements, so it is efficient for use in matrix inversion. static void LUSolve(const TFltVV& A, const TIntV& indx, TFltV& b); // Finds x[1...f] that minimizes ||A' x - y||^2 + ||Gamma x||^2, where A[1...f][1...n] // is a matrix with column training examples (rows = features) and y[1...n] is a // vector of targets. // Solves the primal problem if the number of features is lower than the number of examples, // or the dual problem in the other case. //Paramter Gamma controls overfitting (large values force models to be simpler) // See http://en.wikipedia.org/wiki/Tikhonov_regularization, where the regularization matrix = Gamma*I static void LeastSquares(const TFltVV& A, const TFltV& b, const double& kappa, TFltV& x); // Finds x[1...f] that minimizes ||A' x - y||^2 + ||Gamma x||^2, where A[1...f][1...n] // is a matrix with column training examples (rows = features) and y[1...n] is a // vector of targets. Paramter Gamma controls overfitting (large values force models to be simpler) // See http://en.wikipedia.org/wiki/Tikhonov_regularization, where the regularization matrix = Gamma*I static void PrimalLeastSquares(const TFltVV& A, const TFltV& b, const double& kappa, TFltV& x); // Finds x[1...f] that minimizes ||A' x - y||^2 + ||Gamma x||^2, where A[1...f][1...n] // is a matrix with column training examples (rows = features) and y[1...n] is a // vector of targets. Solves the dual version of the problem and exresses it in the // original coordinates in the end - suitable for cases, where the number of examples // is larger than the number of features. // Paramter Gamma controls overfitting (large values force models to be simpler) // See http://en.wikipedia.org/wiki/Tikhonov_regularization, where the regularization matrix = Gamma*I static void DualLeastSquares(const TFltVV& A, const TFltV& b, const double& kappa, TFltV& x); // Solves system of linear equations A * x = b. A is first decomposed using // LUDecomposition and after solved using LUSolve. A is modified! static void SolveLinearSystem(TFltVV& A, const TFltV& b, TFltV& x); // Computes the eigenvector of A belonging to the specified eigenvalue // uses the inverse iteration algorithm // the algorithms does modify A due to its use of LU decomposition static void GetEigenVec(const TFltVV& A, const double& EigenVal, TFltV& EigenV, const double& ConvergEps=1e-7); }; /////////////////////////////////////////////////////////////////////// // Sparse-SVD // Calculates singular-value-decompositon for sparse matrixes. // If A is a matrix than A is decomposed to A = U S V' // where S is diagonal with singular values on diagonal and U // and V are ortogonal (U'*U = V'*V = I). typedef enum { ssotNoOrto, ssotSelective, ssotFull } TSpSVDReOrtoType; class TSparseSVD { private: // Result = Matrix' * Matrix * Vec(:,ColId) static void MultiplyATA(const TMatrix& Matrix, const TFltVV& Vec, int ColId, TFltV& Result); // Result = Matrix' * Matrix * Vec static void MultiplyATA(const TMatrix& Matrix, const TFltV& Vec, TFltV& Result); public: // calculates NumEig eigen values of symetric matrix // if SvdMatrixProductP than matrix Matrix'*Matrix is used static void SimpleLanczos(const TMatrix& Matrix, const int& NumEig, TFltV& EigValV, const bool& DoLocalReortoP = false, const bool& SvdMatrixProductP = false); // fast, calculates NumEig largers eigen values and vectors // kk should be something like 4*NumEig // if SvdMatrixProductP than matrix Matrix'*Matrix is used static void Lanczos(const TMatrix& Matrix, int NumEig, int Iters, const TSpSVDReOrtoType& ReOrtoType, TFltV& EigValV, TFltVV& EigVecVV, const bool& SvdMatrixProductP = false); static void Lanczos2(const TMatrix& Matrix, int MaxNumEig, int MaxSecs, const TSpSVDReOrtoType& ReOrtoType, TFltV& EigValV, TFltVV& EigVecVV, const bool& SvdMatrixProductP = false); // calculates only singular values (based on SimpleLanczos) static void SimpleLanczosSVD(const TMatrix& Matrix, const int& CalcSV, TFltV& SngValV, const bool& DoLocalReortoP = false); // fast, calculates NumSV largers SV (based on Lanczos) static void LanczosSVD(const TMatrix& Matrix, int NumSV, int Iters, const TSpSVDReOrtoType& ReOrtoType, TFltV& SgnValV, TFltVV& LeftSgnVecVV, TFltVV& RightSgnVecVV); // slow - ortogonal iteration static void OrtoIterSVD(const TMatrix& Matrix, int NumSV, int IterN, TFltV& SgnValV); // slow - ortogonal iteration static void OrtoIterSVD(const TMatrix& Matrix, const int k, TFltV& S, TFltVV& U, TFltVV& V, const int Iters = 100, const double Tol = 1e-6); // projects sparse vector to space spanned by columns of matrix U static void Project(const TIntFltKdV& Vec, const TFltVV& U, TFltV& ProjVec); }; ////////////////////////////////////////////////////////////////////// // Sigmoid -- made by Janez(TM) // (y = 1/[1 + exp[-Ax+B]]) class TSigmoid { private: TFlt A; TFlt B; private: // Evaluates how well the sigmoid function fits the data. // J(A, B) = - ln prod_i P(Y = y_i | Z = z_i). The 'data' parameter // should contain (z_i, y_i) pairs. Smaller J means a better fit. static double EvaluateFit(const TFltIntKdV& data, const double A, const double B); // Computes not only J but also its partial derivatives. static void EvaluateFit(const TFltIntKdV& data, const double A, const double B, double& J, double& JA, double& JB); // Let J(lambda) = J(A + lambda U, B + lambda V). // This function computes J and its first and second derivatives. // They can be used to choose a good lambda (using Newton's method) // when minimizing J. -- This method has not been tested yet. static void EvaluateFit(const TFltIntKdV& data, const double A, const double B, const double U, const double V, const double lambda, double& J, double& JJ, double& JJJ); public: TSigmoid() { }; TSigmoid(const double& A_, const double& B_) : A(A_), B(B_) { }; // Tries to find a pair (A, B) that minimizes J(A, B). // Uses gradient descent. TSigmoid(const TFltIntKdV& data); TSigmoid(TSIn& SIn) { A.Load(SIn); B.Load(SIn); } void Load(TSIn& SIn) { A.Load(SIn); B.Load(SIn); } void Save(TSOut& SOut) const { A.Save(SOut); B.Save(SOut); } double GetVal(const double& x) const { return 1.0 / (1.0 + exp(-A * x + B)); } double operator()(const double& x) const { return GetVal(x); } void GetSigmoidAB(double& A_, double& B_) { A_ = A; B_ = B; } }; class TFullMatrix; ///////////////////////////////////////////////////////////////////////// //// Full-Vector class TVector { friend class TFullMatrix; public: bool IsColVector; TFltV Vec; public: TVector(const bool& IsColVector = true); TVector(const int& Dim, const bool IsColVector = true); TVector(const TFltV& Vect, const bool IsColVector = true); TVector(const TIntV& Vect, const bool IsColVector = true); TVector(const TFullMatrix& Mat); // copy constructor TVector(const TVector& Vector); #ifdef GLib_CPP11 // Move constructor TVector(const TVector&& Vector); #endif // Move assignment TVector& operator=(TVector Vector); // returns a new zero vector static TVector Init(const int& Dim, const bool _IsColVect); // returns a vector of ones static TVector Ones(const int& Dim, const bool IsColVect = true); // returns a vector of zeros static TVector Zeros(const int& Dim, const bool IsColVec = true); // returns a vector with a sequence starting with Start (inclusive) and ending // with End (exclusive) static TVector Range(const int& Start, const int& End, const bool IsColVect = true); // returns a vector with a sequence starting with 0 (inclusive) and ending // with End (exclusive) static TVector Range(const int& End, const bool IsColVect = true); void Add(const double& Val) { Vec.Add(Val); } void DelLast() { Vec.DelLast(); } // returns true if the vectors have the same orientation and the elements are the same bool operator ==(const TVector& Vect) const; // returns the element at index Idx TFlt& operator [](const int& Idx) { return Vec[Idx]; } const TFlt& operator [](const int& Idx) const { return Vec[Idx]; } TVector GetT() const; TVector& Transpose(); double DotProduct(const TFltV& y) const; double DotProduct(const TVector& y) const; // multiplication TFullMatrix operator *(const TVector& y) const; TVector operator *(const TFullMatrix& Mat) const; TVector operator *(const double& k) const; // multiplies all elements by Lambda TVector& operator *=(const double& Lambda); // division // divides all elements by Lambda TVector operator /(const double& Lambda) const; // divides all elements by Lambda TVector& operator /=(const double& Lambda); // multiply the transpose of this vector with B (e.g. x'*B) TVector MulT(const TFullMatrix& B) const; // addition TVector operator +(const TVector& y) const; TVector& operator +=(const TVector& y); // subtraction TVector operator -(const TVector& y) const; public: int Len() const { return Vec.Len(); } bool IsColVec() const { return IsColVector; } bool IsRowVec() const { return !IsColVec(); } bool Empty() const { return Vec.Empty(); } template<typename TFunc> TVector& Map(const TFunc& Func); // applies sqrt on all elements of this matrix TVector& Sqrt() { return Map([](TFlt Val) { return sqrt(Val); }); } // returns a vector containing indexes of all the elements satisfying a condition template<typename TFunc> TVector Find(const TFunc& Func) const; template<typename TFunc, typename TRes> void Find(const TFunc& Func, TRes& Res) const; // returns the 'euclidian' L2 norm double Norm() const; // returns the squared 'euclidian' L2 norm double Norm2() const; // returns the sum of elements double Sum() const; // returns the euclidean distance to the other vector double EuclDist(const TVector& y) const; // returns the underlying list const TFltV& GetVec() const { return Vec; } // returns the underlying list TFltV& GetVec() { return Vec; } // returns this vector as a list of integers TIntV GetIntVec() const; double GetMaxVal() const; // returns the index of the maximum element int GetMaxIdx() const; // returns the index and value of the maximum element TIntFltPr GetMax() const; // returns the index of the minimum element int GetMinIdx() const; void Save(TSOut& SOut) const { TBool(IsColVector).Save(SOut); Vec.Save(SOut); } void Load(TSIn& SIn) { IsColVector = TBool(SIn); Vec.Load(SIn); } }; template <typename TFunc> TVector& TVector::Map(const TFunc& Func) { const int& Dim = Len(); for (int i = 0; i < Dim; i++) { Vec[i] = Func(Vec[i]); } return *this; } template <typename TFunc> TVector TVector::Find(const TFunc& Func) const { TVector Res; Find(Func, Res); return Res; } template <typename TFunc, typename TRes> void TVector::Find(const TFunc& Func, TRes& Res) const { const int& Dim = Len(); for (int i = 0; i < Dim; i++) { if (Func(Vec[i])) { Res.Add(i); } } } ///////////////////////////////////////////////////////////////////////// //// Full-Matrix typedef TTriple<TFullMatrix, TFullMatrix, TFullMatrix> TFullMatrixTr; typedef TTriple<TFullMatrix, TVector, TFullMatrix> TMatVecMatTr; class TFullMatrix : public TMatrix { friend class TVector; private: bool IsWrapper; TFltVV* Mat; public: // constructors/destructors // empty matrix with 0 rows and 0 cols TFullMatrix(); // zero matrix with the specified number of rows and cols TFullMatrix(const int& Rows, const int& Cols); // matrix from TFltVV, if IsWrapper is set to true then the // underlying matrix will not be deleted TFullMatrix(TFltVV& Mat, const bool IsWrapper); TFullMatrix(const TFltVV& Mat); // matrix from vector TFullMatrix(const TVector& Vec); // copy constructor TFullMatrix(const TFullMatrix& Mat); #ifdef GLib_CPP11 // move constructor TFullMatrix(TFullMatrix&& Mat); #endif private: // wraps the matrix and takes control of all the cleanup TFullMatrix(TFltVV* Mat); public: // destructor virtual ~TFullMatrix(); // copy constructor TFullMatrix& operator =(const TFullMatrix& Mat); // move constructor TFullMatrix& operator =(TFullMatrix&& _Mat); // identity matrix static TFullMatrix Identity(const int& Dim); // matrix from TVec<TFltV>, each element from the list goes into one row static TFullMatrix RowMatrix(const TVec<TFltV>& Mat); // matrix from TVec<TFltV>, each element from the list goes into one column static TFullMatrix ColMatrix(const TVec<TFltV>& Mat); // get a matrix with the values from the vector are diagonal elements static TFullMatrix Diag(const TVector& Diag); private: void Clr(); protected: virtual void PMultiply(const TFltVV& B, int ColId, TFltV& Result) const; virtual void PMultiply(const TFltV& Vec, TFltV& Result) const; virtual void PMultiplyT(const TFltVV& B, int ColId, TFltV& Result) const; virtual void PMultiplyT(const TFltV& Vec, TFltV& Result) const; virtual void PMultiply(const TFltVV& B, TFltVV& Result) const; virtual void PMultiplyT(const TFltVV& B, TFltVV& Result) const; // getters virtual int PGetRows() const { return Mat->GetRows(); } virtual int PGetCols() const { return Mat->GetCols(); } public: // returns the underlying TFltVV const TFltVV& GetMat() const { return *Mat; } // returns the underlying TFltVV TFltVV& GetMat() { return *Mat; } // transposed virtual void Transpose(); // returns the transpose of this matrix TFullMatrix GetT() const; void GetT(TFltVV& TransposedVV) const; // returns the value at position (i,j) TFlt& At(const int& i, const int& j) { return Mat->operator ()(i, j); } const TFlt& At(const int& i, const int& j) const { return Mat->operator ()(i, j); } // sets the value at position (i,j) void Set(const double& Val, const int& i, const int& j) { Mat->operator ()(i, j) = Val; } // returns true if the matrix is empty bool Empty() const { return Mat->Empty(); } TFullMatrix& AddCol(const TFltV& Col); TFullMatrix& AddCol(const TVector& Col); TFullMatrix& AddCols(const TFullMatrix& Cols); // operators TFlt& operator ()(const int& i, const int& j) { return At(i,j); } const TFlt& operator ()(const int& i, const int& j) const { return At(i,j); } // returns a submatrix specified by RowV and ColV template<class TIdxV1, class TIdxV2> TFullMatrix operator ()(const TIdxV1& RowV, const TIdxV2& ColV) const; template<class TIdxV> TVector operator ()(const int& RowIdx, const TIdxV& ColV) const; // adds matrix B and returns itself TFullMatrix& operator +=(const TFullMatrix& B); // subtracts matrix B and returns itself TFullMatrix& operator -=(const TFullMatrix& B); // add/subtract TFullMatrix operator +(const TFullMatrix& B) const; TFullMatrix operator -(const TFullMatrix& B) const; // multiply TFullMatrix operator *(const TFullMatrix& B) const; TFullMatrix operator *(const TSparseColMatrix& B) const; // multiply the transpose of this matrix with B (e.g. A'*B) TFullMatrix MulT(const TFullMatrix& B) const; TFullMatrix MulT(const TFltVV& B) const; // multiplies this matrix with a vector TVector operator *(const TVector& x) const; // multiplies this matrix with a vector represented as TFltV // ignores the vectors orientation TVector operator *(const TFltV& x) const; // scalars // multiplies this matrix by a scalar and returns the result TFullMatrix operator *(const double& Lambda) const; // divides this matrix by a scalar and returns the result TFullMatrix operator /(const double& Lambda) const; // returns the power of this matrix A^n where A is this matrix and n is the argument TFullMatrix Pow(const int& k) const; TFullMatrix operator ^(const int& k) const { return Pow(k); }; // returns the RowIdx-th row TVector GetRow(const int& RowIdx) const; // returns the ColIdx-th column TVector GetCol(const int& ColIdx) const; void SetRow(const int& RowIdx, const TVector& RowV); void SetCol(const int& ColIdx, const TVector& ColV); // applies an element-wise operation on this matrix and returns the matrix itself template<typename TFunc> TFullMatrix& Map(const TFunc& Func); // applies sqrt on all elements of this matrix TFullMatrix& Sqrt() { return Map([](TFlt Val) { return sqrt(Val); }); } // returns the L2 norm of the specified column double ColNorm(const int& ColIdx) const; // returns the squared L2 norm of the specified column double ColNorm2(const int& ColIdx) const; // returns the L2 norm of each column and returns them in a row vector TVector ColNormV() const; // returns the squared L2 norm of each column and returns them in a row vector TVector ColNorm2V() const; // returns the Frobenius norm of this matrix double FromNorm() const; // returns the norm of the i-th row double RowNormL1(const int& i) const; // normalizes the rows using L1 norm void NormalizeRowsL1(); // returns the sum of the i-th row double RowSum(const int& i) const; // returns a vector containing the sum of rows TVector RowSumV() const; // returns a vector containing the minimum values of each column TVector GetColMinV() const; // returns the index of the maximum element in each column in a row vector TVector GetColMaxIdxV() const; // returns the index of the minimum element in each column in a row vector TVector GetColMinIdxV() const; // transforms the rows of the matrix to have mean 0 TFullMatrix& CenterRows(); // returns a matrix which has rows centered around zero (check CenterRows) TFullMatrix GetCenteredRows() const; // computes the singular value decomposition if this matrix X = U*S*V' // returns a triple where U is stored in the first value, S is stored as a vector // in the second value and V is stored in the third value // k represents the number of singular values that are computed TMatVecMatTr Svd(const int& k) const; TMatVecMatTr Svd() const { return Svd(TMath::Mn(GetRows(), GetCols())); } // returns the inverse of this matrix TFullMatrix GetInverse() const; bool HasNan() const; public: void Save(TSOut& SOut) const; void Load(TSIn& SIn); }; template <class TIdxV1, class TIdxV2> TFullMatrix TFullMatrix::operator ()(const TIdxV1& RowV, const TIdxV2& ColV) const { const int Rows = RowV.Len(); const int Cols = ColV.Len(); TFullMatrix Result(Rows, Cols); for (int i = 0; i < Rows; i++) { for (int j = 0; j < Cols; j++) { const int Idx1 = (int) RowV[i]; const int Idx2 = (int) ColV[j]; const TFlt Val = Mat->At(Idx1, Idx2); Result.Mat->PutXY(i, j, Val); } } return Result; } template <class TIdxV> TVector TFullMatrix::operator ()(const int& RowIdx, const TIdxV& ColIdxV) const { EAssertR(RowIdx < GetRows(), TStr::Fmt("Invalid row index: %d", RowIdx)); const int Cols = ColIdxV.Len(); TVector Result(Cols, false); for (int ColIdx = 0; ColIdx < Cols; ColIdx++) { Result[ColIdx] = At(RowIdx, ColIdx); } return Result; } template <typename TFunc> TFullMatrix& TFullMatrix::Map(const TFunc& Func) { const int& Rows = GetRows(); const int& Cols = GetCols(); for (int i = 0; i < Rows; i++) { for (int j = 0; j < Cols; j++) { Mat->At(i, j) = Func(Mat->At(i, j)); } } return *this; } #ifdef LAPACKE #include "MKLfunctions.h" #endif #endif
fourier.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % 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 % % % % https://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/blob.h" #include "MagickCore/cache.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/fourier.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { PixelChannel channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,images->columns,images->rows,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,images->columns,images->rows,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(images); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]); Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]); Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]); Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ComplexImages) #endif proceed=SetImageProgress(images,ComplexImageTag,progress++, images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) CopyMagickMemory(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register Quantum *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) ResetMagickMemory(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) ResetMagickMemory(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } } i++; q+=GetPixelChannels(magnitude_image); } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } } i++; q+=GetPixelChannels(phase_image); } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); ResetMagickMemory(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(image,p); break; } case GreenPixelChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(image,p); break; } case BluePixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(image,p); break; } case BlackPixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlack(image,p); break; } case AlphaPixelChannel: { source_pixels[i]=QuantumScale*GetPixelAlpha(image,p); break; } } i++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsImageGray(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayPixelChannel,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image, RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->alpha_trait != UndefinedPixelTrait) thread_status=ForwardFourierTransformChannel(image, AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Inverse fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p); break; } case GreenPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p); break; } case BluePixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p); break; } case BlackPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p); break; } case AlphaPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p); break; } } i++; p+=GetPixelChannels(magnitude_image); } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) CopyMagickMemory(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p); break; } case GreenPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p); break; } case BluePixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p); break; } case BlackPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p); break; } case AlphaPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p); break; } } i++; p+=GetPixelChannels(phase_image); } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) CopyMagickMemory(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register Quantum *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BluePixelChannel: { SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BlackPixelChannel: { SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case AlphaPixelChannel: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } } i++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsImageGray(magnitude_image); if (is_gray != MagickFalse) is_gray=IsImageGray(phase_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayPixelChannel,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->alpha_trait != UndefinedPixelTrait) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
Stmt.h
//===- Stmt.h - Classes for representing statements -------------*- 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 Stmt interface and subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_STMT_H #define LLVM_CLANG_AST_STMT_H #include "clang/AST/DeclGroup.h" #include "clang/AST/DependenceFlags.h" #include "clang/AST/StmtIterator.h" #include "clang/Basic/CapturedStmt.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/BitmaskEnum.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/iterator.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include <algorithm> #include <cassert> #include <cstddef> #include <iterator> #include <string> namespace llvm { class FoldingSetNodeID; } // namespace llvm namespace clang { class ASTContext; class Attr; class CapturedDecl; class Decl; class Expr; class AddrLabelExpr; class LabelDecl; class ODRHash; class PrinterHelper; struct PrintingPolicy; class RecordDecl; class SourceManager; class StringLiteral; class Token; class VarDecl; //===----------------------------------------------------------------------===// // AST classes for statements. //===----------------------------------------------------------------------===// /// Stmt - This represents one statement. /// class alignas(void *) Stmt { public: enum StmtClass { NoStmtClass = 0, #define STMT(CLASS, PARENT) CLASS##Class, #define STMT_RANGE(BASE, FIRST, LAST) \ first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class, #define LAST_STMT_RANGE(BASE, FIRST, LAST) \ first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class #define ABSTRACT_STMT(STMT) #include "clang/AST/StmtNodes.inc" }; // Make vanilla 'new' and 'delete' illegal for Stmts. protected: friend class ASTStmtReader; friend class ASTStmtWriter; void *operator new(size_t bytes) noexcept { llvm_unreachable("Stmts cannot be allocated with regular 'new'."); } void operator delete(void *data) noexcept { llvm_unreachable("Stmts cannot be released with regular 'delete'."); } //===--- Statement bitfields classes ---===// class StmtBitfields { friend class ASTStmtReader; friend class ASTStmtWriter; friend class Stmt; /// The statement class. unsigned sClass : 8; }; enum { NumStmtBits = 8 }; class NullStmtBitfields { friend class ASTStmtReader; friend class ASTStmtWriter; friend class NullStmt; unsigned : NumStmtBits; /// True if the null statement was preceded by an empty macro, e.g: /// @code /// #define CALL(x) /// CALL(0); /// @endcode unsigned HasLeadingEmptyMacro : 1; /// The location of the semi-colon. SourceLocation SemiLoc; }; class CompoundStmtBitfields { friend class ASTStmtReader; friend class CompoundStmt; unsigned : NumStmtBits; unsigned NumStmts : 32 - NumStmtBits; /// The location of the opening "{". SourceLocation LBraceLoc; }; class LabelStmtBitfields { friend class LabelStmt; unsigned : NumStmtBits; SourceLocation IdentLoc; }; class AttributedStmtBitfields { friend class ASTStmtReader; friend class AttributedStmt; unsigned : NumStmtBits; /// Number of attributes. unsigned NumAttrs : 32 - NumStmtBits; /// The location of the attribute. SourceLocation AttrLoc; }; class IfStmtBitfields { friend class ASTStmtReader; friend class IfStmt; unsigned : NumStmtBits; /// True if this if statement is a constexpr if. unsigned IsConstexpr : 1; /// True if this if statement has storage for an else statement. unsigned HasElse : 1; /// True if this if statement has storage for a variable declaration. unsigned HasVar : 1; /// True if this if statement has storage for an init statement. unsigned HasInit : 1; /// The location of the "if". SourceLocation IfLoc; }; class SwitchStmtBitfields { friend class SwitchStmt; unsigned : NumStmtBits; /// True if the SwitchStmt has storage for an init statement. unsigned HasInit : 1; /// True if the SwitchStmt has storage for a condition variable. unsigned HasVar : 1; /// If the SwitchStmt is a switch on an enum value, records whether all /// the enum values were covered by CaseStmts. The coverage information /// value is meant to be a hint for possible clients. unsigned AllEnumCasesCovered : 1; /// The location of the "switch". SourceLocation SwitchLoc; }; class WhileStmtBitfields { friend class ASTStmtReader; friend class WhileStmt; unsigned : NumStmtBits; /// True if the WhileStmt has storage for a condition variable. unsigned HasVar : 1; /// The location of the "while". SourceLocation WhileLoc; }; class DoStmtBitfields { friend class DoStmt; unsigned : NumStmtBits; /// The location of the "do". SourceLocation DoLoc; }; class ForStmtBitfields { friend class ForStmt; unsigned : NumStmtBits; /// The location of the "for". SourceLocation ForLoc; }; class GotoStmtBitfields { friend class GotoStmt; friend class IndirectGotoStmt; unsigned : NumStmtBits; /// The location of the "goto". SourceLocation GotoLoc; }; class ContinueStmtBitfields { friend class ContinueStmt; unsigned : NumStmtBits; /// The location of the "continue". SourceLocation ContinueLoc; }; class BreakStmtBitfields { friend class BreakStmt; unsigned : NumStmtBits; /// The location of the "break". SourceLocation BreakLoc; }; class ReturnStmtBitfields { friend class ReturnStmt; unsigned : NumStmtBits; /// True if this ReturnStmt has storage for an NRVO candidate. unsigned HasNRVOCandidate : 1; /// The location of the "return". SourceLocation RetLoc; }; class SwitchCaseBitfields { friend class SwitchCase; friend class CaseStmt; unsigned : NumStmtBits; /// Used by CaseStmt to store whether it is a case statement /// of the form case LHS ... RHS (a GNU extension). unsigned CaseStmtIsGNURange : 1; /// The location of the "case" or "default" keyword. SourceLocation KeywordLoc; }; //===--- Expression bitfields classes ---===// class ExprBitfields { friend class ASTStmtReader; // deserialization friend class AtomicExpr; // ctor friend class BlockDeclRefExpr; // ctor friend class CallExpr; // ctor friend class CXXConstructExpr; // ctor friend class CXXDependentScopeMemberExpr; // ctor friend class CXXNewExpr; // ctor friend class CXXUnresolvedConstructExpr; // ctor friend class DeclRefExpr; // computeDependence friend class DependentScopeDeclRefExpr; // ctor friend class DesignatedInitExpr; // ctor friend class Expr; friend class InitListExpr; // ctor friend class ObjCArrayLiteral; // ctor friend class ObjCDictionaryLiteral; // ctor friend class ObjCMessageExpr; // ctor friend class OffsetOfExpr; // ctor friend class OpaqueValueExpr; // ctor friend class OverloadExpr; // ctor friend class ParenListExpr; // ctor friend class PseudoObjectExpr; // ctor friend class ShuffleVectorExpr; // ctor unsigned : NumStmtBits; unsigned ValueKind : 2; unsigned ObjectKind : 3; unsigned /*ExprDependence*/ Dependent : llvm::BitWidth<ExprDependence>; }; enum { NumExprBits = NumStmtBits + 5 + llvm::BitWidth<ExprDependence> }; class ConstantExprBitfields { friend class ASTStmtReader; friend class ASTStmtWriter; friend class ConstantExpr; unsigned : NumExprBits; /// The kind of result that is tail-allocated. unsigned ResultKind : 2; /// The kind of Result as defined by APValue::Kind. unsigned APValueKind : 4; /// When ResultKind == RSK_Int64, true if the tail-allocated integer is /// unsigned. unsigned IsUnsigned : 1; /// When ResultKind == RSK_Int64. the BitWidth of the tail-allocated /// integer. 7 bits because it is the minimal number of bits to represent a /// value from 0 to 64 (the size of the tail-allocated integer). unsigned BitWidth : 7; /// When ResultKind == RSK_APValue, true if the ASTContext will cleanup the /// tail-allocated APValue. unsigned HasCleanup : 1; /// True if this ConstantExpr was created for immediate invocation. unsigned IsImmediateInvocation : 1; }; class PredefinedExprBitfields { friend class ASTStmtReader; friend class PredefinedExpr; unsigned : NumExprBits; /// The kind of this PredefinedExpr. One of the enumeration values /// in PredefinedExpr::IdentKind. unsigned Kind : 4; /// True if this PredefinedExpr has a trailing "StringLiteral *" /// for the predefined identifier. unsigned HasFunctionName : 1; /// The location of this PredefinedExpr. SourceLocation Loc; }; class DeclRefExprBitfields { friend class ASTStmtReader; // deserialization friend class DeclRefExpr; unsigned : NumExprBits; unsigned HasQualifier : 1; unsigned HasTemplateKWAndArgsInfo : 1; unsigned HasFoundDecl : 1; unsigned HadMultipleCandidates : 1; unsigned RefersToEnclosingVariableOrCapture : 1; unsigned NonOdrUseReason : 2; /// The location of the declaration name itself. SourceLocation Loc; }; class FloatingLiteralBitfields { friend class FloatingLiteral; unsigned : NumExprBits; unsigned Semantics : 3; // Provides semantics for APFloat construction unsigned IsExact : 1; }; class StringLiteralBitfields { friend class ASTStmtReader; friend class StringLiteral; unsigned : NumExprBits; /// The kind of this string literal. /// One of the enumeration values of StringLiteral::StringKind. unsigned Kind : 3; /// The width of a single character in bytes. Only values of 1, 2, /// and 4 bytes are supported. StringLiteral::mapCharByteWidth maps /// the target + string kind to the appropriate CharByteWidth. unsigned CharByteWidth : 3; unsigned IsPascal : 1; /// The number of concatenated token this string is made of. /// This is the number of trailing SourceLocation. unsigned NumConcatenated; }; class CharacterLiteralBitfields { friend class CharacterLiteral; unsigned : NumExprBits; unsigned Kind : 3; }; class UnaryOperatorBitfields { friend class UnaryOperator; unsigned : NumExprBits; unsigned Opc : 5; unsigned CanOverflow : 1; // /// This is only meaningful for operations on floating point /// types when additional values need to be in trailing storage. /// It is 0 otherwise. unsigned HasFPFeatures : 1; SourceLocation Loc; }; class UnaryExprOrTypeTraitExprBitfields { friend class UnaryExprOrTypeTraitExpr; unsigned : NumExprBits; unsigned Kind : 3; unsigned IsType : 1; // true if operand is a type, false if an expression. }; class ArrayOrMatrixSubscriptExprBitfields { friend class ArraySubscriptExpr; friend class MatrixSubscriptExpr; unsigned : NumExprBits; SourceLocation RBracketLoc; }; class CallExprBitfields { friend class CallExpr; unsigned : NumExprBits; unsigned NumPreArgs : 1; /// True if the callee of the call expression was found using ADL. unsigned UsesADL : 1; /// Padding used to align OffsetToTrailingObjects to a byte multiple. unsigned : 24 - 2 - NumExprBits; /// The offset in bytes from the this pointer to the start of the /// trailing objects belonging to CallExpr. Intentionally byte sized /// for faster access. unsigned OffsetToTrailingObjects : 8; }; enum { NumCallExprBits = 32 }; class MemberExprBitfields { friend class ASTStmtReader; friend class MemberExpr; unsigned : NumExprBits; /// IsArrow - True if this is "X->F", false if this is "X.F". unsigned IsArrow : 1; /// True if this member expression used a nested-name-specifier to /// refer to the member, e.g., "x->Base::f", or found its member via /// a using declaration. When true, a MemberExprNameQualifier /// structure is allocated immediately after the MemberExpr. unsigned HasQualifierOrFoundDecl : 1; /// True if this member expression specified a template keyword /// and/or a template argument list explicitly, e.g., x->f<int>, /// x->template f, x->template f<int>. /// When true, an ASTTemplateKWAndArgsInfo structure and its /// TemplateArguments (if any) are present. unsigned HasTemplateKWAndArgsInfo : 1; /// True if this member expression refers to a method that /// was resolved from an overloaded set having size greater than 1. unsigned HadMultipleCandidates : 1; /// Value of type NonOdrUseReason indicating why this MemberExpr does /// not constitute an odr-use of the named declaration. Meaningful only /// when naming a static member. unsigned NonOdrUseReason : 2; /// This is the location of the -> or . in the expression. SourceLocation OperatorLoc; }; class CastExprBitfields { friend class CastExpr; friend class ImplicitCastExpr; unsigned : NumExprBits; unsigned Kind : 6; unsigned PartOfExplicitCast : 1; // Only set for ImplicitCastExpr. /// The number of CXXBaseSpecifiers in the cast. 14 bits would be enough /// here. ([implimits] Direct and indirect base classes [16384]). unsigned BasePathSize; }; class BinaryOperatorBitfields { friend class BinaryOperator; unsigned : NumExprBits; unsigned Opc : 6; /// This is only meaningful for operations on floating point /// types when additional values need to be in trailing storage. /// It is 0 otherwise. unsigned HasFPFeatures : 1; SourceLocation OpLoc; }; class InitListExprBitfields { friend class InitListExpr; unsigned : NumExprBits; /// Whether this initializer list originally had a GNU array-range /// designator in it. This is a temporary marker used by CodeGen. unsigned HadArrayRangeDesignator : 1; }; class ParenListExprBitfields { friend class ASTStmtReader; friend class ParenListExpr; unsigned : NumExprBits; /// The number of expressions in the paren list. unsigned NumExprs; }; class GenericSelectionExprBitfields { friend class ASTStmtReader; friend class GenericSelectionExpr; unsigned : NumExprBits; /// The location of the "_Generic". SourceLocation GenericLoc; }; class PseudoObjectExprBitfields { friend class ASTStmtReader; // deserialization friend class PseudoObjectExpr; unsigned : NumExprBits; // These don't need to be particularly wide, because they're // strictly limited by the forms of expressions we permit. unsigned NumSubExprs : 8; unsigned ResultIndex : 32 - 8 - NumExprBits; }; class SourceLocExprBitfields { friend class ASTStmtReader; friend class SourceLocExpr; unsigned : NumExprBits; /// The kind of source location builtin represented by the SourceLocExpr. /// Ex. __builtin_LINE, __builtin_FUNCTION, ect. unsigned Kind : 2; }; class StmtExprBitfields { friend class ASTStmtReader; friend class StmtExpr; unsigned : NumExprBits; /// The number of levels of template parameters enclosing this statement /// expression. Used to determine if a statement expression remains /// dependent after instantiation. unsigned TemplateDepth; }; //===--- C++ Expression bitfields classes ---===// class CXXOperatorCallExprBitfields { friend class ASTStmtReader; friend class CXXOperatorCallExpr; unsigned : NumCallExprBits; /// The kind of this overloaded operator. One of the enumerator /// value of OverloadedOperatorKind. unsigned OperatorKind : 6; }; class CXXRewrittenBinaryOperatorBitfields { friend class ASTStmtReader; friend class CXXRewrittenBinaryOperator; unsigned : NumCallExprBits; unsigned IsReversed : 1; }; class CXXBoolLiteralExprBitfields { friend class CXXBoolLiteralExpr; unsigned : NumExprBits; /// The value of the boolean literal. unsigned Value : 1; /// The location of the boolean literal. SourceLocation Loc; }; class CXXNullPtrLiteralExprBitfields { friend class CXXNullPtrLiteralExpr; unsigned : NumExprBits; /// The location of the null pointer literal. SourceLocation Loc; }; class CXXThisExprBitfields { friend class CXXThisExpr; unsigned : NumExprBits; /// Whether this is an implicit "this". unsigned IsImplicit : 1; /// The location of the "this". SourceLocation Loc; }; class CXXThrowExprBitfields { friend class ASTStmtReader; friend class CXXThrowExpr; unsigned : NumExprBits; /// Whether the thrown variable (if any) is in scope. unsigned IsThrownVariableInScope : 1; /// The location of the "throw". SourceLocation ThrowLoc; }; class CXXDefaultArgExprBitfields { friend class ASTStmtReader; friend class CXXDefaultArgExpr; unsigned : NumExprBits; /// The location where the default argument expression was used. SourceLocation Loc; }; class CXXDefaultInitExprBitfields { friend class ASTStmtReader; friend class CXXDefaultInitExpr; unsigned : NumExprBits; /// The location where the default initializer expression was used. SourceLocation Loc; }; class CXXScalarValueInitExprBitfields { friend class ASTStmtReader; friend class CXXScalarValueInitExpr; unsigned : NumExprBits; SourceLocation RParenLoc; }; class CXXNewExprBitfields { friend class ASTStmtReader; friend class ASTStmtWriter; friend class CXXNewExpr; unsigned : NumExprBits; /// Was the usage ::new, i.e. is the global new to be used? unsigned IsGlobalNew : 1; /// Do we allocate an array? If so, the first trailing "Stmt *" is the /// size expression. unsigned IsArray : 1; /// Should the alignment be passed to the allocation function? unsigned ShouldPassAlignment : 1; /// If this is an array allocation, does the usual deallocation /// function for the allocated type want to know the allocated size? unsigned UsualArrayDeleteWantsSize : 1; /// What kind of initializer do we have? Could be none, parens, or braces. /// In storage, we distinguish between "none, and no initializer expr", and /// "none, but an implicit initializer expr". unsigned StoredInitializationStyle : 2; /// True if the allocated type was expressed as a parenthesized type-id. unsigned IsParenTypeId : 1; /// The number of placement new arguments. unsigned NumPlacementArgs; }; class CXXDeleteExprBitfields { friend class ASTStmtReader; friend class CXXDeleteExpr; unsigned : NumExprBits; /// Is this a forced global delete, i.e. "::delete"? unsigned GlobalDelete : 1; /// Is this the array form of delete, i.e. "delete[]"? unsigned ArrayForm : 1; /// ArrayFormAsWritten can be different from ArrayForm if 'delete' is /// applied to pointer-to-array type (ArrayFormAsWritten will be false /// while ArrayForm will be true). unsigned ArrayFormAsWritten : 1; /// Does the usual deallocation function for the element type require /// a size_t argument? unsigned UsualArrayDeleteWantsSize : 1; /// Location of the expression. SourceLocation Loc; }; class TypeTraitExprBitfields { friend class ASTStmtReader; friend class ASTStmtWriter; friend class TypeTraitExpr; unsigned : NumExprBits; /// The kind of type trait, which is a value of a TypeTrait enumerator. unsigned Kind : 8; /// If this expression is not value-dependent, this indicates whether /// the trait evaluated true or false. unsigned Value : 1; /// The number of arguments to this type trait. According to [implimits] /// 8 bits would be enough, but we require (and test for) at least 16 bits /// to mirror FunctionType. unsigned NumArgs; }; class DependentScopeDeclRefExprBitfields { friend class ASTStmtReader; friend class ASTStmtWriter; friend class DependentScopeDeclRefExpr; unsigned : NumExprBits; /// Whether the name includes info for explicit template /// keyword and arguments. unsigned HasTemplateKWAndArgsInfo : 1; }; class CXXConstructExprBitfields { friend class ASTStmtReader; friend class CXXConstructExpr; unsigned : NumExprBits; unsigned Elidable : 1; unsigned HadMultipleCandidates : 1; unsigned ListInitialization : 1; unsigned StdInitListInitialization : 1; unsigned ZeroInitialization : 1; unsigned ConstructionKind : 3; SourceLocation Loc; }; class ExprWithCleanupsBitfields { friend class ASTStmtReader; // deserialization friend class ExprWithCleanups; unsigned : NumExprBits; // When false, it must not have side effects. unsigned CleanupsHaveSideEffects : 1; unsigned NumObjects : 32 - 1 - NumExprBits; }; class CXXUnresolvedConstructExprBitfields { friend class ASTStmtReader; friend class CXXUnresolvedConstructExpr; unsigned : NumExprBits; /// The number of arguments used to construct the type. unsigned NumArgs; }; class CXXDependentScopeMemberExprBitfields { friend class ASTStmtReader; friend class CXXDependentScopeMemberExpr; unsigned : NumExprBits; /// Whether this member expression used the '->' operator or /// the '.' operator. unsigned IsArrow : 1; /// Whether this member expression has info for explicit template /// keyword and arguments. unsigned HasTemplateKWAndArgsInfo : 1; /// See getFirstQualifierFoundInScope() and the comment listing /// the trailing objects. unsigned HasFirstQualifierFoundInScope : 1; /// The location of the '->' or '.' operator. SourceLocation OperatorLoc; }; class OverloadExprBitfields { friend class ASTStmtReader; friend class OverloadExpr; unsigned : NumExprBits; /// Whether the name includes info for explicit template /// keyword and arguments. unsigned HasTemplateKWAndArgsInfo : 1; /// Padding used by the derived classes to store various bits. If you /// need to add some data here, shrink this padding and add your data /// above. NumOverloadExprBits also needs to be updated. unsigned : 32 - NumExprBits - 1; /// The number of results. unsigned NumResults; }; enum { NumOverloadExprBits = NumExprBits + 1 }; class UnresolvedLookupExprBitfields { friend class ASTStmtReader; friend class UnresolvedLookupExpr; unsigned : NumOverloadExprBits; /// True if these lookup results should be extended by /// argument-dependent lookup if this is the operand of a function call. unsigned RequiresADL : 1; /// True if these lookup results are overloaded. This is pretty trivially /// rederivable if we urgently need to kill this field. unsigned Overloaded : 1; }; static_assert(sizeof(UnresolvedLookupExprBitfields) <= 4, "UnresolvedLookupExprBitfields must be <= than 4 bytes to" "avoid trashing OverloadExprBitfields::NumResults!"); class UnresolvedMemberExprBitfields { friend class ASTStmtReader; friend class UnresolvedMemberExpr; unsigned : NumOverloadExprBits; /// Whether this member expression used the '->' operator or /// the '.' operator. unsigned IsArrow : 1; /// Whether the lookup results contain an unresolved using declaration. unsigned HasUnresolvedUsing : 1; }; static_assert(sizeof(UnresolvedMemberExprBitfields) <= 4, "UnresolvedMemberExprBitfields must be <= than 4 bytes to" "avoid trashing OverloadExprBitfields::NumResults!"); class CXXNoexceptExprBitfields { friend class ASTStmtReader; friend class CXXNoexceptExpr; unsigned : NumExprBits; unsigned Value : 1; }; class SubstNonTypeTemplateParmExprBitfields { friend class ASTStmtReader; friend class SubstNonTypeTemplateParmExpr; unsigned : NumExprBits; /// The location of the non-type template parameter reference. SourceLocation NameLoc; }; class LambdaExprBitfields { friend class ASTStmtReader; friend class ASTStmtWriter; friend class LambdaExpr; unsigned : NumExprBits; /// The default capture kind, which is a value of type /// LambdaCaptureDefault. unsigned CaptureDefault : 2; /// Whether this lambda had an explicit parameter list vs. an /// implicit (and empty) parameter list. unsigned ExplicitParams : 1; /// Whether this lambda had the result type explicitly specified. unsigned ExplicitResultType : 1; /// The number of captures. unsigned NumCaptures : 16; }; class RequiresExprBitfields { friend class ASTStmtReader; friend class ASTStmtWriter; friend class RequiresExpr; unsigned : NumExprBits; unsigned IsSatisfied : 1; SourceLocation RequiresKWLoc; }; //===--- C++ Coroutines TS bitfields classes ---===// class CoawaitExprBitfields { friend class CoawaitExpr; unsigned : NumExprBits; unsigned IsImplicit : 1; }; //===--- Obj-C Expression bitfields classes ---===// class ObjCIndirectCopyRestoreExprBitfields { friend class ObjCIndirectCopyRestoreExpr; unsigned : NumExprBits; unsigned ShouldCopy : 1; }; //===--- Clang Extensions bitfields classes ---===// class OpaqueValueExprBitfields { friend class ASTStmtReader; friend class OpaqueValueExpr; unsigned : NumExprBits; /// The OVE is a unique semantic reference to its source expression if this /// bit is set to true. unsigned IsUnique : 1; SourceLocation Loc; }; union { // Same order as in StmtNodes.td. // Statements StmtBitfields StmtBits; NullStmtBitfields NullStmtBits; CompoundStmtBitfields CompoundStmtBits; LabelStmtBitfields LabelStmtBits; AttributedStmtBitfields AttributedStmtBits; IfStmtBitfields IfStmtBits; SwitchStmtBitfields SwitchStmtBits; WhileStmtBitfields WhileStmtBits; DoStmtBitfields DoStmtBits; ForStmtBitfields ForStmtBits; GotoStmtBitfields GotoStmtBits; ContinueStmtBitfields ContinueStmtBits; BreakStmtBitfields BreakStmtBits; ReturnStmtBitfields ReturnStmtBits; SwitchCaseBitfields SwitchCaseBits; // Expressions ExprBitfields ExprBits; ConstantExprBitfields ConstantExprBits; PredefinedExprBitfields PredefinedExprBits; DeclRefExprBitfields DeclRefExprBits; FloatingLiteralBitfields FloatingLiteralBits; StringLiteralBitfields StringLiteralBits; CharacterLiteralBitfields CharacterLiteralBits; UnaryOperatorBitfields UnaryOperatorBits; UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits; ArrayOrMatrixSubscriptExprBitfields ArrayOrMatrixSubscriptExprBits; CallExprBitfields CallExprBits; MemberExprBitfields MemberExprBits; CastExprBitfields CastExprBits; BinaryOperatorBitfields BinaryOperatorBits; InitListExprBitfields InitListExprBits; ParenListExprBitfields ParenListExprBits; GenericSelectionExprBitfields GenericSelectionExprBits; PseudoObjectExprBitfields PseudoObjectExprBits; SourceLocExprBitfields SourceLocExprBits; // GNU Extensions. StmtExprBitfields StmtExprBits; // C++ Expressions CXXOperatorCallExprBitfields CXXOperatorCallExprBits; CXXRewrittenBinaryOperatorBitfields CXXRewrittenBinaryOperatorBits; CXXBoolLiteralExprBitfields CXXBoolLiteralExprBits; CXXNullPtrLiteralExprBitfields CXXNullPtrLiteralExprBits; CXXThisExprBitfields CXXThisExprBits; CXXThrowExprBitfields CXXThrowExprBits; CXXDefaultArgExprBitfields CXXDefaultArgExprBits; CXXDefaultInitExprBitfields CXXDefaultInitExprBits; CXXScalarValueInitExprBitfields CXXScalarValueInitExprBits; CXXNewExprBitfields CXXNewExprBits; CXXDeleteExprBitfields CXXDeleteExprBits; TypeTraitExprBitfields TypeTraitExprBits; DependentScopeDeclRefExprBitfields DependentScopeDeclRefExprBits; CXXConstructExprBitfields CXXConstructExprBits; ExprWithCleanupsBitfields ExprWithCleanupsBits; CXXUnresolvedConstructExprBitfields CXXUnresolvedConstructExprBits; CXXDependentScopeMemberExprBitfields CXXDependentScopeMemberExprBits; OverloadExprBitfields OverloadExprBits; UnresolvedLookupExprBitfields UnresolvedLookupExprBits; UnresolvedMemberExprBitfields UnresolvedMemberExprBits; CXXNoexceptExprBitfields CXXNoexceptExprBits; SubstNonTypeTemplateParmExprBitfields SubstNonTypeTemplateParmExprBits; LambdaExprBitfields LambdaExprBits; RequiresExprBitfields RequiresExprBits; // C++ Coroutines TS expressions CoawaitExprBitfields CoawaitBits; // Obj-C Expressions ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits; // Clang Extensions OpaqueValueExprBitfields OpaqueValueExprBits; }; public: // Only allow allocation of Stmts using the allocator in ASTContext // or by doing a placement new. void* operator new(size_t bytes, const ASTContext& C, unsigned alignment = 8); void* operator new(size_t bytes, const ASTContext* C, unsigned alignment = 8) { return operator new(bytes, *C, alignment); } void *operator new(size_t bytes, void *mem) noexcept { return mem; } void operator delete(void *, const ASTContext &, unsigned) noexcept {} void operator delete(void *, const ASTContext *, unsigned) noexcept {} void operator delete(void *, size_t) noexcept {} void operator delete(void *, void *) noexcept {} public: /// A placeholder type used to construct an empty shell of a /// type, that will be filled in later (e.g., by some /// de-serialization). struct EmptyShell {}; protected: /// Iterator for iterating over Stmt * arrays that contain only T *. /// /// This is needed because AST nodes use Stmt* arrays to store /// references to children (to be compatible with StmtIterator). template<typename T, typename TPtr = T *, typename StmtPtr = Stmt *> struct CastIterator : llvm::iterator_adaptor_base<CastIterator<T, TPtr, StmtPtr>, StmtPtr *, std::random_access_iterator_tag, TPtr> { using Base = typename CastIterator::iterator_adaptor_base; CastIterator() : Base(nullptr) {} CastIterator(StmtPtr *I) : Base(I) {} typename Base::value_type operator*() const { return cast_or_null<T>(*this->I); } }; /// Const iterator for iterating over Stmt * arrays that contain only T *. template <typename T> using ConstCastIterator = CastIterator<T, const T *const, const Stmt *const>; using ExprIterator = CastIterator<Expr>; using ConstExprIterator = ConstCastIterator<Expr>; private: /// Whether statistic collection is enabled. static bool StatisticsEnabled; protected: /// Construct an empty statement. explicit Stmt(StmtClass SC, EmptyShell) : Stmt(SC) {} public: Stmt() = delete; Stmt(const Stmt &) = delete; Stmt(Stmt &&) = delete; Stmt &operator=(const Stmt &) = delete; Stmt &operator=(Stmt &&) = delete; Stmt(StmtClass SC) { static_assert(sizeof(*this) <= 8, "changing bitfields changed sizeof(Stmt)"); static_assert(sizeof(*this) % alignof(void *) == 0, "Insufficient alignment!"); StmtBits.sClass = SC; if (StatisticsEnabled) Stmt::addStmtClass(SC); } StmtClass getStmtClass() const { return static_cast<StmtClass>(StmtBits.sClass); } const char *getStmtClassName() const; /// SourceLocation tokens are not useful in isolation - they are low level /// value objects created/interpreted by SourceManager. We assume AST /// clients will have a pointer to the respective SourceManager. SourceRange getSourceRange() const LLVM_READONLY; SourceLocation getBeginLoc() const LLVM_READONLY; SourceLocation getEndLoc() const LLVM_READONLY; // global temp stats (until we have a per-module visitor) static void addStmtClass(const StmtClass s); static void EnableStatistics(); static void PrintStats(); /// Dumps the specified AST fragment and all subtrees to /// \c llvm::errs(). void dump() const; void dump(raw_ostream &OS, const ASTContext &Context) const; /// \return Unique reproducible object identifier int64_t getID(const ASTContext &Context) const; /// dumpColor - same as dump(), but forces color highlighting. void dumpColor() const; /// dumpPretty/printPretty - These two methods do a "pretty print" of the AST /// back to its original source language syntax. void dumpPretty(const ASTContext &Context) const; void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation = 0, StringRef NewlineSymbol = "\n", const ASTContext *Context = nullptr) const; /// Pretty-prints in JSON format. void printJson(raw_ostream &Out, PrinterHelper *Helper, const PrintingPolicy &Policy, bool AddQuotes) const; /// viewAST - Visualize an AST rooted at this Stmt* using GraphViz. Only /// works on systems with GraphViz (Mac OS X) or dot+gv installed. void viewAST() const; /// Skip no-op (attributed, compound) container stmts and skip captured /// stmt at the top, if \a IgnoreCaptured is true. Stmt *IgnoreContainers(bool IgnoreCaptured = false); const Stmt *IgnoreContainers(bool IgnoreCaptured = false) const { return const_cast<Stmt *>(this)->IgnoreContainers(IgnoreCaptured); } const Stmt *stripLabelLikeStatements() const; Stmt *stripLabelLikeStatements() { return const_cast<Stmt*>( const_cast<const Stmt*>(this)->stripLabelLikeStatements()); } /// Child Iterators: All subclasses must implement 'children' /// to permit easy iteration over the substatements/subexpessions of an /// AST node. This permits easy iteration over all nodes in the AST. using child_iterator = StmtIterator; using const_child_iterator = ConstStmtIterator; using child_range = llvm::iterator_range<child_iterator>; using const_child_range = llvm::iterator_range<const_child_iterator>; child_range children(); const_child_range children() const { auto Children = const_cast<Stmt *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_iterator child_begin() { return children().begin(); } child_iterator child_end() { return children().end(); } const_child_iterator child_begin() const { return children().begin(); } const_child_iterator child_end() const { return children().end(); } /// Produce a unique representation of the given statement. /// /// \param ID once the profiling operation is complete, will contain /// the unique representation of the given statement. /// /// \param Context the AST context in which the statement resides /// /// \param Canonical whether the profile should be based on the canonical /// representation of this statement (e.g., where non-type template /// parameters are identified by index/level rather than their /// declaration pointers) or the exact representation of the statement as /// written in the source. void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const; /// Calculate a unique representation for a statement that is /// stable across compiler invocations. /// /// \param ID profile information will be stored in ID. /// /// \param Hash an ODRHash object which will be called where pointers would /// have been used in the Profile function. void ProcessODRHash(llvm::FoldingSetNodeID &ID, ODRHash& Hash) const; }; /// DeclStmt - Adaptor class for mixing declarations with statements and /// expressions. For example, CompoundStmt mixes statements, expressions /// and declarations (variables, types). Another example is ForStmt, where /// the first statement can be an expression or a declaration. class DeclStmt : public Stmt { DeclGroupRef DG; SourceLocation StartLoc, EndLoc; public: DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc) : Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {} /// Build an empty declaration statement. explicit DeclStmt(EmptyShell Empty) : Stmt(DeclStmtClass, Empty) {} /// isSingleDecl - This method returns true if this DeclStmt refers /// to a single Decl. bool isSingleDecl() const { return DG.isSingleDecl(); } const Decl *getSingleDecl() const { return DG.getSingleDecl(); } Decl *getSingleDecl() { return DG.getSingleDecl(); } const DeclGroupRef getDeclGroup() const { return DG; } DeclGroupRef getDeclGroup() { return DG; } void setDeclGroup(DeclGroupRef DGR) { DG = DGR; } void setStartLoc(SourceLocation L) { StartLoc = L; } SourceLocation getEndLoc() const { return EndLoc; } void setEndLoc(SourceLocation L) { EndLoc = L; } SourceLocation getBeginLoc() const LLVM_READONLY { return StartLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == DeclStmtClass; } // Iterators over subexpressions. child_range children() { return child_range(child_iterator(DG.begin(), DG.end()), child_iterator(DG.end(), DG.end())); } const_child_range children() const { auto Children = const_cast<DeclStmt *>(this)->children(); return const_child_range(Children); } using decl_iterator = DeclGroupRef::iterator; using const_decl_iterator = DeclGroupRef::const_iterator; using decl_range = llvm::iterator_range<decl_iterator>; using decl_const_range = llvm::iterator_range<const_decl_iterator>; decl_range decls() { return decl_range(decl_begin(), decl_end()); } decl_const_range decls() const { return decl_const_range(decl_begin(), decl_end()); } decl_iterator decl_begin() { return DG.begin(); } decl_iterator decl_end() { return DG.end(); } const_decl_iterator decl_begin() const { return DG.begin(); } const_decl_iterator decl_end() const { return DG.end(); } using reverse_decl_iterator = std::reverse_iterator<decl_iterator>; reverse_decl_iterator decl_rbegin() { return reverse_decl_iterator(decl_end()); } reverse_decl_iterator decl_rend() { return reverse_decl_iterator(decl_begin()); } }; /// NullStmt - This is the null statement ";": C99 6.8.3p3. /// class NullStmt : public Stmt { public: NullStmt(SourceLocation L, bool hasLeadingEmptyMacro = false) : Stmt(NullStmtClass) { NullStmtBits.HasLeadingEmptyMacro = hasLeadingEmptyMacro; setSemiLoc(L); } /// Build an empty null statement. explicit NullStmt(EmptyShell Empty) : Stmt(NullStmtClass, Empty) {} SourceLocation getSemiLoc() const { return NullStmtBits.SemiLoc; } void setSemiLoc(SourceLocation L) { NullStmtBits.SemiLoc = L; } bool hasLeadingEmptyMacro() const { return NullStmtBits.HasLeadingEmptyMacro; } SourceLocation getBeginLoc() const { return getSemiLoc(); } SourceLocation getEndLoc() const { return getSemiLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == NullStmtClass; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// CompoundStmt - This represents a group of statements like { stmt stmt }. class CompoundStmt final : public Stmt, private llvm::TrailingObjects<CompoundStmt, Stmt *> { friend class ASTStmtReader; friend TrailingObjects; /// The location of the closing "}". LBraceLoc is stored in CompoundStmtBits. SourceLocation RBraceLoc; CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB, SourceLocation RB); explicit CompoundStmt(EmptyShell Empty) : Stmt(CompoundStmtClass, Empty) {} void setStmts(ArrayRef<Stmt *> Stmts); public: static CompoundStmt *Create(const ASTContext &C, ArrayRef<Stmt *> Stmts, SourceLocation LB, SourceLocation RB); // Build an empty compound statement with a location. explicit CompoundStmt(SourceLocation Loc) : Stmt(CompoundStmtClass), RBraceLoc(Loc) { CompoundStmtBits.NumStmts = 0; CompoundStmtBits.LBraceLoc = Loc; } // Build an empty compound statement. static CompoundStmt *CreateEmpty(const ASTContext &C, unsigned NumStmts); bool body_empty() const { return CompoundStmtBits.NumStmts == 0; } unsigned size() const { return CompoundStmtBits.NumStmts; } using body_iterator = Stmt **; using body_range = llvm::iterator_range<body_iterator>; body_range body() { return body_range(body_begin(), body_end()); } body_iterator body_begin() { return getTrailingObjects<Stmt *>(); } body_iterator body_end() { return body_begin() + size(); } Stmt *body_front() { return !body_empty() ? body_begin()[0] : nullptr; } Stmt *body_back() { return !body_empty() ? body_begin()[size() - 1] : nullptr; } using const_body_iterator = Stmt *const *; using body_const_range = llvm::iterator_range<const_body_iterator>; body_const_range body() const { return body_const_range(body_begin(), body_end()); } const_body_iterator body_begin() const { return getTrailingObjects<Stmt *>(); } const_body_iterator body_end() const { return body_begin() + size(); } const Stmt *body_front() const { return !body_empty() ? body_begin()[0] : nullptr; } const Stmt *body_back() const { return !body_empty() ? body_begin()[size() - 1] : nullptr; } using reverse_body_iterator = std::reverse_iterator<body_iterator>; reverse_body_iterator body_rbegin() { return reverse_body_iterator(body_end()); } reverse_body_iterator body_rend() { return reverse_body_iterator(body_begin()); } using const_reverse_body_iterator = std::reverse_iterator<const_body_iterator>; const_reverse_body_iterator body_rbegin() const { return const_reverse_body_iterator(body_end()); } const_reverse_body_iterator body_rend() const { return const_reverse_body_iterator(body_begin()); } // Get the Stmt that StmtExpr would consider to be the result of this // compound statement. This is used by StmtExpr to properly emulate the GCC // compound expression extension, which ignores trailing NullStmts when // getting the result of the expression. // i.e. ({ 5;;; }) // ^^ ignored // If we don't find something that isn't a NullStmt, just return the last // Stmt. Stmt *getStmtExprResult() { for (auto *B : llvm::reverse(body())) { if (!isa<NullStmt>(B)) return B; } return body_back(); } const Stmt *getStmtExprResult() const { return const_cast<CompoundStmt *>(this)->getStmtExprResult(); } SourceLocation getBeginLoc() const { return CompoundStmtBits.LBraceLoc; } SourceLocation getEndLoc() const { return RBraceLoc; } SourceLocation getLBracLoc() const { return CompoundStmtBits.LBraceLoc; } SourceLocation getRBracLoc() const { return RBraceLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == CompoundStmtClass; } // Iterators child_range children() { return child_range(body_begin(), body_end()); } const_child_range children() const { return const_child_range(body_begin(), body_end()); } }; // SwitchCase is the base class for CaseStmt and DefaultStmt, class SwitchCase : public Stmt { protected: /// The location of the ":". SourceLocation ColonLoc; // The location of the "case" or "default" keyword. Stored in SwitchCaseBits. // SourceLocation KeywordLoc; /// A pointer to the following CaseStmt or DefaultStmt class, /// used by SwitchStmt. SwitchCase *NextSwitchCase = nullptr; SwitchCase(StmtClass SC, SourceLocation KWLoc, SourceLocation ColonLoc) : Stmt(SC), ColonLoc(ColonLoc) { setKeywordLoc(KWLoc); } SwitchCase(StmtClass SC, EmptyShell) : Stmt(SC) {} public: const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; } SwitchCase *getNextSwitchCase() { return NextSwitchCase; } void setNextSwitchCase(SwitchCase *SC) { NextSwitchCase = SC; } SourceLocation getKeywordLoc() const { return SwitchCaseBits.KeywordLoc; } void setKeywordLoc(SourceLocation L) { SwitchCaseBits.KeywordLoc = L; } SourceLocation getColonLoc() const { return ColonLoc; } void setColonLoc(SourceLocation L) { ColonLoc = L; } inline Stmt *getSubStmt(); const Stmt *getSubStmt() const { return const_cast<SwitchCase *>(this)->getSubStmt(); } SourceLocation getBeginLoc() const { return getKeywordLoc(); } inline SourceLocation getEndLoc() const LLVM_READONLY; static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass || T->getStmtClass() == DefaultStmtClass; } }; /// CaseStmt - Represent a case statement. It can optionally be a GNU case /// statement of the form LHS ... RHS representing a range of cases. class CaseStmt final : public SwitchCase, private llvm::TrailingObjects<CaseStmt, Stmt *, SourceLocation> { friend TrailingObjects; // CaseStmt is followed by several trailing objects, some of which optional. // Note that it would be more convenient to put the optional trailing objects // at the end but this would impact children(). // The trailing objects are in order: // // * A "Stmt *" for the LHS of the case statement. Always present. // // * A "Stmt *" for the RHS of the case statement. This is a GNU extension // which allow ranges in cases statement of the form LHS ... RHS. // Present if and only if caseStmtIsGNURange() is true. // // * A "Stmt *" for the substatement of the case statement. Always present. // // * A SourceLocation for the location of the ... if this is a case statement // with a range. Present if and only if caseStmtIsGNURange() is true. enum { LhsOffset = 0, SubStmtOffsetFromRhs = 1 }; enum { NumMandatoryStmtPtr = 2 }; unsigned numTrailingObjects(OverloadToken<Stmt *>) const { return NumMandatoryStmtPtr + caseStmtIsGNURange(); } unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { return caseStmtIsGNURange(); } unsigned lhsOffset() const { return LhsOffset; } unsigned rhsOffset() const { return LhsOffset + caseStmtIsGNURange(); } unsigned subStmtOffset() const { return rhsOffset() + SubStmtOffsetFromRhs; } /// Build a case statement assuming that the storage for the /// trailing objects has been properly allocated. CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc, SourceLocation ellipsisLoc, SourceLocation colonLoc) : SwitchCase(CaseStmtClass, caseLoc, colonLoc) { // Handle GNU case statements of the form LHS ... RHS. bool IsGNURange = rhs != nullptr; SwitchCaseBits.CaseStmtIsGNURange = IsGNURange; setLHS(lhs); setSubStmt(nullptr); if (IsGNURange) { setRHS(rhs); setEllipsisLoc(ellipsisLoc); } } /// Build an empty switch case statement. explicit CaseStmt(EmptyShell Empty, bool CaseStmtIsGNURange) : SwitchCase(CaseStmtClass, Empty) { SwitchCaseBits.CaseStmtIsGNURange = CaseStmtIsGNURange; } public: /// Build a case statement. static CaseStmt *Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs, SourceLocation caseLoc, SourceLocation ellipsisLoc, SourceLocation colonLoc); /// Build an empty case statement. static CaseStmt *CreateEmpty(const ASTContext &Ctx, bool CaseStmtIsGNURange); /// True if this case statement is of the form case LHS ... RHS, which /// is a GNU extension. In this case the RHS can be obtained with getRHS() /// and the location of the ellipsis can be obtained with getEllipsisLoc(). bool caseStmtIsGNURange() const { return SwitchCaseBits.CaseStmtIsGNURange; } SourceLocation getCaseLoc() const { return getKeywordLoc(); } void setCaseLoc(SourceLocation L) { setKeywordLoc(L); } /// Get the location of the ... in a case statement of the form LHS ... RHS. SourceLocation getEllipsisLoc() const { return caseStmtIsGNURange() ? *getTrailingObjects<SourceLocation>() : SourceLocation(); } /// Set the location of the ... in a case statement of the form LHS ... RHS. /// Assert that this case statement is of this form. void setEllipsisLoc(SourceLocation L) { assert( caseStmtIsGNURange() && "setEllipsisLoc but this is not a case stmt of the form LHS ... RHS!"); *getTrailingObjects<SourceLocation>() = L; } Expr *getLHS() { return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]); } const Expr *getLHS() const { return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]); } void setLHS(Expr *Val) { getTrailingObjects<Stmt *>()[lhsOffset()] = reinterpret_cast<Stmt *>(Val); } Expr *getRHS() { return caseStmtIsGNURange() ? reinterpret_cast<Expr *>( getTrailingObjects<Stmt *>()[rhsOffset()]) : nullptr; } const Expr *getRHS() const { return caseStmtIsGNURange() ? reinterpret_cast<Expr *>( getTrailingObjects<Stmt *>()[rhsOffset()]) : nullptr; } void setRHS(Expr *Val) { assert(caseStmtIsGNURange() && "setRHS but this is not a case stmt of the form LHS ... RHS!"); getTrailingObjects<Stmt *>()[rhsOffset()] = reinterpret_cast<Stmt *>(Val); } Stmt *getSubStmt() { return getTrailingObjects<Stmt *>()[subStmtOffset()]; } const Stmt *getSubStmt() const { return getTrailingObjects<Stmt *>()[subStmtOffset()]; } void setSubStmt(Stmt *S) { getTrailingObjects<Stmt *>()[subStmtOffset()] = S; } SourceLocation getBeginLoc() const { return getKeywordLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { // Handle deeply nested case statements with iteration instead of recursion. const CaseStmt *CS = this; while (const auto *CS2 = dyn_cast<CaseStmt>(CS->getSubStmt())) CS = CS2; return CS->getSubStmt()->getEndLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass; } // Iterators child_range children() { return child_range(getTrailingObjects<Stmt *>(), getTrailingObjects<Stmt *>() + numTrailingObjects(OverloadToken<Stmt *>())); } const_child_range children() const { return const_child_range(getTrailingObjects<Stmt *>(), getTrailingObjects<Stmt *>() + numTrailingObjects(OverloadToken<Stmt *>())); } }; class DefaultStmt : public SwitchCase { Stmt *SubStmt; public: DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt) : SwitchCase(DefaultStmtClass, DL, CL), SubStmt(substmt) {} /// Build an empty default statement. explicit DefaultStmt(EmptyShell Empty) : SwitchCase(DefaultStmtClass, Empty) {} Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } void setSubStmt(Stmt *S) { SubStmt = S; } SourceLocation getDefaultLoc() const { return getKeywordLoc(); } void setDefaultLoc(SourceLocation L) { setKeywordLoc(L); } SourceLocation getBeginLoc() const { return getKeywordLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == DefaultStmtClass; } // Iterators child_range children() { return child_range(&SubStmt, &SubStmt + 1); } const_child_range children() const { return const_child_range(&SubStmt, &SubStmt + 1); } }; SourceLocation SwitchCase::getEndLoc() const { if (const auto *CS = dyn_cast<CaseStmt>(this)) return CS->getEndLoc(); else if (const auto *DS = dyn_cast<DefaultStmt>(this)) return DS->getEndLoc(); llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!"); } Stmt *SwitchCase::getSubStmt() { if (auto *CS = dyn_cast<CaseStmt>(this)) return CS->getSubStmt(); else if (auto *DS = dyn_cast<DefaultStmt>(this)) return DS->getSubStmt(); llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!"); } /// Represents a statement that could possibly have a value and type. This /// covers expression-statements, as well as labels and attributed statements. /// /// Value statements have a special meaning when they are the last non-null /// statement in a GNU statement expression, where they determine the value /// of the statement expression. class ValueStmt : public Stmt { protected: using Stmt::Stmt; public: const Expr *getExprStmt() const; Expr *getExprStmt() { const ValueStmt *ConstThis = this; return const_cast<Expr*>(ConstThis->getExprStmt()); } static bool classof(const Stmt *T) { return T->getStmtClass() >= firstValueStmtConstant && T->getStmtClass() <= lastValueStmtConstant; } }; /// LabelStmt - Represents a label, which has a substatement. For example: /// foo: return; class LabelStmt : public ValueStmt { LabelDecl *TheDecl; Stmt *SubStmt; public: /// Build a label statement. LabelStmt(SourceLocation IL, LabelDecl *D, Stmt *substmt) : ValueStmt(LabelStmtClass), TheDecl(D), SubStmt(substmt) { setIdentLoc(IL); } /// Build an empty label statement. explicit LabelStmt(EmptyShell Empty) : ValueStmt(LabelStmtClass, Empty) {} SourceLocation getIdentLoc() const { return LabelStmtBits.IdentLoc; } void setIdentLoc(SourceLocation L) { LabelStmtBits.IdentLoc = L; } LabelDecl *getDecl() const { return TheDecl; } void setDecl(LabelDecl *D) { TheDecl = D; } const char *getName() const; Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } void setSubStmt(Stmt *SS) { SubStmt = SS; } SourceLocation getBeginLoc() const { return getIdentLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();} child_range children() { return child_range(&SubStmt, &SubStmt + 1); } const_child_range children() const { return const_child_range(&SubStmt, &SubStmt + 1); } static bool classof(const Stmt *T) { return T->getStmtClass() == LabelStmtClass; } }; /// Represents an attribute applied to a statement. /// /// Represents an attribute applied to a statement. For example: /// [[omp::for(...)]] for (...) { ... } class AttributedStmt final : public ValueStmt, private llvm::TrailingObjects<AttributedStmt, const Attr *> { friend class ASTStmtReader; friend TrailingObjects; Stmt *SubStmt; AttributedStmt(SourceLocation Loc, ArrayRef<const Attr *> Attrs, Stmt *SubStmt) : ValueStmt(AttributedStmtClass), SubStmt(SubStmt) { AttributedStmtBits.NumAttrs = Attrs.size(); AttributedStmtBits.AttrLoc = Loc; std::copy(Attrs.begin(), Attrs.end(), getAttrArrayPtr()); } explicit AttributedStmt(EmptyShell Empty, unsigned NumAttrs) : ValueStmt(AttributedStmtClass, Empty) { AttributedStmtBits.NumAttrs = NumAttrs; AttributedStmtBits.AttrLoc = SourceLocation{}; std::fill_n(getAttrArrayPtr(), NumAttrs, nullptr); } const Attr *const *getAttrArrayPtr() const { return getTrailingObjects<const Attr *>(); } const Attr **getAttrArrayPtr() { return getTrailingObjects<const Attr *>(); } public: static AttributedStmt *Create(const ASTContext &C, SourceLocation Loc, ArrayRef<const Attr *> Attrs, Stmt *SubStmt); // Build an empty attributed statement. static AttributedStmt *CreateEmpty(const ASTContext &C, unsigned NumAttrs); SourceLocation getAttrLoc() const { return AttributedStmtBits.AttrLoc; } ArrayRef<const Attr *> getAttrs() const { return llvm::makeArrayRef(getAttrArrayPtr(), AttributedStmtBits.NumAttrs); } Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } SourceLocation getBeginLoc() const { return getAttrLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();} child_range children() { return child_range(&SubStmt, &SubStmt + 1); } const_child_range children() const { return const_child_range(&SubStmt, &SubStmt + 1); } static bool classof(const Stmt *T) { return T->getStmtClass() == AttributedStmtClass; } }; /// IfStmt - This represents an if/then/else. class IfStmt final : public Stmt, private llvm::TrailingObjects<IfStmt, Stmt *, SourceLocation> { friend TrailingObjects; // IfStmt is followed by several trailing objects, some of which optional. // Note that it would be more convenient to put the optional trailing // objects at then end but this would change the order of the children. // The trailing objects are in order: // // * A "Stmt *" for the init statement. // Present if and only if hasInitStorage(). // // * A "Stmt *" for the condition variable. // Present if and only if hasVarStorage(). This is in fact a "DeclStmt *". // // * A "Stmt *" for the condition. // Always present. This is in fact a "Expr *". // // * A "Stmt *" for the then statement. // Always present. // // * A "Stmt *" for the else statement. // Present if and only if hasElseStorage(). // // * A "SourceLocation" for the location of the "else". // Present if and only if hasElseStorage(). enum { InitOffset = 0, ThenOffsetFromCond = 1, ElseOffsetFromCond = 2 }; enum { NumMandatoryStmtPtr = 2 }; unsigned numTrailingObjects(OverloadToken<Stmt *>) const { return NumMandatoryStmtPtr + hasElseStorage() + hasVarStorage() + hasInitStorage(); } unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { return hasElseStorage(); } unsigned initOffset() const { return InitOffset; } unsigned varOffset() const { return InitOffset + hasInitStorage(); } unsigned condOffset() const { return InitOffset + hasInitStorage() + hasVarStorage(); } unsigned thenOffset() const { return condOffset() + ThenOffsetFromCond; } unsigned elseOffset() const { return condOffset() + ElseOffsetFromCond; } /// Build an if/then/else statement. IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond, Stmt *Then, SourceLocation EL, Stmt *Else); /// Build an empty if/then/else statement. explicit IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit); public: /// Create an IfStmt. static IfStmt *Create(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond, Stmt *Then, SourceLocation EL = SourceLocation(), Stmt *Else = nullptr); /// Create an empty IfStmt optionally with storage for an else statement, /// condition variable and init expression. static IfStmt *CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar, bool HasInit); /// True if this IfStmt has the storage for an init statement. bool hasInitStorage() const { return IfStmtBits.HasInit; } /// True if this IfStmt has storage for a variable declaration. bool hasVarStorage() const { return IfStmtBits.HasVar; } /// True if this IfStmt has storage for an else statement. bool hasElseStorage() const { return IfStmtBits.HasElse; } Expr *getCond() { return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]); } const Expr *getCond() const { return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]); } void setCond(Expr *Cond) { getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond); } Stmt *getThen() { return getTrailingObjects<Stmt *>()[thenOffset()]; } const Stmt *getThen() const { return getTrailingObjects<Stmt *>()[thenOffset()]; } void setThen(Stmt *Then) { getTrailingObjects<Stmt *>()[thenOffset()] = Then; } Stmt *getElse() { return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()] : nullptr; } const Stmt *getElse() const { return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()] : nullptr; } void setElse(Stmt *Else) { assert(hasElseStorage() && "This if statement has no storage for an else statement!"); getTrailingObjects<Stmt *>()[elseOffset()] = Else; } /// Retrieve the variable declared in this "if" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// if (int x = foo()) { /// printf("x is %d", x); /// } /// \endcode VarDecl *getConditionVariable(); const VarDecl *getConditionVariable() const { return const_cast<IfStmt *>(this)->getConditionVariable(); } /// Set the condition variable for this if statement. /// The if statement must have storage for the condition variable. void setConditionVariable(const ASTContext &Ctx, VarDecl *V); /// If this IfStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. DeclStmt *getConditionVariableDeclStmt() { return hasVarStorage() ? static_cast<DeclStmt *>( getTrailingObjects<Stmt *>()[varOffset()]) : nullptr; } const DeclStmt *getConditionVariableDeclStmt() const { return hasVarStorage() ? static_cast<DeclStmt *>( getTrailingObjects<Stmt *>()[varOffset()]) : nullptr; } Stmt *getInit() { return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()] : nullptr; } const Stmt *getInit() const { return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()] : nullptr; } void setInit(Stmt *Init) { assert(hasInitStorage() && "This if statement has no storage for an init statement!"); getTrailingObjects<Stmt *>()[initOffset()] = Init; } SourceLocation getIfLoc() const { return IfStmtBits.IfLoc; } void setIfLoc(SourceLocation IfLoc) { IfStmtBits.IfLoc = IfLoc; } SourceLocation getElseLoc() const { return hasElseStorage() ? *getTrailingObjects<SourceLocation>() : SourceLocation(); } void setElseLoc(SourceLocation ElseLoc) { assert(hasElseStorage() && "This if statement has no storage for an else statement!"); *getTrailingObjects<SourceLocation>() = ElseLoc; } bool isConstexpr() const { return IfStmtBits.IsConstexpr; } void setConstexpr(bool C) { IfStmtBits.IsConstexpr = C; } /// If this is an 'if constexpr', determine which substatement will be taken. /// Otherwise, or if the condition is value-dependent, returns None. Optional<const Stmt*> getNondiscardedCase(const ASTContext &Ctx) const; bool isObjCAvailabilityCheck() const; SourceLocation getBeginLoc() const { return getIfLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { if (getElse()) return getElse()->getEndLoc(); return getThen()->getEndLoc(); } // Iterators over subexpressions. The iterators will include iterating // over the initialization expression referenced by the condition variable. child_range children() { return child_range(getTrailingObjects<Stmt *>(), getTrailingObjects<Stmt *>() + numTrailingObjects(OverloadToken<Stmt *>())); } const_child_range children() const { return const_child_range(getTrailingObjects<Stmt *>(), getTrailingObjects<Stmt *>() + numTrailingObjects(OverloadToken<Stmt *>())); } static bool classof(const Stmt *T) { return T->getStmtClass() == IfStmtClass; } }; /// SwitchStmt - This represents a 'switch' stmt. class SwitchStmt final : public Stmt, private llvm::TrailingObjects<SwitchStmt, Stmt *> { friend TrailingObjects; /// Points to a linked list of case and default statements. SwitchCase *FirstCase; // SwitchStmt is followed by several trailing objects, // some of which optional. Note that it would be more convenient to // put the optional trailing objects at the end but this would change // the order in children(). // The trailing objects are in order: // // * A "Stmt *" for the init statement. // Present if and only if hasInitStorage(). // // * A "Stmt *" for the condition variable. // Present if and only if hasVarStorage(). This is in fact a "DeclStmt *". // // * A "Stmt *" for the condition. // Always present. This is in fact an "Expr *". // // * A "Stmt *" for the body. // Always present. enum { InitOffset = 0, BodyOffsetFromCond = 1 }; enum { NumMandatoryStmtPtr = 2 }; unsigned numTrailingObjects(OverloadToken<Stmt *>) const { return NumMandatoryStmtPtr + hasInitStorage() + hasVarStorage(); } unsigned initOffset() const { return InitOffset; } unsigned varOffset() const { return InitOffset + hasInitStorage(); } unsigned condOffset() const { return InitOffset + hasInitStorage() + hasVarStorage(); } unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; } /// Build a switch statement. SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond); /// Build a empty switch statement. explicit SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar); public: /// Create a switch statement. static SwitchStmt *Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond); /// Create an empty switch statement optionally with storage for /// an init expression and a condition variable. static SwitchStmt *CreateEmpty(const ASTContext &Ctx, bool HasInit, bool HasVar); /// True if this SwitchStmt has storage for an init statement. bool hasInitStorage() const { return SwitchStmtBits.HasInit; } /// True if this SwitchStmt has storage for a condition variable. bool hasVarStorage() const { return SwitchStmtBits.HasVar; } Expr *getCond() { return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]); } const Expr *getCond() const { return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]); } void setCond(Expr *Cond) { getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond); } Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; } const Stmt *getBody() const { return getTrailingObjects<Stmt *>()[bodyOffset()]; } void setBody(Stmt *Body) { getTrailingObjects<Stmt *>()[bodyOffset()] = Body; } Stmt *getInit() { return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()] : nullptr; } const Stmt *getInit() const { return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()] : nullptr; } void setInit(Stmt *Init) { assert(hasInitStorage() && "This switch statement has no storage for an init statement!"); getTrailingObjects<Stmt *>()[initOffset()] = Init; } /// Retrieve the variable declared in this "switch" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// switch (int x = foo()) { /// case 0: break; /// // ... /// } /// \endcode VarDecl *getConditionVariable(); const VarDecl *getConditionVariable() const { return const_cast<SwitchStmt *>(this)->getConditionVariable(); } /// Set the condition variable in this switch statement. /// The switch statement must have storage for it. void setConditionVariable(const ASTContext &Ctx, VarDecl *VD); /// If this SwitchStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. DeclStmt *getConditionVariableDeclStmt() { return hasVarStorage() ? static_cast<DeclStmt *>( getTrailingObjects<Stmt *>()[varOffset()]) : nullptr; } const DeclStmt *getConditionVariableDeclStmt() const { return hasVarStorage() ? static_cast<DeclStmt *>( getTrailingObjects<Stmt *>()[varOffset()]) : nullptr; } SwitchCase *getSwitchCaseList() { return FirstCase; } const SwitchCase *getSwitchCaseList() const { return FirstCase; } void setSwitchCaseList(SwitchCase *SC) { FirstCase = SC; } SourceLocation getSwitchLoc() const { return SwitchStmtBits.SwitchLoc; } void setSwitchLoc(SourceLocation L) { SwitchStmtBits.SwitchLoc = L; } void setBody(Stmt *S, SourceLocation SL) { setBody(S); setSwitchLoc(SL); } void addSwitchCase(SwitchCase *SC) { assert(!SC->getNextSwitchCase() && "case/default already added to a switch"); SC->setNextSwitchCase(FirstCase); FirstCase = SC; } /// Set a flag in the SwitchStmt indicating that if the 'switch (X)' is a /// switch over an enum value then all cases have been explicitly covered. void setAllEnumCasesCovered() { SwitchStmtBits.AllEnumCasesCovered = true; } /// Returns true if the SwitchStmt is a switch of an enum value and all cases /// have been explicitly covered. bool isAllEnumCasesCovered() const { return SwitchStmtBits.AllEnumCasesCovered; } SourceLocation getBeginLoc() const { return getSwitchLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { return getBody() ? getBody()->getEndLoc() : reinterpret_cast<const Stmt *>(getCond())->getEndLoc(); } // Iterators child_range children() { return child_range(getTrailingObjects<Stmt *>(), getTrailingObjects<Stmt *>() + numTrailingObjects(OverloadToken<Stmt *>())); } const_child_range children() const { return const_child_range(getTrailingObjects<Stmt *>(), getTrailingObjects<Stmt *>() + numTrailingObjects(OverloadToken<Stmt *>())); } static bool classof(const Stmt *T) { return T->getStmtClass() == SwitchStmtClass; } }; /// WhileStmt - This represents a 'while' stmt. class WhileStmt final : public Stmt, private llvm::TrailingObjects<WhileStmt, Stmt *> { friend TrailingObjects; // WhileStmt is followed by several trailing objects, // some of which optional. Note that it would be more // convenient to put the optional trailing object at the end // but this would affect children(). // The trailing objects are in order: // // * A "Stmt *" for the condition variable. // Present if and only if hasVarStorage(). This is in fact a "DeclStmt *". // // * A "Stmt *" for the condition. // Always present. This is in fact an "Expr *". // // * A "Stmt *" for the body. // Always present. // enum { VarOffset = 0, BodyOffsetFromCond = 1 }; enum { NumMandatoryStmtPtr = 2 }; SourceLocation LParenLoc, RParenLoc; unsigned varOffset() const { return VarOffset; } unsigned condOffset() const { return VarOffset + hasVarStorage(); } unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; } unsigned numTrailingObjects(OverloadToken<Stmt *>) const { return NumMandatoryStmtPtr + hasVarStorage(); } /// Build a while statement. WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body, SourceLocation WL, SourceLocation LParenLoc, SourceLocation RParenLoc); /// Build an empty while statement. explicit WhileStmt(EmptyShell Empty, bool HasVar); public: /// Create a while statement. static WhileStmt *Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body, SourceLocation WL, SourceLocation LParenLoc, SourceLocation RParenLoc); /// Create an empty while statement optionally with storage for /// a condition variable. static WhileStmt *CreateEmpty(const ASTContext &Ctx, bool HasVar); /// True if this WhileStmt has storage for a condition variable. bool hasVarStorage() const { return WhileStmtBits.HasVar; } Expr *getCond() { return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]); } const Expr *getCond() const { return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]); } void setCond(Expr *Cond) { getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond); } Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; } const Stmt *getBody() const { return getTrailingObjects<Stmt *>()[bodyOffset()]; } void setBody(Stmt *Body) { getTrailingObjects<Stmt *>()[bodyOffset()] = Body; } /// Retrieve the variable declared in this "while" statement, if any. /// /// In the following example, "x" is the condition variable. /// \code /// while (int x = random()) { /// // ... /// } /// \endcode VarDecl *getConditionVariable(); const VarDecl *getConditionVariable() const { return const_cast<WhileStmt *>(this)->getConditionVariable(); } /// Set the condition variable of this while statement. /// The while statement must have storage for it. void setConditionVariable(const ASTContext &Ctx, VarDecl *V); /// If this WhileStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. DeclStmt *getConditionVariableDeclStmt() { return hasVarStorage() ? static_cast<DeclStmt *>( getTrailingObjects<Stmt *>()[varOffset()]) : nullptr; } const DeclStmt *getConditionVariableDeclStmt() const { return hasVarStorage() ? static_cast<DeclStmt *>( getTrailingObjects<Stmt *>()[varOffset()]) : nullptr; } SourceLocation getWhileLoc() const { return WhileStmtBits.WhileLoc; } void setWhileLoc(SourceLocation L) { WhileStmtBits.WhileLoc = L; } SourceLocation getLParenLoc() const { return LParenLoc; } void setLParenLoc(SourceLocation L) { LParenLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getBeginLoc() const { return getWhileLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { return getBody()->getEndLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == WhileStmtClass; } // Iterators child_range children() { return child_range(getTrailingObjects<Stmt *>(), getTrailingObjects<Stmt *>() + numTrailingObjects(OverloadToken<Stmt *>())); } const_child_range children() const { return const_child_range(getTrailingObjects<Stmt *>(), getTrailingObjects<Stmt *>() + numTrailingObjects(OverloadToken<Stmt *>())); } }; /// DoStmt - This represents a 'do/while' stmt. class DoStmt : public Stmt { enum { BODY, COND, END_EXPR }; Stmt *SubExprs[END_EXPR]; SourceLocation WhileLoc; SourceLocation RParenLoc; // Location of final ')' in do stmt condition. public: DoStmt(Stmt *Body, Expr *Cond, SourceLocation DL, SourceLocation WL, SourceLocation RP) : Stmt(DoStmtClass), WhileLoc(WL), RParenLoc(RP) { setCond(Cond); setBody(Body); setDoLoc(DL); } /// Build an empty do-while statement. explicit DoStmt(EmptyShell Empty) : Stmt(DoStmtClass, Empty) {} Expr *getCond() { return reinterpret_cast<Expr *>(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast<Expr *>(SubExprs[COND]); } void setCond(Expr *Cond) { SubExprs[COND] = reinterpret_cast<Stmt *>(Cond); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getBody() const { return SubExprs[BODY]; } void setBody(Stmt *Body) { SubExprs[BODY] = Body; } SourceLocation getDoLoc() const { return DoStmtBits.DoLoc; } void setDoLoc(SourceLocation L) { DoStmtBits.DoLoc = L; } SourceLocation getWhileLoc() const { return WhileLoc; } void setWhileLoc(SourceLocation L) { WhileLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getBeginLoc() const { return getDoLoc(); } SourceLocation getEndLoc() const { return getRParenLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == DoStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); } const_child_range children() const { return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); } }; /// ForStmt - This represents a 'for (init;cond;inc)' stmt. Note that any of /// the init/cond/inc parts of the ForStmt will be null if they were not /// specified in the source. class ForStmt : public Stmt { enum { INIT, CONDVAR, COND, INC, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // SubExprs[INIT] is an expression or declstmt. SourceLocation LParenLoc, RParenLoc; public: ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar, Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP, SourceLocation RP); /// Build an empty for statement. explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) {} Stmt *getInit() { return SubExprs[INIT]; } /// Retrieve the variable declared in this "for" statement, if any. /// /// In the following example, "y" is the condition variable. /// \code /// for (int x = random(); int y = mangle(x); ++x) { /// // ... /// } /// \endcode VarDecl *getConditionVariable() const; void setConditionVariable(const ASTContext &C, VarDecl *V); /// If this ForStmt has a condition variable, return the faux DeclStmt /// associated with the creation of that condition variable. const DeclStmt *getConditionVariableDeclStmt() const { return reinterpret_cast<DeclStmt*>(SubExprs[CONDVAR]); } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } Expr *getInc() { return reinterpret_cast<Expr*>(SubExprs[INC]); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getInit() const { return SubExprs[INIT]; } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Expr *getInc() const { return reinterpret_cast<Expr*>(SubExprs[INC]); } const Stmt *getBody() const { return SubExprs[BODY]; } void setInit(Stmt *S) { SubExprs[INIT] = S; } void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); } void setInc(Expr *E) { SubExprs[INC] = reinterpret_cast<Stmt*>(E); } void setBody(Stmt *S) { SubExprs[BODY] = S; } SourceLocation getForLoc() const { return ForStmtBits.ForLoc; } void setForLoc(SourceLocation L) { ForStmtBits.ForLoc = L; } SourceLocation getLParenLoc() const { return LParenLoc; } void setLParenLoc(SourceLocation L) { LParenLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getBeginLoc() const { return getForLoc(); } SourceLocation getEndLoc() const { return getBody()->getEndLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ForStmtClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } const_child_range children() const { return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); } }; /// GotoStmt - This represents a direct goto. class GotoStmt : public Stmt { LabelDecl *Label; SourceLocation LabelLoc; public: GotoStmt(LabelDecl *label, SourceLocation GL, SourceLocation LL) : Stmt(GotoStmtClass), Label(label), LabelLoc(LL) { setGotoLoc(GL); } /// Build an empty goto statement. explicit GotoStmt(EmptyShell Empty) : Stmt(GotoStmtClass, Empty) {} LabelDecl *getLabel() const { return Label; } void setLabel(LabelDecl *D) { Label = D; } SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; } void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; } SourceLocation getLabelLoc() const { return LabelLoc; } void setLabelLoc(SourceLocation L) { LabelLoc = L; } SourceLocation getBeginLoc() const { return getGotoLoc(); } SourceLocation getEndLoc() const { return getLabelLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == GotoStmtClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// IndirectGotoStmt - This represents an indirect goto. class IndirectGotoStmt : public Stmt { SourceLocation StarLoc; Stmt *Target; public: IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, Expr *target) : Stmt(IndirectGotoStmtClass), StarLoc(starLoc) { setTarget(target); setGotoLoc(gotoLoc); } /// Build an empty indirect goto statement. explicit IndirectGotoStmt(EmptyShell Empty) : Stmt(IndirectGotoStmtClass, Empty) {} void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; } SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; } void setStarLoc(SourceLocation L) { StarLoc = L; } SourceLocation getStarLoc() const { return StarLoc; } Expr *getTarget() { return reinterpret_cast<Expr *>(Target); } const Expr *getTarget() const { return reinterpret_cast<const Expr *>(Target); } void setTarget(Expr *E) { Target = reinterpret_cast<Stmt *>(E); } /// getConstantTarget - Returns the fixed target of this indirect /// goto, if one exists. LabelDecl *getConstantTarget(); const LabelDecl *getConstantTarget() const { return const_cast<IndirectGotoStmt *>(this)->getConstantTarget(); } SourceLocation getBeginLoc() const { return getGotoLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { return Target->getEndLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == IndirectGotoStmtClass; } // Iterators child_range children() { return child_range(&Target, &Target + 1); } const_child_range children() const { return const_child_range(&Target, &Target + 1); } }; /// ContinueStmt - This represents a continue. class ContinueStmt : public Stmt { public: ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass) { setContinueLoc(CL); } /// Build an empty continue statement. explicit ContinueStmt(EmptyShell Empty) : Stmt(ContinueStmtClass, Empty) {} SourceLocation getContinueLoc() const { return ContinueStmtBits.ContinueLoc; } void setContinueLoc(SourceLocation L) { ContinueStmtBits.ContinueLoc = L; } SourceLocation getBeginLoc() const { return getContinueLoc(); } SourceLocation getEndLoc() const { return getContinueLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ContinueStmtClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// BreakStmt - This represents a break. class BreakStmt : public Stmt { public: BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass) { setBreakLoc(BL); } /// Build an empty break statement. explicit BreakStmt(EmptyShell Empty) : Stmt(BreakStmtClass, Empty) {} SourceLocation getBreakLoc() const { return BreakStmtBits.BreakLoc; } void setBreakLoc(SourceLocation L) { BreakStmtBits.BreakLoc = L; } SourceLocation getBeginLoc() const { return getBreakLoc(); } SourceLocation getEndLoc() const { return getBreakLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == BreakStmtClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// ReturnStmt - This represents a return, optionally of an expression: /// return; /// return 4; /// /// Note that GCC allows return with no argument in a function declared to /// return a value, and it allows returning a value in functions declared to /// return void. We explicitly model this in the AST, which means you can't /// depend on the return type of the function and the presence of an argument. class ReturnStmt final : public Stmt, private llvm::TrailingObjects<ReturnStmt, const VarDecl *> { friend TrailingObjects; /// The return expression. Stmt *RetExpr; // ReturnStmt is followed optionally by a trailing "const VarDecl *" // for the NRVO candidate. Present if and only if hasNRVOCandidate(). /// True if this ReturnStmt has storage for an NRVO candidate. bool hasNRVOCandidate() const { return ReturnStmtBits.HasNRVOCandidate; } unsigned numTrailingObjects(OverloadToken<const VarDecl *>) const { return hasNRVOCandidate(); } /// Build a return statement. ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate); /// Build an empty return statement. explicit ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate); public: /// Create a return statement. static ReturnStmt *Create(const ASTContext &Ctx, SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate); /// Create an empty return statement, optionally with /// storage for an NRVO candidate. static ReturnStmt *CreateEmpty(const ASTContext &Ctx, bool HasNRVOCandidate); Expr *getRetValue() { return reinterpret_cast<Expr *>(RetExpr); } const Expr *getRetValue() const { return reinterpret_cast<Expr *>(RetExpr); } void setRetValue(Expr *E) { RetExpr = reinterpret_cast<Stmt *>(E); } /// Retrieve the variable that might be used for the named return /// value optimization. /// /// The optimization itself can only be performed if the variable is /// also marked as an NRVO object. const VarDecl *getNRVOCandidate() const { return hasNRVOCandidate() ? *getTrailingObjects<const VarDecl *>() : nullptr; } /// Set the variable that might be used for the named return value /// optimization. The return statement must have storage for it, /// which is the case if and only if hasNRVOCandidate() is true. void setNRVOCandidate(const VarDecl *Var) { assert(hasNRVOCandidate() && "This return statement has no storage for an NRVO candidate!"); *getTrailingObjects<const VarDecl *>() = Var; } SourceLocation getReturnLoc() const { return ReturnStmtBits.RetLoc; } void setReturnLoc(SourceLocation L) { ReturnStmtBits.RetLoc = L; } SourceLocation getBeginLoc() const { return getReturnLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { return RetExpr ? RetExpr->getEndLoc() : getReturnLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ReturnStmtClass; } // Iterators child_range children() { if (RetExpr) return child_range(&RetExpr, &RetExpr + 1); return child_range(child_iterator(), child_iterator()); } const_child_range children() const { if (RetExpr) return const_child_range(&RetExpr, &RetExpr + 1); return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// AsmStmt is the base class for GCCAsmStmt and MSAsmStmt. class AsmStmt : public Stmt { protected: friend class ASTStmtReader; SourceLocation AsmLoc; /// True if the assembly statement does not have any input or output /// operands. bool IsSimple; /// If true, treat this inline assembly as having side effects. /// This assembly statement should not be optimized, deleted or moved. bool IsVolatile; unsigned NumOutputs; unsigned NumInputs; unsigned NumClobbers; Stmt **Exprs = nullptr; AsmStmt(StmtClass SC, SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, unsigned numclobbers) : Stmt (SC), AsmLoc(asmloc), IsSimple(issimple), IsVolatile(isvolatile), NumOutputs(numoutputs), NumInputs(numinputs), NumClobbers(numclobbers) {} public: /// Build an empty inline-assembly statement. explicit AsmStmt(StmtClass SC, EmptyShell Empty) : Stmt(SC, Empty) {} SourceLocation getAsmLoc() const { return AsmLoc; } void setAsmLoc(SourceLocation L) { AsmLoc = L; } bool isSimple() const { return IsSimple; } void setSimple(bool V) { IsSimple = V; } bool isVolatile() const { return IsVolatile; } void setVolatile(bool V) { IsVolatile = V; } SourceLocation getBeginLoc() const LLVM_READONLY { return {}; } SourceLocation getEndLoc() const LLVM_READONLY { return {}; } //===--- Asm String Analysis ---===// /// Assemble final IR asm string. std::string generateAsmString(const ASTContext &C) const; //===--- Output operands ---===// unsigned getNumOutputs() const { return NumOutputs; } /// getOutputConstraint - Return the constraint string for the specified /// output operand. All output constraints are known to be non-empty (either /// '=' or '+'). StringRef getOutputConstraint(unsigned i) const; /// isOutputPlusConstraint - Return true if the specified output constraint /// is a "+" constraint (which is both an input and an output) or false if it /// is an "=" constraint (just an output). bool isOutputPlusConstraint(unsigned i) const { return getOutputConstraint(i)[0] == '+'; } const Expr *getOutputExpr(unsigned i) const; /// getNumPlusOperands - Return the number of output operands that have a "+" /// constraint. unsigned getNumPlusOperands() const; //===--- Input operands ---===// unsigned getNumInputs() const { return NumInputs; } /// getInputConstraint - Return the specified input constraint. Unlike output /// constraints, these can be empty. StringRef getInputConstraint(unsigned i) const; const Expr *getInputExpr(unsigned i) const; //===--- Other ---===// unsigned getNumClobbers() const { return NumClobbers; } StringRef getClobber(unsigned i) const; static bool classof(const Stmt *T) { return T->getStmtClass() == GCCAsmStmtClass || T->getStmtClass() == MSAsmStmtClass; } // Input expr iterators. using inputs_iterator = ExprIterator; using const_inputs_iterator = ConstExprIterator; using inputs_range = llvm::iterator_range<inputs_iterator>; using inputs_const_range = llvm::iterator_range<const_inputs_iterator>; inputs_iterator begin_inputs() { return &Exprs[0] + NumOutputs; } inputs_iterator end_inputs() { return &Exprs[0] + NumOutputs + NumInputs; } inputs_range inputs() { return inputs_range(begin_inputs(), end_inputs()); } const_inputs_iterator begin_inputs() const { return &Exprs[0] + NumOutputs; } const_inputs_iterator end_inputs() const { return &Exprs[0] + NumOutputs + NumInputs; } inputs_const_range inputs() const { return inputs_const_range(begin_inputs(), end_inputs()); } // Output expr iterators. using outputs_iterator = ExprIterator; using const_outputs_iterator = ConstExprIterator; using outputs_range = llvm::iterator_range<outputs_iterator>; using outputs_const_range = llvm::iterator_range<const_outputs_iterator>; outputs_iterator begin_outputs() { return &Exprs[0]; } outputs_iterator end_outputs() { return &Exprs[0] + NumOutputs; } outputs_range outputs() { return outputs_range(begin_outputs(), end_outputs()); } const_outputs_iterator begin_outputs() const { return &Exprs[0]; } const_outputs_iterator end_outputs() const { return &Exprs[0] + NumOutputs; } outputs_const_range outputs() const { return outputs_const_range(begin_outputs(), end_outputs()); } child_range children() { return child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs); } const_child_range children() const { return const_child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs); } }; /// This represents a GCC inline-assembly statement extension. class GCCAsmStmt : public AsmStmt { friend class ASTStmtReader; SourceLocation RParenLoc; StringLiteral *AsmStr; // FIXME: If we wanted to, we could allocate all of these in one big array. StringLiteral **Constraints = nullptr; StringLiteral **Clobbers = nullptr; IdentifierInfo **Names = nullptr; unsigned NumLabels = 0; public: GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, IdentifierInfo **names, StringLiteral **constraints, Expr **exprs, StringLiteral *asmstr, unsigned numclobbers, StringLiteral **clobbers, unsigned numlabels, SourceLocation rparenloc); /// Build an empty inline-assembly statement. explicit GCCAsmStmt(EmptyShell Empty) : AsmStmt(GCCAsmStmtClass, Empty) {} SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } //===--- Asm String Analysis ---===// const StringLiteral *getAsmString() const { return AsmStr; } StringLiteral *getAsmString() { return AsmStr; } void setAsmString(StringLiteral *E) { AsmStr = E; } /// AsmStringPiece - this is part of a decomposed asm string specification /// (for use with the AnalyzeAsmString function below). An asm string is /// considered to be a concatenation of these parts. class AsmStringPiece { public: enum Kind { String, // String in .ll asm string form, "$" -> "$$" and "%%" -> "%". Operand // Operand reference, with optional modifier %c4. }; private: Kind MyKind; std::string Str; unsigned OperandNo; // Source range for operand references. CharSourceRange Range; public: AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {} AsmStringPiece(unsigned OpNo, const std::string &S, SourceLocation Begin, SourceLocation End) : MyKind(Operand), Str(S), OperandNo(OpNo), Range(CharSourceRange::getCharRange(Begin, End)) {} bool isString() const { return MyKind == String; } bool isOperand() const { return MyKind == Operand; } const std::string &getString() const { return Str; } unsigned getOperandNo() const { assert(isOperand()); return OperandNo; } CharSourceRange getRange() const { assert(isOperand() && "Range is currently used only for Operands."); return Range; } /// getModifier - Get the modifier for this operand, if present. This /// returns '\0' if there was no modifier. char getModifier() const; }; /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing /// it into pieces. If the asm string is erroneous, emit errors and return /// true, otherwise return false. This handles canonicalization and /// translation of strings from GCC syntax to LLVM IR syntax, and handles //// flattening of named references like %[foo] to Operand AsmStringPiece's. unsigned AnalyzeAsmString(SmallVectorImpl<AsmStringPiece> &Pieces, const ASTContext &C, unsigned &DiagOffs) const; /// Assemble final IR asm string. std::string generateAsmString(const ASTContext &C) const; //===--- Output operands ---===// IdentifierInfo *getOutputIdentifier(unsigned i) const { return Names[i]; } StringRef getOutputName(unsigned i) const { if (IdentifierInfo *II = getOutputIdentifier(i)) return II->getName(); return {}; } StringRef getOutputConstraint(unsigned i) const; const StringLiteral *getOutputConstraintLiteral(unsigned i) const { return Constraints[i]; } StringLiteral *getOutputConstraintLiteral(unsigned i) { return Constraints[i]; } Expr *getOutputExpr(unsigned i); const Expr *getOutputExpr(unsigned i) const { return const_cast<GCCAsmStmt*>(this)->getOutputExpr(i); } //===--- Input operands ---===// IdentifierInfo *getInputIdentifier(unsigned i) const { return Names[i + NumOutputs]; } StringRef getInputName(unsigned i) const { if (IdentifierInfo *II = getInputIdentifier(i)) return II->getName(); return {}; } StringRef getInputConstraint(unsigned i) const; const StringLiteral *getInputConstraintLiteral(unsigned i) const { return Constraints[i + NumOutputs]; } StringLiteral *getInputConstraintLiteral(unsigned i) { return Constraints[i + NumOutputs]; } Expr *getInputExpr(unsigned i); void setInputExpr(unsigned i, Expr *E); const Expr *getInputExpr(unsigned i) const { return const_cast<GCCAsmStmt*>(this)->getInputExpr(i); } //===--- Labels ---===// bool isAsmGoto() const { return NumLabels > 0; } unsigned getNumLabels() const { return NumLabels; } IdentifierInfo *getLabelIdentifier(unsigned i) const { return Names[i + NumOutputs + NumInputs]; } AddrLabelExpr *getLabelExpr(unsigned i) const; StringRef getLabelName(unsigned i) const; using labels_iterator = CastIterator<AddrLabelExpr>; using const_labels_iterator = ConstCastIterator<AddrLabelExpr>; using labels_range = llvm::iterator_range<labels_iterator>; using labels_const_range = llvm::iterator_range<const_labels_iterator>; labels_iterator begin_labels() { return &Exprs[0] + NumOutputs + NumInputs; } labels_iterator end_labels() { return &Exprs[0] + NumOutputs + NumInputs + NumLabels; } labels_range labels() { return labels_range(begin_labels(), end_labels()); } const_labels_iterator begin_labels() const { return &Exprs[0] + NumOutputs + NumInputs; } const_labels_iterator end_labels() const { return &Exprs[0] + NumOutputs + NumInputs + NumLabels; } labels_const_range labels() const { return labels_const_range(begin_labels(), end_labels()); } private: void setOutputsAndInputsAndClobbers(const ASTContext &C, IdentifierInfo **Names, StringLiteral **Constraints, Stmt **Exprs, unsigned NumOutputs, unsigned NumInputs, unsigned NumLabels, StringLiteral **Clobbers, unsigned NumClobbers); public: //===--- Other ---===// /// getNamedOperand - Given a symbolic operand reference like %[foo], /// translate this into a numeric value needed to reference the same operand. /// This returns -1 if the operand name is invalid. int getNamedOperand(StringRef SymbolicName) const; StringRef getClobber(unsigned i) const; StringLiteral *getClobberStringLiteral(unsigned i) { return Clobbers[i]; } const StringLiteral *getClobberStringLiteral(unsigned i) const { return Clobbers[i]; } SourceLocation getBeginLoc() const LLVM_READONLY { return AsmLoc; } SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == GCCAsmStmtClass; } }; /// This represents a Microsoft inline-assembly statement extension. class MSAsmStmt : public AsmStmt { friend class ASTStmtReader; SourceLocation LBraceLoc, EndLoc; StringRef AsmStr; unsigned NumAsmToks = 0; Token *AsmToks = nullptr; StringRef *Constraints = nullptr; StringRef *Clobbers = nullptr; public: MSAsmStmt(const ASTContext &C, SourceLocation asmloc, SourceLocation lbraceloc, bool issimple, bool isvolatile, ArrayRef<Token> asmtoks, unsigned numoutputs, unsigned numinputs, ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs, StringRef asmstr, ArrayRef<StringRef> clobbers, SourceLocation endloc); /// Build an empty MS-style inline-assembly statement. explicit MSAsmStmt(EmptyShell Empty) : AsmStmt(MSAsmStmtClass, Empty) {} SourceLocation getLBraceLoc() const { return LBraceLoc; } void setLBraceLoc(SourceLocation L) { LBraceLoc = L; } SourceLocation getEndLoc() const { return EndLoc; } void setEndLoc(SourceLocation L) { EndLoc = L; } bool hasBraces() const { return LBraceLoc.isValid(); } unsigned getNumAsmToks() { return NumAsmToks; } Token *getAsmToks() { return AsmToks; } //===--- Asm String Analysis ---===// StringRef getAsmString() const { return AsmStr; } /// Assemble final IR asm string. std::string generateAsmString(const ASTContext &C) const; //===--- Output operands ---===// StringRef getOutputConstraint(unsigned i) const { assert(i < NumOutputs); return Constraints[i]; } Expr *getOutputExpr(unsigned i); const Expr *getOutputExpr(unsigned i) const { return const_cast<MSAsmStmt*>(this)->getOutputExpr(i); } //===--- Input operands ---===// StringRef getInputConstraint(unsigned i) const { assert(i < NumInputs); return Constraints[i + NumOutputs]; } Expr *getInputExpr(unsigned i); void setInputExpr(unsigned i, Expr *E); const Expr *getInputExpr(unsigned i) const { return const_cast<MSAsmStmt*>(this)->getInputExpr(i); } //===--- Other ---===// ArrayRef<StringRef> getAllConstraints() const { return llvm::makeArrayRef(Constraints, NumInputs + NumOutputs); } ArrayRef<StringRef> getClobbers() const { return llvm::makeArrayRef(Clobbers, NumClobbers); } ArrayRef<Expr*> getAllExprs() const { return llvm::makeArrayRef(reinterpret_cast<Expr**>(Exprs), NumInputs + NumOutputs); } StringRef getClobber(unsigned i) const { return getClobbers()[i]; } private: void initialize(const ASTContext &C, StringRef AsmString, ArrayRef<Token> AsmToks, ArrayRef<StringRef> Constraints, ArrayRef<Expr*> Exprs, ArrayRef<StringRef> Clobbers); public: SourceLocation getBeginLoc() const LLVM_READONLY { return AsmLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == MSAsmStmtClass; } child_range children() { return child_range(&Exprs[0], &Exprs[NumInputs + NumOutputs]); } const_child_range children() const { return const_child_range(&Exprs[0], &Exprs[NumInputs + NumOutputs]); } }; class SEHExceptStmt : public Stmt { friend class ASTReader; friend class ASTStmtReader; SourceLocation Loc; Stmt *Children[2]; enum { FILTER_EXPR, BLOCK }; SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); explicit SEHExceptStmt(EmptyShell E) : Stmt(SEHExceptStmtClass, E) {} public: static SEHExceptStmt* Create(const ASTContext &C, SourceLocation ExceptLoc, Expr *FilterExpr, Stmt *Block); SourceLocation getBeginLoc() const LLVM_READONLY { return getExceptLoc(); } SourceLocation getExceptLoc() const { return Loc; } SourceLocation getEndLoc() const { return getBlock()->getEndLoc(); } Expr *getFilterExpr() const { return reinterpret_cast<Expr*>(Children[FILTER_EXPR]); } CompoundStmt *getBlock() const { return cast<CompoundStmt>(Children[BLOCK]); } child_range children() { return child_range(Children, Children+2); } const_child_range children() const { return const_child_range(Children, Children + 2); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHExceptStmtClass; } }; class SEHFinallyStmt : public Stmt { friend class ASTReader; friend class ASTStmtReader; SourceLocation Loc; Stmt *Block; SEHFinallyStmt(SourceLocation Loc, Stmt *Block); explicit SEHFinallyStmt(EmptyShell E) : Stmt(SEHFinallyStmtClass, E) {} public: static SEHFinallyStmt* Create(const ASTContext &C, SourceLocation FinallyLoc, Stmt *Block); SourceLocation getBeginLoc() const LLVM_READONLY { return getFinallyLoc(); } SourceLocation getFinallyLoc() const { return Loc; } SourceLocation getEndLoc() const { return Block->getEndLoc(); } CompoundStmt *getBlock() const { return cast<CompoundStmt>(Block); } child_range children() { return child_range(&Block,&Block+1); } const_child_range children() const { return const_child_range(&Block, &Block + 1); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHFinallyStmtClass; } }; class SEHTryStmt : public Stmt { friend class ASTReader; friend class ASTStmtReader; bool IsCXXTry; SourceLocation TryLoc; Stmt *Children[2]; enum { TRY = 0, HANDLER = 1 }; SEHTryStmt(bool isCXXTry, // true if 'try' otherwise '__try' SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); explicit SEHTryStmt(EmptyShell E) : Stmt(SEHTryStmtClass, E) {} public: static SEHTryStmt* Create(const ASTContext &C, bool isCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); SourceLocation getBeginLoc() const LLVM_READONLY { return getTryLoc(); } SourceLocation getTryLoc() const { return TryLoc; } SourceLocation getEndLoc() const { return Children[HANDLER]->getEndLoc(); } bool getIsCXXTry() const { return IsCXXTry; } CompoundStmt* getTryBlock() const { return cast<CompoundStmt>(Children[TRY]); } Stmt *getHandler() const { return Children[HANDLER]; } /// Returns 0 if not defined SEHExceptStmt *getExceptHandler() const; SEHFinallyStmt *getFinallyHandler() const; child_range children() { return child_range(Children, Children+2); } const_child_range children() const { return const_child_range(Children, Children + 2); } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHTryStmtClass; } }; /// Represents a __leave statement. class SEHLeaveStmt : public Stmt { SourceLocation LeaveLoc; public: explicit SEHLeaveStmt(SourceLocation LL) : Stmt(SEHLeaveStmtClass), LeaveLoc(LL) {} /// Build an empty __leave statement. explicit SEHLeaveStmt(EmptyShell Empty) : Stmt(SEHLeaveStmtClass, Empty) {} SourceLocation getLeaveLoc() const { return LeaveLoc; } void setLeaveLoc(SourceLocation L) { LeaveLoc = L; } SourceLocation getBeginLoc() const LLVM_READONLY { return LeaveLoc; } SourceLocation getEndLoc() const LLVM_READONLY { return LeaveLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == SEHLeaveStmtClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// This captures a statement into a function. For example, the following /// pragma annotated compound statement can be represented as a CapturedStmt, /// and this compound statement is the body of an anonymous outlined function. /// @code /// #pragma omp parallel /// { /// compute(); /// } /// @endcode class CapturedStmt : public Stmt { public: /// The different capture forms: by 'this', by reference, capture for /// variable-length array type etc. enum VariableCaptureKind { VCK_This, VCK_ByRef, VCK_ByCopy, VCK_VLAType, }; /// Describes the capture of either a variable, or 'this', or /// variable-length array type. class Capture { llvm::PointerIntPair<VarDecl *, 2, VariableCaptureKind> VarAndKind; SourceLocation Loc; public: friend class ASTStmtReader; /// Create a new capture. /// /// \param Loc The source location associated with this capture. /// /// \param Kind The kind of capture (this, ByRef, ...). /// /// \param Var The variable being captured, or null if capturing this. Capture(SourceLocation Loc, VariableCaptureKind Kind, VarDecl *Var = nullptr); /// Determine the kind of capture. VariableCaptureKind getCaptureKind() const; /// Retrieve the source location at which the variable or 'this' was /// first used. SourceLocation getLocation() const { return Loc; } /// Determine whether this capture handles the C++ 'this' pointer. bool capturesThis() const { return getCaptureKind() == VCK_This; } /// Determine whether this capture handles a variable (by reference). bool capturesVariable() const { return getCaptureKind() == VCK_ByRef; } /// Determine whether this capture handles a variable by copy. bool capturesVariableByCopy() const { return getCaptureKind() == VCK_ByCopy; } /// Determine whether this capture handles a variable-length array /// type. bool capturesVariableArrayType() const { return getCaptureKind() == VCK_VLAType; } /// Retrieve the declaration of the variable being captured. /// /// This operation is only valid if this capture captures a variable. VarDecl *getCapturedVar() const; }; private: /// The number of variable captured, including 'this'. unsigned NumCaptures; /// The pointer part is the implicit the outlined function and the /// int part is the captured region kind, 'CR_Default' etc. llvm::PointerIntPair<CapturedDecl *, 2, CapturedRegionKind> CapDeclAndKind; /// The record for captured variables, a RecordDecl or CXXRecordDecl. RecordDecl *TheRecordDecl = nullptr; /// Construct a captured statement. CapturedStmt(Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures, ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD); /// Construct an empty captured statement. CapturedStmt(EmptyShell Empty, unsigned NumCaptures); Stmt **getStoredStmts() { return reinterpret_cast<Stmt **>(this + 1); } Stmt *const *getStoredStmts() const { return reinterpret_cast<Stmt *const *>(this + 1); } Capture *getStoredCaptures() const; void setCapturedStmt(Stmt *S) { getStoredStmts()[NumCaptures] = S; } public: friend class ASTStmtReader; static CapturedStmt *Create(const ASTContext &Context, Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures, ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD); static CapturedStmt *CreateDeserialized(const ASTContext &Context, unsigned NumCaptures); /// Retrieve the statement being captured. Stmt *getCapturedStmt() { return getStoredStmts()[NumCaptures]; } const Stmt *getCapturedStmt() const { return getStoredStmts()[NumCaptures]; } /// Retrieve the outlined function declaration. CapturedDecl *getCapturedDecl(); const CapturedDecl *getCapturedDecl() const; /// Set the outlined function declaration. void setCapturedDecl(CapturedDecl *D); /// Retrieve the captured region kind. CapturedRegionKind getCapturedRegionKind() const; /// Set the captured region kind. void setCapturedRegionKind(CapturedRegionKind Kind); /// Retrieve the record declaration for captured variables. const RecordDecl *getCapturedRecordDecl() const { return TheRecordDecl; } /// Set the record declaration for captured variables. void setCapturedRecordDecl(RecordDecl *D) { assert(D && "null RecordDecl"); TheRecordDecl = D; } /// True if this variable has been captured. bool capturesVariable(const VarDecl *Var) const; /// An iterator that walks over the captures. using capture_iterator = Capture *; using const_capture_iterator = const Capture *; using capture_range = llvm::iterator_range<capture_iterator>; using capture_const_range = llvm::iterator_range<const_capture_iterator>; capture_range captures() { return capture_range(capture_begin(), capture_end()); } capture_const_range captures() const { return capture_const_range(capture_begin(), capture_end()); } /// Retrieve an iterator pointing to the first capture. capture_iterator capture_begin() { return getStoredCaptures(); } const_capture_iterator capture_begin() const { return getStoredCaptures(); } /// Retrieve an iterator pointing past the end of the sequence of /// captures. capture_iterator capture_end() const { return getStoredCaptures() + NumCaptures; } /// Retrieve the number of captures, including 'this'. unsigned capture_size() const { return NumCaptures; } /// Iterator that walks over the capture initialization arguments. using capture_init_iterator = Expr **; using capture_init_range = llvm::iterator_range<capture_init_iterator>; /// Const iterator that walks over the capture initialization /// arguments. using const_capture_init_iterator = Expr *const *; using const_capture_init_range = llvm::iterator_range<const_capture_init_iterator>; capture_init_range capture_inits() { return capture_init_range(capture_init_begin(), capture_init_end()); } const_capture_init_range capture_inits() const { return const_capture_init_range(capture_init_begin(), capture_init_end()); } /// Retrieve the first initialization argument. capture_init_iterator capture_init_begin() { return reinterpret_cast<Expr **>(getStoredStmts()); } const_capture_init_iterator capture_init_begin() const { return reinterpret_cast<Expr *const *>(getStoredStmts()); } /// Retrieve the iterator pointing one past the last initialization /// argument. capture_init_iterator capture_init_end() { return capture_init_begin() + NumCaptures; } const_capture_init_iterator capture_init_end() const { return capture_init_begin() + NumCaptures; } SourceLocation getBeginLoc() const LLVM_READONLY { return getCapturedStmt()->getBeginLoc(); } SourceLocation getEndLoc() const LLVM_READONLY { return getCapturedStmt()->getEndLoc(); } SourceRange getSourceRange() const LLVM_READONLY { return getCapturedStmt()->getSourceRange(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CapturedStmtClass; } child_range children(); const_child_range children() const; }; } // namespace clang #endif // LLVM_CLANG_AST_STMT_H
graph.h
// Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef GRAPH_H_ #define GRAPH_H_ #include <algorithm> #include <cinttypes> #include <cstddef> #include <iostream> #include <type_traits> #include "pvector.h" #include "util.h" /* GAP Benchmark Suite Class: CSRGraph Author: Scott Beamer Simple container for graph in CSR format - Intended to be constructed by a Builder - To make weighted, set DestID_ template type to NodeWeight - MakeInverse parameter controls whether graph stores its inverse */ // Used to hold node & weight, with another node it makes a weighted edge template <typename NodeID_, typename WeightT_> struct NodeWeight { NodeID_ v; WeightT_ w; NodeWeight() {} NodeWeight(NodeID_ v) : v(v), w(1) {} NodeWeight(NodeID_ v, WeightT_ w) : v(v), w(w) {} bool operator< (const NodeWeight& rhs) const { return v == rhs.v ? w < rhs.w : v < rhs.v; } // doesn't check WeightT_s, needed to remove duplicate edges bool operator== (const NodeWeight& rhs) const { return v == rhs.v; } // doesn't check WeightT_s, needed to remove self edges bool operator== (const NodeID_& rhs) const { return v == rhs; } operator NodeID_() { return v; } void PrintEdgeWeight() { std::cout << " -- v: " << v << "(" << w << ")\n"; } }; template <typename NodeID_, typename WeightT_> std::ostream& operator<<(std::ostream& os, const NodeWeight<NodeID_, WeightT_>& nw) { os << nw.v << " " << nw.w; return os; } template <typename NodeID_, typename WeightT_> std::istream& operator>>(std::istream& is, NodeWeight<NodeID_, WeightT_>& nw) { is >> nw.v >> nw.w; return is; } // Syntatic sugar for an edge template <typename SrcT, typename DstT = SrcT> struct EdgePair { SrcT u; DstT v; EdgePair() {} EdgePair(SrcT u, DstT v) : u(u), v(v) {} }; // SG = serialized graph, these types are for writing graph to file typedef int32_t SGID; typedef EdgePair<SGID> SGEdge; typedef int64_t SGOffset; template <class NodeID_, class DestID_ = NodeID_, bool MakeInverse = true> class CSRGraph { // Used for *non-negative* offsets within a neighborhood typedef std::make_unsigned<std::ptrdiff_t>::type OffsetT; // Used to access neighbors of vertex, basically sugar for iterators class Neighborhood { NodeID_ n_; DestID_** g_index_; OffsetT start_offset_; public: Neighborhood(NodeID_ n, DestID_** g_index, OffsetT start_offset) : n_(n), g_index_(g_index), start_offset_(0) { OffsetT max_offset = end() - begin(); start_offset_ = std::min(start_offset, max_offset); } typedef DestID_* iterator; iterator begin() { return g_index_[n_] + start_offset_; } iterator end() { return g_index_[n_+1]; } }; void ReleaseResources() { if (out_index_ != nullptr) delete[] out_index_; if (out_neighbors_ != nullptr) delete[] out_neighbors_; if (directed_) { if (in_index_ != nullptr) delete[] in_index_; if (in_neighbors_ != nullptr) delete[] in_neighbors_; } } public: CSRGraph() : directed_(false), num_nodes_(-1), num_edges_(-1), out_index_(nullptr), out_neighbors_(nullptr), in_index_(nullptr), in_neighbors_(nullptr) {} CSRGraph(int64_t num_nodes, DestID_** index, DestID_* neighs) : directed_(false), num_nodes_(num_nodes), out_index_(index), out_neighbors_(neighs), in_index_(index), in_neighbors_(neighs) { num_edges_ = (out_index_[num_nodes_] - out_index_[0]) / 2; } CSRGraph(int64_t num_nodes, DestID_** out_index, DestID_* out_neighs, DestID_** in_index, DestID_* in_neighs) : directed_(true), num_nodes_(num_nodes), out_index_(out_index), out_neighbors_(out_neighs), in_index_(in_index), in_neighbors_(in_neighs) { num_edges_ = out_index_[num_nodes_] - out_index_[0]; } CSRGraph(CSRGraph&& other) : directed_(other.directed_), num_nodes_(other.num_nodes_), num_edges_(other.num_edges_), out_index_(other.out_index_), out_neighbors_(other.out_neighbors_), in_index_(other.in_index_), in_neighbors_(other.in_neighbors_) { other.num_edges_ = -1; other.num_nodes_ = -1; other.out_index_ = nullptr; other.out_neighbors_ = nullptr; other.in_index_ = nullptr; other.in_neighbors_ = nullptr; } ~CSRGraph() { ReleaseResources(); } CSRGraph& operator=(CSRGraph&& other) { if (this != &other) { ReleaseResources(); directed_ = other.directed_; num_edges_ = other.num_edges_; num_nodes_ = other.num_nodes_; out_index_ = other.out_index_; out_neighbors_ = other.out_neighbors_; in_index_ = other.in_index_; in_neighbors_ = other.in_neighbors_; other.num_edges_ = -1; other.num_nodes_ = -1; other.out_index_ = nullptr; other.out_neighbors_ = nullptr; other.in_index_ = nullptr; other.in_neighbors_ = nullptr; } return *this; } bool directed() const { return directed_; } int64_t num_nodes() const { return num_nodes_; } int64_t num_edges() const { return num_edges_; } int64_t num_edges_directed() const { return directed_ ? num_edges_ : 2*num_edges_; } int64_t out_degree(NodeID_ v) const { return out_index_[v+1] - out_index_[v]; } int64_t in_degree(NodeID_ v) const { static_assert(MakeInverse, "Graph inversion disabled but reading inverse"); return in_index_[v+1] - in_index_[v]; } Neighborhood out_neigh(NodeID_ n, OffsetT start_offset = 0) const { return Neighborhood(n, out_index_, start_offset); } Neighborhood in_neigh(NodeID_ n, OffsetT start_offset = 0) const { static_assert(MakeInverse, "Graph inversion disabled but reading inverse"); return Neighborhood(n, in_index_, start_offset); } void PrintStats() const { std::cout << "Graph has " << num_nodes_ << " nodes and " << num_edges_ << " "; if (!directed_) std::cout << "un"; std::cout << "directed edges for degree: "; std::cout << num_edges_/num_nodes_ << std::endl; } void PrintTopology() const { for (NodeID_ i=0; i < num_nodes_; i++) { std::cout << i << ": "; for (DestID_ j : out_neigh(i)) { std::cout << j << " "; } std::cout << std::endl; } } static DestID_** GenIndex(const pvector<SGOffset> &offsets, DestID_* neighs) { NodeID_ length = offsets.size(); DestID_** index = new DestID_*[length]; #pragma omp parallel for for (NodeID_ n=0; n < length; n++) index[n] = neighs + offsets[n]; return index; } pvector<SGOffset> VertexOffsets(bool in_graph = false) const { pvector<SGOffset> offsets(num_nodes_+1); for (NodeID_ n=0; n < num_nodes_+1; n++) if (in_graph) offsets[n] = in_index_[n] - in_index_[0]; else offsets[n] = out_index_[n] - out_index_[0]; return offsets; } Range<NodeID_> vertices() const { return Range<NodeID_>(num_nodes()); } /* Helper function to print outgoing neighbors of a node with their weights */ void PrintNeighbors(NodeID_ node_id) const { std::cout << "Printing neighbors for " << node_id << std::endl; for(auto v : out_neigh(node_id)) std::cout << " -- v: " << v.v << " (" << v.w << ")" << std::endl; } /* Function to calculate the difference between max and min timestamp difference from all outgoing edges from a node. TODO: integrate this while building a graph so we don't have to recompute this every time? */ float TimeBoundsDelta(NodeID_ node_id) const { // PrintNeighbors(node_id); float min_bound = 0, max_bound = 0; int cnt = 0; for(auto v : out_neigh(node_id)) { if(cnt == 0) min_bound = max_bound = v.w; if(v.w < min_bound) min_bound = v.w; if(v.w > max_bound) max_bound = v.w; cnt++; } return (max_bound - min_bound); } bool EdgeExists(NodeID_ src_node, NodeID_ dst_node) const { for(auto v : out_neigh(src_node)) { if(v.v == dst_node) return true; } return false; } public: bool directed_; int64_t num_nodes_; int64_t num_edges_; DestID_** out_index_; DestID_* out_neighbors_; DestID_** in_index_; DestID_* in_neighbors_; }; #endif // GRAPH_H_
9.norace4.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define N 100 int main() { int sum = 0; #pragma omp ordered for (int i = 0; i < N; i++) { sum += i; } return 0; } // We do not support inter SCoP data races for now // CHECK: Region is Data Race Free. // END
pt_to_pt_haloexchange.c
/***************************************************************************** * * * Mixed-mode OpenMP/MPI MicroBenchmark Suite - Version 1.0 * * * * produced by * * * * Mark Bull, Jim Enright and Fiona Reid * * * * at * * * * Edinburgh Parallel Computing Centre * * * * email: markb@epcc.ed.ac.uk, fiona@epcc.ed.ac.uk * * * * * * Copyright 2012, The University of Edinburgh * * * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ****************************************************************************/ /*-----------------------------------------------------------*/ /* Contains the point-to-point halo exchange mixed mode */ /* OpenMP/MPI benchmarks. */ /* This includes: -masteronly haloexchange */ /* -funnelled haloexchange */ /* -multiple haloexchange */ /*-----------------------------------------------------------*/ #include "pt_to_pt_haloexchange.h" /*-----------------------------------------------------------*/ /* haloExchange */ /* */ /* Driver subroutine for the haloExchange benchmark. */ /*-----------------------------------------------------------*/ int haloExchange(int benchmarkType){ int dataSizeIter; /* find the ranks of the left and right neighbour */ findNeighbours(); /* initialise repsToDo to defaultReps */ repsToDo = defaultReps; /* Start loop over data sizes */ dataSizeIter = minDataSize; /* Initialise dataSizeIter */ while (dataSizeIter <= maxDataSize){ /* set sizeofBuffer */ sizeofBuffer = dataSizeIter * numThreads; /*Allocate space for the main data arrays */ allocateHaloexchangeData(sizeofBuffer); /* perform benchmark warm-up */ if (benchmarkType == MASTERONLY){ masteronlyHaloexchange(warmUpIters, dataSizeIter); } else if (benchmarkType == FUNNELLED){ funnelledHaloexchange(warmUpIters, dataSizeIter); } else if (benchmarkType == MULTIPLE){ multipleHaloexchange(warmUpIters, dataSizeIter); } /* Each process performs a verification test */ testHaloexchange(sizeofBuffer, dataSizeIter); /*Initialise the benchmark */ benchComplete = FALSE; /*Execute benchmark until target time is reached */ while (benchComplete != TRUE){ /*Start timer */ MPI_Barrier(comm); startTime = MPI_Wtime(); /*Execute benchmarkType for repsToDo repetitions*/ if (benchmarkType == MASTERONLY){ masteronlyHaloexchange(repsToDo, dataSizeIter); } else if (benchmarkType == FUNNELLED){ funnelledHaloexchange(repsToDo, dataSizeIter); } else if (benchmarkType == MULTIPLE){ multipleHaloexchange(repsToDo, dataSizeIter); } /*Stop timer */ MPI_Barrier(comm); finishTime = MPI_Wtime(); totalTime = finishTime - startTime; /* Test if target time is reached with the number of reps */ if (myMPIRank==0){ benchComplete = repTimeCheck(totalTime, repsToDo); } /* Ensure all procs have the same value of benchComplete */ /* and repsToDo */ MPI_Bcast(&benchComplete, 1, MPI_INT, 0, comm); MPI_Bcast(&repsToDo, 1, MPI_INT, 0, comm); } /* Master process sets benchmark results */ if (myMPIRank == 0 ){ setReportParams(dataSizeIter, repsToDo, totalTime); printReport(); } /* Free allocated data */ freeHaloexchangeData(); /* Double dataSize and loop again */ dataSizeIter = dataSizeIter * 2; } return 0; } /*-----------------------------------------------------------*/ /* masteronlyHaloexchange */ /* */ /* Each process exchanges a message with its left and */ /* right neighbour. */ /* Communication takes place outside of the parallel */ /* region. */ /*-----------------------------------------------------------*/ int masteronlyHaloexchange(int totalReps, int dataSize){ int repIter, i; for (repIter=0; repIter<totalReps; repIter++){ /* Each thread writes its globalID to rightSendBuf * and leftSendBuf using a parallel for directive. */ #pragma omp parallel for default(none) \ private(i) \ shared(leftSendBuf,rightSendBuf,dataSize) \ shared(sizeofBuffer,globalIDarray) \ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ leftSendBuf[i] = globalIDarray[myThreadID]; rightSendBuf[i] = globalIDarray[myThreadID]; } /* Process starts send of data to leftNeighbour and * rightNeighbour using non-blocking send... */ MPI_Isend(leftSendBuf, sizeofBuffer, MPI_INT, leftNeighbour, \ TAG, commCart, &requestArray[0]); MPI_Isend(rightSendBuf, sizeofBuffer, MPI_INT, rightNeighbour, \ TAG, commCart, &requestArray[1]); /* Process then waits for messages from leftNeighbour and rightNeighbour */ MPI_Irecv(leftRecvBuf, sizeofBuffer, MPI_INT, leftNeighbour, \ TAG, commCart, &requestArray[2]); MPI_Irecv(rightRecvBuf, sizeofBuffer, MPI_INT, rightNeighbour, \ TAG, commCart, &requestArray[3]); /* Finish the sends with an MPI_Waitall on the requests */ MPI_Waitall(4, requestArray, statusArray); /* Each thread now reads its part of the left and right * received buffers. */ #pragma omp parallel for default(none) \ private(i) \ shared(leftRecvBuf,rightRecvBuf,dataSize,sizeofBuffer) \ shared(finalLeftBuf,finalRightBuf) \ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ finalLeftBuf[i] = leftRecvBuf[i]; finalRightBuf[i] = rightRecvBuf[i]; } } return 0; } /*-----------------------------------------------------------*/ /* funnelledHaloexchange */ /* */ /* Each process exchanges a message with its left and */ /* right neighbour. */ /* Communication takes place by one thread inside of the */ /* parallel region. */ /*-----------------------------------------------------------*/ int funnelledHaloexchange(int totalReps, int dataSize){ int repIter, i; /* Open the parallel region */ #pragma omp parallel default(none) \ private(i,repIter) \ shared(dataSize,sizeofBuffer,leftSendBuf,rightSendBuf) \ shared(rightRecvBuf,leftRecvBuf,finalLeftBuf,finalRightBuf) \ shared(globalIDarray,commCart,totalReps,requestArray,statusArray) \ shared(leftNeighbour,rightNeighbour) { for (repIter=0; repIter<totalReps; repIter++){ /* Each thread writes its globalID to rightSendBuf * and leftSendBuf. */ #pragma omp for schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ leftSendBuf[i] = globalIDarray[myThreadID]; rightSendBuf[i] = globalIDarray[myThreadID]; } /* Implicit barrier here takes care of necessary synchronisation */ #pragma omp master { /* Master thread starts send of data to left and right neighbours * with a non-blocking send. */ MPI_Isend(leftSendBuf, sizeofBuffer, MPI_INT, leftNeighbour, \ TAG, commCart, &requestArray[0]); MPI_Isend(rightSendBuf, sizeofBuffer, MPI_INT, rightNeighbour, \ TAG, commCart, &requestArray[1]); /* Thread then starts receive of messages from leftNeighbour * and rightNeighbour. */ MPI_Irecv(leftRecvBuf, sizeofBuffer, MPI_INT, leftNeighbour, \ TAG, commCart, &requestArray[2]); MPI_Irecv(rightRecvBuf, sizeofBuffer, MPI_INT, rightNeighbour, \ TAG, commCart, &requestArray[3]); /* Finish the sends and receives with an MPI_Waitall on the requests */ MPI_Waitall(4, requestArray, statusArray); } /*Barrier to ensure master thread has completed transfer. */ #pragma omp barrier /* Each thread now reads its part of the left and right received buffers. */ #pragma omp for schedule(static,dataSize) for(i=0; i<sizeofBuffer; i++){ finalLeftBuf[i] = leftRecvBuf[i]; finalRightBuf[i] = rightRecvBuf[i]; } } } return 0; } /*-----------------------------------------------------------*/ /* multipleHaloexchange */ /* */ /* Each process exchanges a message with its left and */ /* right neighbour. */ /* All threads take part in the inter-porcess */ /* communication. */ /*-----------------------------------------------------------*/ int multipleHaloexchange(int totalReps, int dataSize){ int repIter, i; int lBound; /* Open the parallel region */ #pragma omp parallel default(none) \ private(i,requestArray,statusArray,lBound,repIter) \ shared(dataSize,sizeofBuffer,leftSendBuf,rightSendBuf) \ shared(rightRecvBuf,leftRecvBuf,finalLeftBuf,finalRightBuf) \ shared(leftNeighbour,rightNeighbour,globalIDarray,commCart,totalReps) { for (repIter=0; repIter<totalReps; repIter++){ /* Calculate lower bound for each thread */ lBound = (myThreadID * dataSize); /* Each thread writes its globalID to rightSendBuf * and leftSendBuf. */ #pragma omp for nowait schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ leftSendBuf[i] = globalIDarray[myThreadID]; rightSendBuf[i] = globalIDarray[myThreadID]; } /* Each thread starts send of dataSize items to leftNeighbour * and to rightNeighbour. */ MPI_Isend(&leftSendBuf[lBound], dataSize, MPI_INT, leftNeighbour, \ myThreadID, commCart, &requestArray[0]); MPI_Isend(&rightSendBuf[lBound], dataSize, MPI_INT, rightNeighbour, \ myThreadID, commCart, &requestArray[1]); /* Each Thread then starts receive of messages from leftNeighbour * and rightNeighbour. */ MPI_Irecv(&leftRecvBuf[lBound], dataSize, MPI_INT, leftNeighbour, \ myThreadID, commCart, &requestArray[2]); MPI_Irecv(&rightRecvBuf[lBound], dataSize, MPI_INT, rightNeighbour, \ myThreadID, commCart, &requestArray[3]); /* Finish the sends with an MPI_Waitall on the requests */ MPI_Waitall(4, requestArray, statusArray); /* Each thread now reads its part of the left and * right received buffers. */ #pragma omp for nowait schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ finalLeftBuf[i] = leftRecvBuf[i]; finalRightBuf[i] = rightRecvBuf[i]; } } } return 0; } /*-----------------------------------------------------------*/ /* allocateHaloexchangeData */ /* */ /* Allocate memory for the main data arrays in the */ /* haloexchange. */ /*-----------------------------------------------------------*/ int allocateHaloexchangeData(int sizeofBuffer){ leftSendBuf = (int *)malloc(sizeofBuffer * sizeof(int)); leftRecvBuf = (int *)malloc(sizeofBuffer * sizeof(int)); rightSendBuf = (int *)malloc(sizeofBuffer * sizeof(int)); rightRecvBuf = (int *)malloc(sizeofBuffer * sizeof(int)); finalLeftBuf = (int *)malloc(sizeofBuffer * sizeof(int)); finalRightBuf = (int *)malloc(sizeofBuffer * sizeof(int)); return 0; } /*-----------------------------------------------------------*/ /* freeHaloexchangeData */ /* */ /* Deallocates the storage space for the main data arrays. */ /*-----------------------------------------------------------*/ int freeHaloexchangeData(){ free(leftSendBuf); free(leftRecvBuf); free(rightSendBuf); free(rightRecvBuf); free(finalLeftBuf); free(finalRightBuf); return 0; } /*-----------------------------------------------------------*/ /* testHaloexchange */ /* */ /* Verifies that the halo exchange benchmark worked */ /* correctly. */ /*-----------------------------------------------------------*/ int testHaloexchange(int sizeofBuffer, int dataSize){ int i; int testFlag, reduceFlag; int *testLeftBuf, *testRightBuf; /* set testFlag to true */ testFlag = TRUE; /*allocate space for testLeftBuf and testRightBuf */ testLeftBuf = (int *)malloc(sizeofBuffer * sizeof(int)); testRightBuf = (int *)malloc(sizeofBuffer * sizeof(int)); /*construct testLeftBuf and testRightBuf with correct values */ #pragma omp parallel for default(none) \ private(i) \ shared(leftNeighbour,rightNeighbour,numThreads) \ shared(dataSize,sizeofBuffer,testLeftBuf,testRightBuf) \ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ /* Calculate globalID of thread expected in finalLeftBuf.. */ testLeftBuf[i] = (leftNeighbour * numThreads) + myThreadID; /* ..and in finalRightBuf. */ testRightBuf[i] = (rightNeighbour * numThreads) + myThreadID; } /* Compare.. */ for (i=0; i<sizeofBuffer; i++){ /* 1) values from left neighbour */ if (testLeftBuf[i] != finalLeftBuf[i]){ testFlag = FALSE; } /* 2) values from right neighbour */ if (testRightBuf[i] != finalRightBuf[i]){ testFlag = FALSE; } } MPI_Reduce(&testFlag, &reduceFlag, 1, MPI_INT, MPI_LAND, 0, comm); /* Master then sets testOutcome flag */ if (myMPIRank == 0){ setTestOutcome(reduceFlag); } /* free space for testLeftBuf and testRightBuf */ free(testLeftBuf); free(testRightBuf); return 0; }
GB_binop__min_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__min_int8) // A.*B function (eWiseMult): GB (_AemultB_08__min_int8) // A.*B function (eWiseMult): GB (_AemultB_02__min_int8) // A.*B function (eWiseMult): GB (_AemultB_04__min_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__min_int8) // A*D function (colscale): GB (_AxD__min_int8) // D*A function (rowscale): GB (_DxB__min_int8) // C+=B function (dense accum): GB (_Cdense_accumB__min_int8) // C+=b function (dense accum): GB (_Cdense_accumb__min_int8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_int8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_int8) // C=scalar+B GB (_bind1st__min_int8) // C=scalar+B' GB (_bind1st_tran__min_int8) // C=A+scalar GB (_bind2nd__min_int8) // C=A'+scalar GB (_bind2nd_tran__min_int8) // C type: int8_t // A type: int8_t // B,b type: int8_t // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ int8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int8_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IMIN (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MIN || GxB_NO_INT8 || GxB_NO_MIN_INT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__min_int8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__min_int8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__min_int8) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__min_int8) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__min_int8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__min_int8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__min_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__min_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__min_int8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__min_int8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *Cx = (int8_t *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__min_int8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int8_t *Cx = (int8_t *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IMIN (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (x, aij) ; \ } GrB_Info GB (_bind1st_tran__min_int8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GrB_Type_wait.c
//------------------------------------------------------------------------------ // GrB_Type_wait: wait for a user-defined GrB_Type to complete //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // In SuiteSparse:GraphBLAS, a user-defined GrB_Type has no pending operations // to wait for. All this method does is verify that the type is properly // initialized, and then it does an OpenMP flush. #include "GB.h" GrB_Info GrB_Type_wait // no work, just check if the GrB_Type is valid ( GrB_Type type, GrB_WaitMode waitmode ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GB_WHERE1 ("GrB_Type_wait (type, waitmode)") ; GB_RETURN_IF_NULL_OR_FAULTY (type) ; //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- #pragma omp flush return (GrB_SUCCESS) ; }
burgers1d_perf_b.c
#ifndef TAPENADE #include <math.h> #endif #define Max(x,y) fmax(x,y) #define Min(x,y) fmin(x,y) #define Heaviside(x) ((x>=0)?1.0:0.0) #define u(x) u[x] #define u_b(x) u_b[x] #define u_1(x) u_1[x] #define u_1_b(x) u_1_b[x] void burgers1d_perf_b(double* u, double* u_b, double* u_1, double* u_1_b, double D, double C, int n) { int i; i=0; u_1_b(i) += (C*Max(0, u_1(i + 1)) + D)*u_b(i + 1); i=n - 2; u_1_b(i) += (-C*((-u_1(i) + u_1(i + 1))*Heaviside(-u_1(i)) + (u_1(i) - u_1(i - 1))*Heaviside(u_1(i)) + Max(0, u_1(i)) - Min(0, u_1(i))) - 2.0*D + 1)*u_b(i); u_1_b(i) += (-C*Min(0, u_1(i - 1)) + D)*u_b(i - 1); i=1; u_1_b(i) += (C*Max(0, u_1(i + 1)) + D)*u_b(i + 1); u_1_b(i) += (-C*((-u_1(i) + u_1(i + 1))*Heaviside(-u_1(i)) + (u_1(i) - u_1(i - 1))*Heaviside(u_1(i)) + Max(0, u_1(i)) - Min(0, u_1(i))) - 2.0*D + 1)*u_b(i); i=n - 1; u_1_b(i) += (-C*Min(0, u_1(i - 1)) + D)*u_b(i - 1); #pragma omp parallel for private(i) for ( i=2; i<=n - 3; i++ ) { u_1_b(i) += (C*Max(0, u_1(i + 1)) + D)*u_b(i + 1); u_1_b(i) += (-C*((-u_1(i) + u_1(i + 1))*Heaviside(-u_1(i)) + (u_1(i) - u_1(i - 1))*Heaviside(u_1(i)) + Max(0, u_1(i)) - Min(0, u_1(i))) - 2.0*D + 1)*u_b(i); u_1_b(i) += (-C*Min(0, u_1(i - 1)) + D)*u_b(i - 1); } }
DRB114-if-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. */ /* When if() evalutes to true, this program has data races due to true dependence within the loop at 65. Data race pair: a[i+1]@66:5 vs. a[i]@66:12 */ #include <stdlib.h> #include <stdio.h> #include <time.h> int main(int argc, char* argv[]) { int i; int len=100; int a[100]; for (i=0;i<len;i++) a[i]=i; srand(time(NULL)); #pragma omp parallel for if (rand()%2) for (i=0;i<len-1;i++) a[i+1]=a[i]+1; printf("a[50]=%d\n", a[50]); return 0; }
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 32; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
GB_unop__identity_int64_uint32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef 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__identity_int64_uint32) // op(A') function: GB (_unop_tran__identity_int64_uint32) // C type: int64_t // A type: uint32_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int64_t z = (int64_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int64_t z = (int64_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT64 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int64_uint32) ( int64_t *Cx, // Cx and Ax may be aliased const uint32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t aij = Ax [p] ; int64_t z = (int64_t) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint32_t aij = Ax [p] ; int64_t z = (int64_t) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int64_uint32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
gbdt.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_BOOSTING_GBDT_H_ #define LIGHTGBM_BOOSTING_GBDT_H_ #include <LightGBM/boosting.h> #include <LightGBM/objective_function.h> #include <LightGBM/prediction_early_stop.h> #include <string> #include <algorithm> #include <cstdio> #include <fstream> #include <map> #include <memory> #include <mutex> #include <unordered_map> #include <utility> #include <vector> #include <LightGBM/json11.hpp> #include "score_updater.hpp" using namespace json11; namespace LightGBM { /*! * \brief GBDT algorithm implementation. including Training, prediction, bagging. */ class GBDT : public GBDTBase { public: /*! * \brief Constructor */ GBDT(); /*! * \brief Destructor */ ~GBDT(); /*! * \brief Initialization logic * \param gbdt_config Config for boosting * \param train_data Training data * \param objective_function Training objective function * \param training_metrics Training metrics */ void Init(const Config* gbdt_config, const Dataset* train_data, const ObjectiveFunction* objective_function, const std::vector<const Metric*>& training_metrics) override; /*! * \brief Merge model from other boosting object. Will insert to the front of current boosting object * \param other */ void MergeFrom(const Boosting* other) override { auto other_gbdt = reinterpret_cast<const GBDT*>(other); // tmp move to other vector auto original_models = std::move(models_); models_ = std::vector<std::unique_ptr<Tree>>(); // push model from other first for (const auto& tree : other_gbdt->models_) { auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get()))); models_.push_back(std::move(new_tree)); } num_init_iteration_ = static_cast<int>(models_.size()) / num_tree_per_iteration_; // push model in current object for (const auto& tree : original_models) { auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get()))); models_.push_back(std::move(new_tree)); } num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_; } void ShuffleModels(int start_iter, int end_iter) override { int total_iter = static_cast<int>(models_.size()) / num_tree_per_iteration_; start_iter = std::max(0, start_iter); if (end_iter <= 0) { end_iter = total_iter; } end_iter = std::min(total_iter, end_iter); auto original_models = std::move(models_); std::vector<int> indices(total_iter); for (int i = 0; i < total_iter; ++i) { indices[i] = i; } Random tmp_rand(17); for (int i = start_iter; i < end_iter - 1; ++i) { int j = tmp_rand.NextShort(i + 1, end_iter); std::swap(indices[i], indices[j]); } models_ = std::vector<std::unique_ptr<Tree>>(); for (int i = 0; i < total_iter; ++i) { for (int j = 0; j < num_tree_per_iteration_; ++j) { int tree_idx = indices[i] * num_tree_per_iteration_ + j; auto new_tree = std::unique_ptr<Tree>(new Tree(*(original_models[tree_idx].get()))); models_.push_back(std::move(new_tree)); } } } /*! * \brief Reset the training data * \param train_data New Training data * \param objective_function Training objective function * \param training_metrics Training metrics */ void ResetTrainingData(const Dataset* train_data, const ObjectiveFunction* objective_function, const std::vector<const Metric*>& training_metrics) override; /*! * \brief Reset Boosting Config * \param gbdt_config Config for boosting */ void ResetConfig(const Config* gbdt_config) override; /*! * \brief Adding a validation dataset * \param valid_data Validation dataset * \param valid_metrics Metrics for validation dataset */ void AddValidDataset(const Dataset* valid_data, const std::vector<const Metric*>& valid_metrics) override; /*! * \brief Perform a full training procedure * \param snapshot_freq frequence of snapshot * \param model_output_path path of model file */ void Train(int snapshot_freq, const std::string& model_output_path) override; void RefitTree(const std::vector<std::vector<int>>& tree_leaf_prediction) override; /*! * \brief Training logic * \param gradients nullptr for using default objective, otherwise use self-defined boosting * \param hessians nullptr for using default objective, otherwise use self-defined boosting * \return True if cannot train any more */ bool TrainOneIter(const score_t* gradients, const score_t* hessians) override; /*! * \brief Rollback one iteration */ void RollbackOneIter() override; /*! * \brief Get current iteration */ int GetCurrentIteration() const override { return static_cast<int>(models_.size()) / num_tree_per_iteration_; } /*! * \brief Can use early stopping for prediction or not * \return True if cannot use early stopping for prediction */ bool NeedAccuratePrediction() const override { if (objective_function_ == nullptr) { return true; } else { return objective_function_->NeedAccuratePrediction(); } } /*! * \brief Get evaluation result at data_idx data * \param data_idx 0: training data, 1: 1st validation data * \return evaluation result */ std::vector<double> GetEvalAt(int data_idx) const override; /*! * \brief Get current training score * \param out_len length of returned score * \return training score */ const double* GetTrainingScore(int64_t* out_len) override; /*! * \brief Get size of prediction at data_idx data * \param data_idx 0: training data, 1: 1st validation data * \return The size of prediction */ int64_t GetNumPredictAt(int data_idx) const override { CHECK(data_idx >= 0 && data_idx <= static_cast<int>(valid_score_updater_.size())); data_size_t num_data = train_data_->num_data(); if (data_idx > 0) { num_data = valid_score_updater_[data_idx - 1]->num_data(); } return num_data * num_class_; } /*! * \brief Get prediction result at data_idx data * \param data_idx 0: training data, 1: 1st validation data * \param result used to store prediction result, should allocate memory before call this function * \param out_len length of returned score */ void GetPredictAt(int data_idx, double* out_result, int64_t* out_len) override; /*! * \brief Get number of prediction for one data * \param num_iteration number of used iterations * \param is_pred_leaf True if predicting leaf index * \param is_pred_contrib True if predicting feature contribution * \return number of prediction */ inline int NumPredictOneRow(int num_iteration, bool is_pred_leaf, bool is_pred_contrib) const override { int num_preb_in_one_row = num_class_; if (is_pred_leaf) { int max_iteration = GetCurrentIteration(); if (num_iteration > 0) { num_preb_in_one_row *= static_cast<int>(std::min(max_iteration, num_iteration)); } else { num_preb_in_one_row *= max_iteration; } } else if (is_pred_contrib) { num_preb_in_one_row = num_tree_per_iteration_ * (max_feature_idx_ + 2); // +1 for 0-based indexing, +1 for baseline } return num_preb_in_one_row; } void PredictRaw(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const override; void PredictRawByMap(const std::unordered_map<int, double>& features, double* output, const PredictionEarlyStopInstance* early_stop) const override; void Predict(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const override; void PredictByMap(const std::unordered_map<int, double>& features, double* output, const PredictionEarlyStopInstance* early_stop) const override; void PredictLeafIndex(const double* features, double* output) const override; void PredictLeafIndexByMap(const std::unordered_map<int, double>& features, double* output) const override; void PredictContrib(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const override; /*! * \brief Dump model to json format string * \param start_iteration The model will be saved start from * \param num_iteration Number of iterations that want to dump, -1 means dump all * \return Json format string of model */ std::string DumpModel(int start_iteration, int num_iteration) const override; /*! * \brief Translate model to if-else statement * \param num_iteration Number of iterations that want to translate, -1 means translate all * \return if-else format codes of model */ std::string ModelToIfElse(int num_iteration) const override; /*! * \brief Translate model to if-else statement * \param num_iteration Number of iterations that want to translate, -1 means translate all * \param filename Filename that want to save to * \return is_finish Is training finished or not */ bool SaveModelToIfElse(int num_iteration, const char* filename) const override; /*! * \brief Save model to file * \param start_iteration The model will be saved start from * \param num_iterations Number of model that want to save, -1 means save all * \param filename Filename that want to save to * \return is_finish Is training finished or not */ bool SaveModelToFile(int start_iteration, int num_iterations, const char* filename) const override; /*! * \brief Save model to string * \param start_iteration The model will be saved start from * \param num_iterations Number of model that want to save, -1 means save all * \return Non-empty string if succeeded */ std::string SaveModelToString(int start_iteration, int num_iterations) const override; /*! * \brief Restore from a serialized buffer */ bool LoadModelFromString(const char* buffer, size_t len) override; /*! * \brief Calculate feature importances * \param num_iteration Number of model that want to use for feature importance, -1 means use all * \param importance_type: 0 for split, 1 for gain * \return vector of feature_importance */ std::vector<double> FeatureImportance(int num_iteration, int importance_type) const override; /*! * \brief Get max feature index of this model * \return Max feature index of this model */ inline int MaxFeatureIdx() const override { return max_feature_idx_; } /*! * \brief Get feature names of this model * \return Feature names of this model */ inline std::vector<std::string> FeatureNames() const override { return feature_names_; } /*! * \brief Get index of label column * \return index of label column */ inline int LabelIdx() const override { return label_idx_; } /*! * \brief Get number of weak sub-models * \return Number of weak sub-models */ inline int NumberOfTotalModel() const override { return static_cast<int>(models_.size()); } /*! * \brief Get number of tree per iteration * \return number of tree per iteration */ inline int NumModelPerIteration() const override { return num_tree_per_iteration_; } /*! * \brief Get number of classes * \return Number of classes */ inline int NumberOfClasses() const override { return num_class_; } inline void InitPredict(int num_iteration, bool is_pred_contrib) override { num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_; if (num_iteration > 0) { num_iteration_for_pred_ = std::min(num_iteration, num_iteration_for_pred_); } if (is_pred_contrib) { #pragma omp parallel for schedule(static) for (int i = 0; i < static_cast<int>(models_.size()); ++i) { models_[i]->RecomputeMaxDepth(); } } } inline double GetLeafValue(int tree_idx, int leaf_idx) const override { CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size()); CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves()); return models_[tree_idx]->LeafOutput(leaf_idx); } inline void SetLeafValue(int tree_idx, int leaf_idx, double val) override { CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size()); CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves()); models_[tree_idx]->SetLeafOutput(leaf_idx, val); } /*! * \brief Get Type name of this boosting object */ const char* SubModelName() const override { return "tree"; } protected: /*! * \brief Print eval result and check early stopping */ virtual bool EvalAndCheckEarlyStopping(); /*! * \brief reset config for bagging */ void ResetBaggingConfig(const Config* config, bool is_change_dataset); /*! * \brief Implement bagging logic * \param iter Current interation */ virtual void Bagging(int iter); /*! * \brief Helper function for bagging, used for multi-threading optimization * \param start start indice of bagging * \param cnt count * \param buffer output buffer * \return count of left size */ data_size_t BaggingHelper(Random* cur_rand, data_size_t start, data_size_t cnt, data_size_t* buffer); /*! * \brief Helper function for bagging, used for multi-threading optimization, balanced sampling * \param start start indice of bagging * \param cnt count * \param buffer output buffer * \return count of left size */ data_size_t BalancedBaggingHelper(Random* cur_rand, data_size_t start, data_size_t cnt, data_size_t* buffer); /*! * \brief calculate the object function */ virtual void Boosting(); /*! * \brief updating score after tree was trained * \param tree Trained tree of this iteration * \param cur_tree_id Current tree for multiclass training */ virtual void UpdateScore(const Tree* tree, const int cur_tree_id); /*! * \brief eval results for one metric */ virtual std::vector<double> EvalOneMetric(const Metric* metric, const double* score) const; /*! * \brief Print metric result of current iteration * \param iter Current interation * \return best_msg if met early_stopping */ std::string OutputMetric(int iter); double BoostFromAverage(int class_id, bool update_scorer); /*! \brief current iteration */ int iter_; /*! \brief Pointer to training data */ const Dataset* train_data_; /*! \brief Config of gbdt */ std::unique_ptr<Config> config_; /*! \brief Tree learner, will use this class to learn trees */ std::unique_ptr<TreeLearner> tree_learner_; /*! \brief Objective function */ const ObjectiveFunction* objective_function_; /*! \brief Store and update training data's score */ std::unique_ptr<ScoreUpdater> train_score_updater_; /*! \brief Metrics for training data */ std::vector<const Metric*> training_metrics_; /*! \brief Store and update validation data's scores */ std::vector<std::unique_ptr<ScoreUpdater>> valid_score_updater_; /*! \brief Metric for validation data */ std::vector<std::vector<const Metric*>> valid_metrics_; /*! \brief Number of rounds for early stopping */ int early_stopping_round_; /*! \brief Only use first metric for early stopping */ bool es_first_metric_only_; /*! \brief Best iteration(s) for early stopping */ std::vector<std::vector<int>> best_iter_; /*! \brief Best score(s) for early stopping */ std::vector<std::vector<double>> best_score_; /*! \brief output message of best iteration */ std::vector<std::vector<std::string>> best_msg_; /*! \brief Trained models(trees) */ std::vector<std::unique_ptr<Tree>> models_; /*! \brief Max feature index of training data*/ int max_feature_idx_; /*! \brief First order derivative of training data */ std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> gradients_; /*! \brief Secend order derivative of training data */ std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> hessians_; /*! \brief Store the indices of in-bag data */ std::vector<data_size_t, Common::AlignmentAllocator<data_size_t, kAlignedSize>> bag_data_indices_; /*! \brief Number of in-bag data */ data_size_t bag_data_cnt_; /*! \brief Store the indices of in-bag data */ std::vector<data_size_t> tmp_indices_; /*! \brief Number of training data */ data_size_t num_data_; /*! \brief Number of trees per iterations */ int num_tree_per_iteration_; /*! \brief Number of class */ int num_class_; /*! \brief Index of label column */ data_size_t label_idx_; /*! \brief number of used model */ int num_iteration_for_pred_; /*! \brief Shrinkage rate for one iteration */ double shrinkage_rate_; /*! \brief Number of loaded initial models */ int num_init_iteration_; /*! \brief Feature names */ std::vector<std::string> feature_names_; std::vector<std::string> feature_infos_; /*! \brief number of threads */ int num_threads_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> offsets_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> left_cnts_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> right_cnts_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> left_write_pos_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> right_write_pos_buf_; std::unique_ptr<Dataset> tmp_subset_; bool is_use_subset_; std::vector<bool> class_need_train_; bool is_constant_hessian_; std::unique_ptr<ObjectiveFunction> loaded_objective_; bool average_output_; bool need_re_bagging_; bool balanced_bagging_; std::string loaded_parameter_; std::vector<int8_t> monotone_constraints_; Json forced_splits_json_; }; } // namespace LightGBM #endif // LightGBM_BOOSTING_GBDT_H_
mmul_omp.c
/* This file is part of ParTI!. ParTI! 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 3 of the License, or (at your option) any later version. ParTI! is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with ParTI!. If not, see <http://www.gnu.org/licenses/>. */ #include <ParTI.h> #include <stdlib.h> #include "sptensor.h" int sptOmpSparseTensorMulMatrix(sptSemiSparseTensor *Y, sptSparseTensor *X, const sptMatrix *U, sptIndex const mode) { int result; sptIndex *ind_buf; sptIndex m; sptNnzIndexVector fiberidx; if(mode >= X->nmodes) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "OMP SpTns * Mtx", "shape mismatch"); } if(X->ndims[mode] != U->nrows) { spt_CheckError(SPTERR_SHAPE_MISMATCH, "OMP SpTns * Mtx", "shape mismatch"); } sptSparseTensorSortIndexAtMode(X, mode, 0, 1); ind_buf = malloc(X->nmodes * sizeof *ind_buf); spt_CheckOSError(!ind_buf, "OMP SpTns * Mtx"); for(m = 0; m < X->nmodes; ++m) { ind_buf[m] = X->ndims[m]; } ind_buf[mode] = U->ncols; result = sptNewSemiSparseTensor(Y, X->nmodes, mode, ind_buf); free(ind_buf); spt_CheckError(result, "OMP SpTns * Mtx", NULL); sptSemiSparseTensorSetIndices(Y, &fiberidx, X); sptTimer timer; sptNewTimer(&timer, 0); sptStartTimer(timer); struct timeval start_t, end_t; //声明时间结构体变量 // 时间 gettimeofday(&start_t, NULL); //记录开始的时间 //--- #pragma omp parallel for for(sptNnzIndex i = 0; i < Y->nnz; ++i) { sptNnzIndex inz_begin = fiberidx.data[i]; sptNnzIndex inz_end = fiberidx.data[i+1]; // jli: exchange two loops for(sptNnzIndex j = inz_begin; j < inz_end; ++j) { sptIndex r = X->inds[mode].data[j]; for(sptIndex k = 0; k < U->ncols; ++k) { Y->values.values[i*Y->stride + k] += X->values.data[j] * U->values[r*U->stride + k]; } } } //{需要计时的代码块} //--- gettimeofday(&end_t, NULL); //记录结束的时间 double total_t_sec, total_t_usec, total_t; //变量声明 total_t_sec = (double)(end_t.tv_sec - start_t.tv_sec); //计算秒数 total_t_usec = (double)(end_t.tv_usec - start_t.tv_usec); //计算微秒数 total_t = total_t_sec + total_t_usec / 1000000.0; //计算总时间 printf("cost time:%lf \n",total_t); sptStopTimer(timer); // sptPrintElapsedTime(timer, "OMP SpTns * Mtx"); sptFreeTimer(timer); sptFreeNnzIndexVector(&fiberidx); return 0; }
Parallelizer.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_PARALLELIZER_H #define EIGEN_PARALLELIZER_H namespace Eigen { namespace internal { /** \internal */ inline void manage_multi_threading(Action action, int* v) { static EIGEN_UNUSED int m_maxThreads = -1; if(action==SetAction) { eigen_internal_assert(v!=0); m_maxThreads = *v; } else if(action==GetAction) { eigen_internal_assert(v!=0); #ifdef EIGEN_HAS_OPENMP if(m_maxThreads>0) *v = m_maxThreads; else *v = omp_get_max_threads(); #else *v = 1; #endif } else { eigen_internal_assert(false); } } } /** Must be call first when calling Eigen from multiple threads */ inline void initParallel() { int nbt; internal::manage_multi_threading(GetAction, &nbt); std::ptrdiff_t l1, l2, l3; internal::manage_caching_sizes(GetAction, &l1, &l2, &l3); } /** \returns the max number of threads reserved for Eigen * \sa setNbThreads */ inline int nbThreads() { int ret; internal::manage_multi_threading(GetAction, &ret); return ret; } /** Sets the max number of threads reserved for Eigen * \sa nbThreads */ inline void setNbThreads(int v) { internal::manage_multi_threading(SetAction, &v); } namespace internal { template<typename Index> struct GemmParallelInfo { GemmParallelInfo() : sync(-1), users(0), lhs_start(0), lhs_length(0) {} Index volatile sync; int volatile users; Index lhs_start; Index lhs_length; }; template<bool Condition, typename Functor, typename Index> void parallelize_gemm(const Functor& func, Index rows, Index cols, Index depth, bool transpose) { // TODO when EIGEN_USE_BLAS is defined, // we should still enable OMP for other scalar types #if !(defined (EIGEN_HAS_OPENMP)) || defined (EIGEN_USE_BLAS) // FIXME the transpose variable is only needed to properly split // the matrix product when multithreading is enabled. This is a temporary // fix to support row-major destination matrices. This whole // parallelizer mechanism has to be redesigned anyway. EIGEN_UNUSED_VARIABLE(depth); EIGEN_UNUSED_VARIABLE(transpose); func(0,rows, 0,cols); #else // Dynamically check whether we should enable or disable OpenMP. // The conditions are: // - the max number of threads we can create is greater than 1 // - we are not already in a parallel code // - the sizes are large enough // compute the maximal number of threads from the size of the product: // This first heuristic takes into account that the product kernel is fully optimized when working with nr columns at once. Index size = transpose ? rows : cols; Index pb_max_threads = std::max<Index>(1,size / Functor::Traits::nr); // compute the maximal number of threads from the total amount of work: double work = static_cast<double>(rows) * static_cast<double>(cols) * static_cast<double>(depth); double kMinTaskSize = 50000; // FIXME improve this heuristic. pb_max_threads = std::max<Index>(1, std::min<Index>(pb_max_threads, work / kMinTaskSize)); // compute the number of threads we are going to use Index threads = std::min<Index>(nbThreads(), pb_max_threads); // if multi-threading is explicitly disabled, not useful, or if we already are in a parallel session, // then abort multi-threading // FIXME omp_get_num_threads()>1 only works for openmp, what if the user does not use openmp? if((!Condition) || (threads==1) || (omp_get_num_threads()>1)) return func(0,rows, 0,cols); Eigen::initParallel(); func.initParallelSession(threads); if(transpose) std::swap(rows,cols); ei_declare_aligned_stack_constructed_variable(GemmParallelInfo<Index>,info,threads,0); #pragma omp parallel num_threads(threads) { Index i = omp_get_thread_num(); // Note that the actual number of threads might be lower than the number of request ones. Index actual_threads = omp_get_num_threads(); Index blockCols = (cols / actual_threads) & ~Index(0x3); Index blockRows = (rows / actual_threads); blockRows = (blockRows/Functor::Traits::mr)*Functor::Traits::mr; Index r0 = i*blockRows; Index actualBlockRows = (i+1==actual_threads) ? rows-r0 : blockRows; Index c0 = i*blockCols; Index actualBlockCols = (i+1==actual_threads) ? cols-c0 : blockCols; info[i].lhs_start = r0; info[i].lhs_length = actualBlockRows; if(transpose) func(c0, actualBlockCols, 0, rows, info); else func(0, rows, c0, actualBlockCols, info); } #endif } } // end namespace internal } // end namespace Eigen #endif // EIGEN_PARALLELIZER_H
syncbench.c
/*************************************************************************** * * * OpenMP MicroBenchmark Suite - Version 2.0 * * * * produced by * * * * Mark Bull and Fiona Reid * * * * at * * * * Edinburgh Parallel Computing Centre * * * * email: markb@epcc.ed.ac.uk or fiona@epcc.ed.ac.uk * * * * * * This version copyright (c) The University of Edinburgh, 2004. * * All rights reserved. * * * **************************************************************************/ #include <stdio.h> #include <math.h> #include <omp.h> #define OUTERREPS 20 #define CONF95 1.96 int nthreads, delaylength, innerreps; double times[OUTERREPS+1], reftime, refsd; void delay(int); void refer(void); void referatom(void); void referred(void); void testpr(void); void testfor(void); void testpfor(void); void testbar(void); void testsing(void); void testcrit(void); void testlock(void); void testorder(void); void testatom(void); void testred(void); void stats(double*, double*); int main (int argv, char **argc) { #pragma omp parallel { #pragma omp master { nthreads = omp_get_num_threads(); } } printf(" Running OpenMP benchmark on %d thread(s)\n", nthreads); delaylength = 500; innerreps = 10000; /* GENERATE REFERENCE TIME */ refer(); /* TEST PARALLEL REGION */ innerreps = 1000; testpr(); /* TEST FOR */ testfor(); /* TEST PARALLEL FOR */ testpfor(); /* TEST BARRIER */ testbar(); /* TEST SINGLE */ testsing(); /* TEST CRITICAL*/ innerreps = 100000; testcrit(); /* TEST LOCK/UNLOCK */ testlock(); /* TEST ORDERED SECTION */ innerreps = 1000; testorder(); /* GENERATE NEW REFERENCE TIME */ innerreps = 100000; referatom(); /* TEST ATOMIC */ testatom(); /* GENERATE NEW REFERENCE TIME */ innerreps = 10000; referred(); /* TEST REDUCTION (1 var) */ innerreps = 1000; testred(); } void refer() { int j,k; double start; double meantime, sd; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing reference time 1\n"); for (k=0; k<=OUTERREPS; k++){ start = getclock(); for (j=0; j<innerreps; j++){ delay(delaylength); } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime, &sd); printf("Reference_time_1 = %f microseconds +/- %f\n", meantime, CONF95*sd); reftime = meantime; refsd = sd; } void referatom() { int j,k; double start; double meantime, sd; float aaaa; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing reference time 2\n"); for (k=0; k<=OUTERREPS; k++){ aaaa=0; start = getclock(); for (j=0; j<innerreps; j++){ aaaa += 1; } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; if (aaaa < 0) printf("%f\n",aaaa); } stats (&meantime, &sd); printf("Reference_time_2 = %f microseconds +/- %f\n", meantime, CONF95*sd); reftime = meantime; refsd = sd; } void referred() { int j,k; double start; double meantime, sd; int aaaa; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing reference time 3\n"); for (k=0; k<=OUTERREPS; k++){ aaaa=0; start = getclock(); for (j=0; j<innerreps; j++){ delay(delaylength); aaaa += 1; } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; if (aaaa < 0) printf("%d\n",aaaa); } stats (&meantime, &sd); printf("Reference_time_3 = %f microseconds +/- %f\n", meantime, CONF95*sd); reftime = meantime; refsd = sd; } void testpr() { int j,k; double start; double meantime, sd; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing PARALLEL time\n"); for (k=0; k<=OUTERREPS; k++){ start = getclock(); for (j=0; j<innerreps; j++){ #pragma omp parallel { delay(delaylength); } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime, &sd); printf("PARALLEL time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("PARALLEL overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void testfor() { int i,j,k; double start; double meantime, sd; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing FOR time\n"); for (k=0; k<=OUTERREPS; k++){ start = getclock(); #pragma omp parallel private(j) { for (j=0; j<innerreps; j++){ #pragma omp for for (i=0; i<nthreads; i++){ delay(delaylength); } } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime, &sd); printf("FOR time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("FOR overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void testpfor() { int i,j,k; double start; double meantime, sd; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing PARALLEL FOR time\n"); for (k=0; k<=OUTERREPS; k++){ start = getclock(); for (j=0; j<innerreps; j++){ #pragma omp parallel for for (i=0; i<nthreads; i++){ delay(delaylength); } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime, &sd); printf("PARALLEL FOR time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("PARALLEL FOR overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void testbar() { int j,k; double start; double meantime, sd; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing BARRIER time\n"); for (k=0; k<=OUTERREPS; k++){ start = getclock(); #pragma omp parallel private(j) { for (j=0; j<innerreps; j++){ delay(delaylength); #pragma omp barrier } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime, &sd); printf("BARRIER time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("BARRIER overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void testsing() { int j,k; double start; double meantime, sd; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing SINGLE time\n"); for (k=0; k<=OUTERREPS; k++){ start = getclock(); #pragma omp parallel private(j) { for (j=0; j<innerreps; j++){ #pragma omp single delay(delaylength); } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime, &sd); printf("SINGLE time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("SINGLE overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void testcrit() { int j,k; double start; double meantime, sd; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing CRITICAL time\n"); for (k=0; k<=OUTERREPS; k++){ start = getclock(); #pragma omp parallel private(j) { for (j=0; j<innerreps/nthreads; j++){ #pragma omp critical { delay(delaylength); } } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime, &sd); printf("CRITICAL time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("CRITICAL overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void testlock() { int j,k; double start; double meantime, sd; omp_lock_t lock; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing LOCK/UNLOCK time\n"); omp_init_lock(&lock); for (k=0; k<=OUTERREPS; k++){ start = getclock(); #pragma omp parallel private(j) { for (j=0; j<innerreps/nthreads; j++){ omp_set_lock(&lock); delay(delaylength); omp_unset_lock(&lock); } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime, &sd); printf("LOCK/UNLOCK time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("LOCK/UNLOCK overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void testorder() { int j,k; double start; double meantime, sd; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing ORDERED time\n"); for (k=0; k<=OUTERREPS; k++){ start = getclock(); #pragma omp parallel for ordered schedule (static,1) for (j=0; j<innerreps; j++){ #pragma omp ordered delay(delaylength); } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime, &sd); printf("ORDERED time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("ORDERED overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void testatom() { int j,k; double start; double meantime, sd; float aaaa; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing ATOMIC time\n"); for (k=0; k<=OUTERREPS; k++){ aaaa = 0; start = getclock(); #pragma omp parallel private(j) { for (j=0; j<innerreps/nthreads; j++){ #pragma omp atomic aaaa += 1; } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; if (aaaa < 0.0) printf("%f\n",aaaa); } stats (&meantime, &sd); printf("ATOMIC time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("ATOMIC overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void testred() { int j,k; double start; double meantime, sd; int aaaa; double getclock(void); printf("\n"); printf("--------------------------------------------------------\n"); printf("Computing REDUCTION time\n"); for (k=0; k<=OUTERREPS; k++){ aaaa = 0; start = getclock(); for (j=0; j<innerreps; j++){ #pragma omp parallel reduction(+:aaaa) { delay(delaylength); aaaa += 1; } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; if (aaaa < 0) printf("%d\n",aaaa); } stats (&meantime, &sd); printf("REDUCTION time = %f microseconds +/- %f\n", meantime, CONF95*sd); printf("REDUCTION overhead = %f microseconds +/- %f\n", meantime-reftime, CONF95*(sd+refsd)); } void stats (double *mtp, double *sdp) { double meantime, totaltime, sumsq, mintime, maxtime, sd, cutoff; int i, nr; mintime = 1.0e10; maxtime = 0.; totaltime = 0.; for (i=1; i<=OUTERREPS; i++){ mintime = (mintime < times[i]) ? mintime : times[i]; maxtime = (maxtime > times[i]) ? maxtime : times[i]; totaltime +=times[i]; } meantime = totaltime / OUTERREPS; sumsq = 0; for (i=1; i<=OUTERREPS; i++){ sumsq += (times[i]-meantime)* (times[i]-meantime); } sd = sqrt(sumsq/(OUTERREPS-1)); cutoff = 3.0 * sd; nr = 0; for (i=1; i<=OUTERREPS; i++){ if ( fabs(times[i]-meantime) > cutoff ) nr ++; } printf("\n"); printf("Sample_size Average Min Max S.D. Outliers\n"); printf(" %d %f %f %f %f %d\n",OUTERREPS, meantime, mintime, maxtime, sd, nr); printf("\n"); *mtp = meantime; *sdp = sd; }
DRB029-truedep1-orig-yes.c
/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it andor modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http:www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses Unicode 10.0.0. Version 10.0 of the Unicode Standard is synchronized with ISOIEC 10646:2017, fifth edition, plus the following additions from Amendment 1 to the fifth edition: - 56 emoji characters - 285 hentaigana - 3 additional Zanabazar Square characters */ /* 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.comLLNL/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 program has data races due to true dependence within the loop at 63. Data race pair: a[i+1]@64:5 vs. a[i]@64:12 */ #include <stdlib.h> #include <stdio.h> int main(int argc, char * argv[]) { int i; int len = 100; int a[100]; int _ret_val_0; #pragma cetus private(i) #pragma loop name main#0 #pragma cetus parallel #pragma omp parallel for private(i) for (i=0; i<len; i ++ ) { a[i]=i; } #pragma cetus private(i) #pragma loop name main#1 for (i=0; i<(len-1); i ++ ) { a[i+1]=(a[i]+1); } printf("a[50]=%d\n", a[50]); _ret_val_0=0; return _ret_val_0; }
tensor_transpose.h
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // 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. #ifndef _H_TENSOR_TRANSPOSE #define _H_TENSOR_TRANSPOSE #include "tensor_desc.h" #include "uni.h" #include "affinity_policy.h" template <typename T> inline static EE transformToNCHWKernel( TensorDesc inputDesc, const T *input, TensorDesc outputDesc, T *output) { DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; if (tensorIs2d(inputDesc)) { CHECK_STATUS(tensor2dGet(inputDesc, &idt, &idf, &in, &iw)); ic = 1; ih = 1; } else if (tensorIs3d(inputDesc)) { if (inputDesc.df == DF_NHWC) { CHECK_STATUS(tensor3dGet(inputDesc, &idt, &idf, &in, &ih, &iw)); ic = 1; } else { CHECK_STATUS(tensor3dGet(inputDesc, &idt, &idf, &in, &ic, &ih)); iw = 1; } } else if (tensorIs4d(inputDesc)) { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); } else { UNI_ERROR_LOG("not support transform %d-dim tensor to NCHW format.\n", (int)inputDesc.nDims); return NOT_SUPPORTED; } if (tensorIs2d(outputDesc)) { CHECK_STATUS(tensor2dGet(outputDesc, &odt, &odf, &on, &oc)); oh = ow = 1; } else if (tensorIs3d(outputDesc)) { CHECK_STATUS(tensor3dGet(outputDesc, &odt, &odf, &on, &oc, &oh)); ow = 1; } else if (tensorIs4d(outputDesc)) { CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); } else { UNI_ERROR_LOG("not support transform to %d-dim NCHW tensor.\n", (int)outputDesc.nDims); return NOT_SUPPORTED; } CHECK_REQUIREMENT(idt == odt); EE ret = SUCCESS; switch (idf) { case DF_NORMAL: case DF_MTK: case DF_NCHW: { if (in == on && ic == oc && ih == oh && iw == ow) { if (output != input) { UNI_MEMCPY(output, input, tensorNumBytes(outputDesc)); } } else { U32 tileSize = UNI_MIN(iw, ow) * bytesOf(idt); for (U32 n = 0; n < on && n < in; n++) { for (U32 c = 0; c < oc && c < ic; c++) { for (U32 h = 0; h < oh && h < ih; h++) { U32 srcIndex = ((n * ic + c) * ih + h) * iw; U32 dstIndex = ((n * oc + c) * oh + h) * ow; UNI_MEMCPY(output + dstIndex, input + srcIndex, tileSize); } } } } break; } case DF_NCHWC8: { U32 cx = 8; U32 ic_a = ic / cx; U32 minH = UNI_MIN(oh, ih); U32 minC = UNI_MIN(oc, ic); for (U32 n = 0; n < on && n < in; n++) { #ifdef _USE_OPENMP #pragma omp parallel for num_threads(OMP_NUM_THREADS) #endif for (U32 c = 0; c < minC; c++) { for (U32 h = 0; h < minH; h++) { for (U32 w = 0; w < ow && w < iw; w++) { U32 c_a = c / cx; U32 c_b = c % cx; U32 srcIndex = (((n * ic_a + c_a) * ih + h) * iw + w) * cx + c_b; U32 dstIndex = ((n * oc + c) * oh + h) * ow + w; // support channel cut output[dstIndex] = input[srcIndex]; } } } } break; } case DF_NCHWC16: { U32 ic16 = ic / 16; for (U32 n = 0; n < in; ++n) { U32 c = 0; for (; c < ic16; ++c) { for (U32 h = 0; h < ih; ++h) { for (U32 w = 0; w < iw; ++w) { for (U32 cc = 0; cc < 16; ++cc) { output[n * ic * ih * iw + (c * 16 + cc) * ih * iw + h * iw + w] = input[n * ic * ih * iw + c * 16 * ih * iw + (h * iw + w) * 16 + cc]; } } } } c *= 16; while (c < ic) { U32 cx = ic - c; cx = (cx == 12) ? 8 : cx; for (U32 h = 0; h < ih; ++h) { for (U32 w = 0; w < iw; ++w) { for (U32 cc = 0; cc < cx; ++cc) { output[n * ic * ih * iw + (c + cc) * ih * iw + h * iw + w] = input[n * ic * ih * iw + c * ih * iw + (h * iw + w) * cx + cc]; } } } c += cx; } } break; } case DF_NHWCN8: { in /= 8; for (U32 n = 0; n < in; n++) { for (U32 h = 0; h < oh && h < ih; h++) { for (U32 w = 0; w < ow && w < iw; w++) { for (U32 c = 0; c < oc && c < ic; c++) { for (U32 n8 = 0; n8 < 8; n8++) { U32 srcIndex = (((n * ih + h) * iw + w) * ic + c) * 8 + n8; U32 dstIndex = (((n * 8 + n8) * oc + c) * oh + h) * ow + w; output[dstIndex] = input[srcIndex]; } } } } } break; } case DF_NHWC: { for (U32 n = 0; n < on && n < in; n++) { for (U32 c = 0; c < oc && c < ic; c++) { for (U32 h = 0; h < oh && h < ih; h++) { for (U32 w = 0; w < ow && w < iw; w++) { U32 srcIndex = ((n * ih + h) * iw + w) * ic + c; U32 dstIndex = ((n * oc + c) * oh + h) * ow + w; output[dstIndex] = input[srcIndex]; } } } } break; } default: { UNI_ERROR_LOG( "not support transform %s format to NCHW format.\n", DataFormatName()[idf]); ret = NOT_SUPPORTED; break; } } return ret; } inline EE transformToNCHW( TensorDesc inputDesc, const void *input, TensorDesc outputDesc, void *output) { if (nullptr == input || nullptr == output) { CHECK_STATUS(NULL_POINTER); } EE ret = NOT_SUPPORTED; switch (inputDesc.dt) { #ifdef _USE_FP32 case DT_F32: { ret = transformToNCHWKernel<F32>(inputDesc, (F32 *)input, outputDesc, (F32 *)output); break; } #endif #ifdef _USE_FP16 case DT_F16: { ret = transformToNCHWKernel<F16>(inputDesc, (F16 *)input, outputDesc, (F16 *)output); break; } #endif #ifdef _USE_INT8 case DT_I8: { ret = transformToNCHWKernel<INT8>(inputDesc, (INT8 *)input, outputDesc, (INT8 *)output); break; } case DT_U8_Q: { ret = transformToNCHWKernel<UINT8>( inputDesc, (UINT8 *)input, outputDesc, (UINT8 *)output); break; } #endif default: { UNI_ERROR_LOG("not support transform %s type tensor.\n", DataTypeName()[inputDesc.dt]); break; } } return ret; } template <typename T> inline static EE transformToNHWCKernel( TensorDesc inputDesc, const T *input, TensorDesc outputDesc, T *output) { DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; if (tensorIs2d(inputDesc)) { CHECK_STATUS(tensor2dGet(inputDesc, &idt, &idf, &in, &iw)); ic = 1; ih = 1; } else if (tensorIs3d(inputDesc)) { CHECK_STATUS(tensor3dGet(inputDesc, &idt, &idf, &in, &ih, &iw)); ic = 1; } else if (tensorIs4d(inputDesc)) { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); } else { UNI_ERROR_LOG("not support transform %d-dim tensor to NHWC format\n", (int)inputDesc.nDims); return NOT_SUPPORTED; } if (tensorIs4d(outputDesc)) { CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); } else { UNI_ERROR_LOG("not support transform to %d-dim NHWC tensor.\n", (int)outputDesc.nDims); return NOT_SUPPORTED; } U32 size = tensorNumElements(outputDesc); U32 ihiw = ih * iw; EE ret = SUCCESS; switch (idf) { case DF_NHWC: { CHECK_REQUIREMENT(tensorNumElements(inputDesc) == size); if (input != output) { UNI_MEMCPY(output, input, tensorNumBytes(inputDesc)); } break; } case DF_NORMAL: case DF_MTK: case DF_NCHW: { CHECK_REQUIREMENT(tensorNumElements(inputDesc) == size); for (U32 o = 0, srcIndex = 0; o < in; o++) { for (U32 cc = 0; cc < ic; cc++) { for (U32 hw = 0; hw < ihiw; hw++, srcIndex++) { U32 dstIndex = (o * ihiw + hw) * ic + cc; output[dstIndex] = input[srcIndex]; } } } break; } case DF_NCHWC8: case DF_NCHWC16: { U32 align = (idf == DF_NCHWC16) ? 16 : 8; CHECK_REQUIREMENT(ic % align == 0); ic /= align; for (U32 n = 0, srcIndex = 0; n < in; n++) { for (U32 c = 0; c < ic; c++) { for (U32 hw = 0; hw < ihiw; hw++) { for (U32 cx = 0; cx < align; cx++, srcIndex++) { U32 dstIndex = ((n * ihiw + hw) * ic + c) * align + cx; output[dstIndex] = input[srcIndex]; } } } } break; } default: { UNI_ERROR_LOG( "not support transform %s format tensor to NHWC format\n", DataFormatName()[idf]); ret = NOT_SUPPORTED; break; } } return ret; } inline EE transformToNHWC( TensorDesc inputDesc, const void *input, TensorDesc outputDesc, void *output) { if (nullptr == input || nullptr == output) { return NULL_POINTER; } EE ret = NOT_SUPPORTED; switch (inputDesc.dt) { #ifdef _USE_FP32 case DT_F32: { ret = transformToNHWCKernel<F32>(inputDesc, (F32 *)input, outputDesc, (F32 *)output); break; } #endif #ifdef _USE_FP16 case DT_F16: { ret = transformToNHWCKernel<F16>(inputDesc, (F16 *)input, outputDesc, (F16 *)output); break; } #endif #ifdef _USE_INT8 case DT_I8: { ret = transformToNHWCKernel<INT8>(inputDesc, (INT8 *)input, outputDesc, (INT8 *)output); break; } #endif default: { UNI_ERROR_LOG("not support transform %s type tensor.\n", DataTypeName()[inputDesc.dt]); break; } } return ret; } inline EE transformNCHWC16ToNCHWC8( TensorDesc inputDesc, const void *input, TensorDesc outputDesc, void *output) { if (input == NULL || output == NULL) { CHECK_STATUS(NULL_POINTER); } DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; if (tensorIs2d(inputDesc)) { if (input != output) { UNI_MEMCPY(output, input, tensorNumBytes(inputDesc)); } return SUCCESS; } else if (tensorIs3d(inputDesc)) { CHECK_STATUS(tensor3dGet(inputDesc, &idt, &idf, &in, &ic, &ih)); CHECK_STATUS(tensor3dGet(outputDesc, &odt, &odf, &on, &oc, &oh)); iw = ow = 1; } else { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); } CHECK_REQUIREMENT(in == on && idf == DF_NCHWC16 && odf == DF_NCHWC8 && idt == odt); int elementSize = bytesOf(idt); const U8 *inputPtr = (const U8 *)input; U8 *outputPtr = (U8 *)output; oc /= 8; for (U32 n = 0; n < on && n < in; n++) { for (U32 c = 0; c < oc; c += 2) { for (U32 h = 0; h < oh && h < ih; h++) { for (U32 w = 0; w < ow && w < iw; w++) { for (U32 c8 = 0; c8 < 2 && c8 + c < oc; ++c8) { U32 srcIndex = n * ic * ih * iw + c * ih * iw * 8 + (h * iw + w) * 16 + c8 * 8; U32 dstIndex = n * ic * ih * iw + (c + c8) * ih * iw * 8 + (h * iw + w) * 8; UNI_MEMCPY(outputPtr + dstIndex * elementSize, inputPtr + srcIndex * elementSize, elementSize * 8); } } } } } return SUCCESS; } inline EE transformNCHWToNCHWC8( TensorDesc inputDesc, const void *input, TensorDesc outputDesc, void *output) { if (input == NULL || output == NULL) { CHECK_STATUS(NULL_POINTER); } DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; if (tensorIs2d(inputDesc)) { if (input != output) { UNI_MEMCPY(output, input, tensorNumBytes(inputDesc)); } return SUCCESS; } else if (tensorIs3d(inputDesc)) { CHECK_STATUS(tensor3dGet(inputDesc, &idt, &idf, &in, &ic, &ih)); CHECK_STATUS(tensor3dGet(outputDesc, &odt, &odf, &on, &oc, &oh)); iw = ow = 1; } else { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); } CHECK_REQUIREMENT(in == on && idf != DF_NCHWC8 && odf == DF_NCHWC8 && idt == odt); int elementSize = bytesOf(idt); const U8 *inputPtr = (const U8 *)input; U8 *outputPtr = (U8 *)output; oc /= 8; for (U32 n = 0; n < on && n < in; n++) { for (U32 c = 0; c < oc; c++) { for (U32 h = 0; h < oh && h < ih; h++) { for (U32 w = 0; w < ow && w < iw; w++) { for (U32 c8 = 0, c_i = c * 8; c8 < 8; c8++, c_i++) { U32 dstIndex = ((((n * oc + c) * oh + h) * ow + w) * 8 + c8) * elementSize; // support channel padding if (c_i < ic) { U32 srcIndex = (((n * ic + c_i) * ih + h) * iw + w) * elementSize; UNI_MEMCPY(outputPtr + dstIndex, inputPtr + srcIndex, elementSize); } else { UNI_MEMSET(outputPtr + dstIndex, 0, elementSize); } } } } } } return SUCCESS; } inline EE transformNHWCToNCHWC8( TensorDesc inputDesc, const void *input, TensorDesc outputDesc, void *output) { if (input == NULL || output == NULL) { CHECK_STATUS(NULL_POINTER); } DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); CHECK_REQUIREMENT(in == on && idf == DF_NHWC && odf == DF_NCHWC8 && idt == odt); int elementSize = bytesOf(idt); const U8 *inputPtr = (const U8 *)input; U8 *outputPtr = (U8 *)output; oc /= 8; for (U32 n = 0; n < on && n < in; n++) { for (U32 c = 0; c < oc; c++) { for (U32 h = 0; h < oh && h < ih; h++) { for (U32 w = 0; w < ow && w < iw; w++) { for (U32 c8 = 0, c_i = c * 8; c8 < 8; c8++, c_i++) { U32 dstIndex = ((((n * oc + c) * oh + h) * ow + w) * 8 + c8) * elementSize; // support channel padding if (c_i < ic) { U32 srcIndex = (((n * ih + h) * iw + w) * ic + c_i) * elementSize; UNI_MEMCPY(outputPtr + dstIndex, inputPtr + srcIndex, elementSize); } else { UNI_MEMSET(outputPtr + dstIndex, 0, elementSize); } } } } } } return SUCCESS; } inline EE transformNCHWC8ToNCHWC8ByGroup( TensorDesc inputDesc, const void *input, int group, TensorDesc outputDesc, void *output) { U32 inputSize = tensorNumElements(inputDesc); U32 outputSize = tensorNumElements(outputDesc); if (group <= 1 || inputSize == outputSize) { if (input != output) { UNI_MEMCPY(output, input, outputSize); } return SUCCESS; } U32 channelAlignSize = 8; DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw; U32 on, oc, oh, ow; CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); CHECK_REQUIREMENT(idt == odt); CHECK_REQUIREMENT(idf == DF_NCHWC8 && odf == DF_NCHWC8); U32 icg = ic / group; U32 ocg = oc / group; U32 ict = ic / channelAlignSize; U32 oct = oc / channelAlignSize; U32 elementSize = bytesOf(idt); for (U32 n = 0; n < in; n++) { for (I32 g = 0, od = 0; g < group; g++) { for (U32 c = 0; c < ocg; c++, od++) { U32 id = g * icg + c; U32 id_a = id / channelAlignSize; U32 od_a = od / channelAlignSize; U32 id_b = id % channelAlignSize; U32 od_b = od % channelAlignSize; for (U32 h = 0; h < oh; h++) { for (U32 w = 0; w < ow; w++) { U32 dstIndex = ((((n * oct + od_a) * oh + h) * ow + w) * channelAlignSize + od_b) * elementSize; if (h < ih && w < iw) { U32 srcIndex = ((((n * ict + id_a) * ih + h) * iw + w) * channelAlignSize + id_b) * elementSize; UNI_MEMCPY( (U8 *)output + dstIndex, (const U8 *)input + srcIndex, elementSize); } else { UNI_MEMSET((U8 *)output + dstIndex, 0, elementSize); } } } } } } return SUCCESS; } template <typename T> inline static EE transformToNCHWC16Kernel( TensorDesc inputDesc, const T *input, TensorDesc outputDesc, T *output) { DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; if (tensorIs2d(inputDesc)) { CHECK_STATUS(tensor2dGet(inputDesc, &idt, &idf, &in, &iw)); ic = 1; ih = 1; } else if (tensorIs3d(inputDesc)) { if (inputDesc.df == DF_NHWC) { CHECK_STATUS(tensor3dGet(inputDesc, &idt, &idf, &in, &ih, &iw)); ic = 1; } else { CHECK_STATUS(tensor3dGet(inputDesc, &idt, &idf, &in, &ic, &ih)); iw = 1; } } else if (tensorIs4d(inputDesc)) { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); } else { UNI_ERROR_LOG( "not support transform %d-dim tensor to NCHWC16 format\n", (int)inputDesc.nDims); return NOT_SUPPORTED; } if (tensorIs3d(outputDesc)) { CHECK_STATUS(tensor3dGet(outputDesc, &odt, &odf, &on, &oc, &oh)); ow = 1; } else if (tensorIs4d(outputDesc)) { CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); } else { UNI_ERROR_LOG("not support transform to %d-dim NCHWC16 tensor\n", (int)outputDesc.nDims); return NOT_SUPPORTED; } CHECK_REQUIREMENT(idt == odt); EE ret = SUCCESS; switch (idf) { case DF_NORMAL: case DF_MTK: case DF_NCHW: { U32 ic16 = ic / 16; for (U32 n = 0; n < in; ++n) { U32 c = 0; for (; c < ic16; ++c) { for (U32 h = 0; h < ih; ++h) { for (U32 w = 0; w < iw; ++w) { for (U32 cc = 0; cc < 16; ++cc) { output[n * ic * ih * iw + c * 16 * ih * iw + (h * iw + w) * 16 + cc] = input[n * ic * ih * iw + (c * 16 + cc) * ih * iw + h * iw + w]; } } } } c *= 16; while (c < ic) { U32 cx = ic - c; cx = (cx == 12) ? 8 : cx; for (U32 h = 0; h < ih; ++h) { for (U32 w = 0; w < iw; ++w) { for (U32 cc = 0; cc < cx; ++cc) { output[n * ic * ih * iw + c * ih * iw + (h * iw + w) * cx + cc] = input[n * ic * ih * iw + (c + cc) * ih * iw + h * iw + w]; } } } c += cx; } } break; } case DF_NCHWC8: { U32 ic16 = ic / 16; for (U32 n = 0; n < in; ++n) { U32 c = 0; for (; c < ic16; ++c) { for (U32 h = 0; h < ih; ++h) { for (U32 w = 0; w < iw; ++w) { for (U32 cc = 0; cc < 16; cc += 8) { for (U32 c8 = 0; c8 < 8; ++c8) { output[n * ic * ih * iw + c * 16 * ih * iw + (h * iw + w) * 16 + cc + c8] = input[n * ic * ih * iw + (c * 16 + cc) * ih * iw + (h * iw + w) * 8 + c8]; } } } } } c *= 16; while (c < ic) { U32 cx = ic - c; cx = (cx == 12) ? 8 : cx; for (U32 h = 0; h < ih; ++h) { for (U32 w = 0; w < iw; ++w) { for (U32 cc = 0; cc < cx; cc += 8) { for (U32 c8 = 0; c8 < 8; ++c8) { output[n * ic * ih * iw + c * ih * iw + (h * iw + w) * 8 + cc + c8] = input[n * ic * ih * iw + (c + cc) * ih * iw + (h * iw + w) * 8 + c8]; } } } } c += cx; } } break; } default: { UNI_ERROR_LOG( "not support transform %s format to NCHWC16 format\n", DataFormatName()[idf]); ret = NOT_SUPPORTED; break; } } return ret; } inline EE transformToNCHWC16( TensorDesc inputDesc, const void *input, TensorDesc outputDesc, void *output) { if (nullptr == input || nullptr == output) { return NULL_POINTER; } EE ret = NOT_SUPPORTED; switch (inputDesc.dt) { #ifdef _USE_FP32 case DT_F32: { ret = transformToNCHWC16Kernel<F32>(inputDesc, (F32 *)input, outputDesc, (F32 *)output); break; } #endif #ifdef _USE_INT8 case DT_U8_Q: { ret = transformToNCHWC16Kernel<UINT8>( inputDesc, (UINT8 *)input, outputDesc, (UINT8 *)output); break; } #endif default: { UNI_ERROR_LOG("not support transform %s type tensor.\n", DataTypeName()[inputDesc.dt]); break; } } return ret; } inline EE transformFormat( TensorDesc inputDesc, const void *input, TensorDesc outputDesc, void *output) { EE ret = NOT_SUPPORTED; if (outputDesc.df == DF_NCHW || outputDesc.df == DF_MTK || outputDesc.df == DF_NORMAL) { ret = transformToNCHW(inputDesc, input, outputDesc, output); } else if (outputDesc.df == DF_NCHWC8) { if (inputDesc.df == DF_NORMAL) { UNI_MEMCPY(output, input, tensorNumBytes(inputDesc)); ret = SUCCESS; } else if (inputDesc.df == DF_NCHW || inputDesc.df == DF_MTK || inputDesc.df == DF_NORMAL) { ret = transformNCHWToNCHWC8(inputDesc, input, outputDesc, output); } else if (inputDesc.df == DF_NHWC) { ret = transformNHWCToNCHWC8(inputDesc, input, outputDesc, output); } else if (inputDesc.df == DF_NCHWC8) { ret = transformNCHWC8ToNCHWC8ByGroup(inputDesc, input, 1, outputDesc, output); } else if (inputDesc.df == DF_NCHWC16) { ret = transformNCHWC16ToNCHWC8(inputDesc, input, outputDesc, output); } else { UNI_ERROR_LOG("layout transpose can not support transform from %s format " "to NCHWC8 format.\n", DataFormatName()[inputDesc.df]); } } else if (outputDesc.df == DF_NCHWC16) { ret = transformToNCHWC16(inputDesc, input, outputDesc, output); } else if (outputDesc.df == DF_NHWC) { ret = transformToNHWC(inputDesc, input, outputDesc, output); } else { UNI_ERROR_LOG("layout transpose can not support transform to %s format.\n", DataFormatName()[outputDesc.df]); } return ret; } inline EE transposeFilter( TensorDesc inputDesc, const void *input, TensorDesc outputDesc, void *output) { if (input == NULL || output == NULL) { CHECK_STATUS(NULL_POINTER); } DataType idt, odt; DataFormat idf, odf; U32 in, ic, ih, iw, on, oc, oh, ow; if (tensorIs4d(inputDesc) && tensorIs4d(outputDesc)) { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); CHECK_STATUS(tensor4dGet(outputDesc, &odt, &odf, &on, &oc, &oh, &ow)); } else { UNI_ERROR_LOG("currently only support to transpose 4-dim filter.\n"); return NOT_SUPPORTED; } CHECK_REQUIREMENT(idf == odf); const U8 *src = (const U8 *)input; U8 *dst = (U8 *)output; EE ret = SUCCESS; switch (idf) { case DF_NHWCN8: { CHECK_REQUIREMENT(in % 8 == 0); in /= 8; U32 hwMax = ih * iw - 1; U32 innerSize = bytesOf(idt) * ic * 8; for (U32 o = 0; o < in; o++) { for (U32 hw = 0; hw < ih * iw; hw++) { U32 srcIndex = o * ih * iw * innerSize + hw * innerSize; U32 dstIndex = o * ih * iw * innerSize + (hwMax - hw) * innerSize; UNI_MEMCPY(dst + dstIndex, src + srcIndex, innerSize); } } break; } default: { UNI_ERROR_LOG( "currently not support to transpose %s format filter.\n", DataFormatName()[idf]); ret = NOT_SUPPORTED; break; } } return ret; } #endif
omp_pragma_example2.c
#if 0 //inputBug342-3.c // -rose:C // roseomp: main.C:3114: static int // OmpMidend::transOmpFor(SgPragmaDeclaration*): Assertion isSgForStatement(forstmt) != __null failed. int i; int m; void foo() { // Extra block inserted around subcollection of statements in original block! { //#pragma omp for for (i = 0; i < 10; i++) { m++; } // If we uncomment this statement then we get proper blocking // m++; #pragma omp for } for (i = 1; i < 10; i++) { m++; } } #endif int i,m; void foo () { //#pragma omp for for (i = 0; i < 10; i++) m++; // If we uncomment this statement then we get proper blocking // m++; #pragma omp for for (i = 1; i < 10; i++) m++; }
threadpool.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <string> #include <vector> #include <functional> #include <memory> #if defined(__GNUC__) #pragma GCC diagnostic push #if __GNUC__ >= 6 #pragma GCC diagnostic ignored "-Wignored-attributes" #endif #pragma GCC diagnostic ignored "-Wunused-parameter" #elif defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4267) #pragma warning(disable : 4127) #endif #include <unsupported/Eigen/CXX11/ThreadPool> #if defined(__GNUC__) #pragma GCC diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif namespace onnxruntime { namespace concurrency { /** * Generic class for instantiating thread pools. * Don't put any object of this type into a global variable in a Win32 DLL. */ class ThreadPool { public: /* Initializes a thread pool given the current environment. */ ThreadPool(const std::string& name, int num_threads); /* Enqueue a unit of work. */ void Schedule(std::function<void()> fn); /* Schedule work in the interval [0, total). */ void ParallelFor(int32_t total, std::function<void(int32_t)> fn); /* Schedule work in the interval [0, total), with calls split into (num_batches) batches. */ void BatchParallelFor(int32_t total, std::function<void(int32_t)> fn, int32_t num_batches = 0); /* Schedule work in the interval [first, last]. */ void ParallelForRange(int64_t first, int64_t last, std::function<void(int64_t, int64_t)> fn); // This is not supported until the latest Eigen // void SetStealPartitions(const std::vector<std::pair<unsigned, unsigned>>& partitions); /** * Tries to call the given function in parallel, with calls split into (num_batches) batches. * If tp is NULL and OpenMP is enabled, no grouping */ template <typename F> inline static void TryBatchParallelFor(concurrency::ThreadPool* tp, int32_t total, F&& fn, int32_t num_batches = 0) { if (tp != nullptr) { if (num_batches <= 0) { num_batches = std::min(total, tp->NumThreads()); } tp->BatchParallelFor(total, std::forward<F>(fn), num_batches); } else { #ifdef USE_OPENMP #pragma omp parallel for #endif for (int32_t i = 0; i < total; ++i) { fn(i); } } } /** Tries to call the given function in parallel. **/ template <typename F> inline static void TryParallelFor(concurrency::ThreadPool* tp, int32_t total, F&& fn) { if (tp != nullptr) { tp->ParallelFor(total, std::forward<F>(fn)); } else { #ifdef USE_OPENMP #pragma omp parallel for #endif for (int32_t i = 0; i < total; ++i) { fn(i); } } } int NumThreads() const; int CurrentThreadId() const; Eigen::ThreadPool& GetHandler() { return impl_; } private: Eigen::ThreadPool impl_; }; } // namespace concurrency } // namespace onnxruntime
path.c
#include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <omp.h> #include "mt19937p.h" //ldoc on /** * # The basic recurrence * * At the heart of the method is the following basic recurrence. * If $l_{ij}^s$ represents the length of the shortest path from * $i$ to $j$ that can be attained in at most $2^s$ steps, then * $$ * l_{ij}^{s+1} = \min_k \{ l_{ik}^s + l_{kj}^s \}. * $$ * That is, the shortest path of at most $2^{s+1}$ hops that connects * $i$ to $j$ consists of two segments of length at most $2^s$, one * from $i$ to $k$ and one from $k$ to $j$. Compare this with the * following formula to compute the entries of the square of a * matrix $A$: * $$ * a_{ij}^2 = \sum_k a_{ik} a_{kj}. * $$ * These two formulas are identical, save for the niggling detail that * the latter has addition and multiplication where the former has min * and addition. But the basic pattern is the same, and all the * tricks we learned when discussing matrix multiplication apply -- or * at least, they apply in principle. I'm actually going to be lazy * in the implementation of `square`, which computes one step of * this basic recurrence. I'm not trying to do any clever blocking. * You may choose to be more clever in your assignment, but it is not * required. * * The return value for `square` is true if `l` and `lnew` are * identical, and false otherwise. */ int square(int n, // Number of nodes int* restrict l, // Partial distance at step s int* restrict lnew) // Partial distance at step s+1 { int done = 1; #pragma omp parallel for shared(l, lnew) reduction(&& : done) for (int j = 0; j < n; ++j) { for (int i = 0; i < n; ++i) { int lij = lnew[j*n+i]; for (int k = 0; k < n; ++k) { int lik = l[k*n+i]; int lkj = l[j*n+k]; if (lik + lkj < lij) { lij = lik+lkj; done = 0; } } lnew[j*n+i] = lij; } } return done; } /** * * The value $l_{ij}^0$ is almost the same as the $(i,j)$ entry of * the adjacency matrix, except for one thing: by convention, the * $(i,j)$ entry of the adjacency matrix is zero when there is no * edge between $i$ and $j$; but in this case, we want $l_{ij}^0$ * to be "infinite". It turns out that it is adequate to make * $l_{ij}^0$ longer than the longest possible shortest path; if * edges are unweighted, $n+1$ is a fine proxy for "infinite." * The functions `infinitize` and `deinfinitize` convert back * and forth between the zero-for-no-edge and $n+1$-for-no-edge * conventions. */ static inline void infinitize(int n, int* l) { for (int i = 0; i < n*n; ++i) if (l[i] == 0) l[i] = n+1; } static inline void deinfinitize(int n, int* l) { for (int i = 0; i < n*n; ++i) if (l[i] == n+1) l[i] = 0; } /** * * Of course, any loop-free path in a graph with $n$ nodes can * at most pass through every node in the graph. Therefore, * once $2^s \geq n$, the quantity $l_{ij}^s$ is actually * the length of the shortest path of any number of hops. This means * we can compute the shortest path lengths for all pairs of nodes * in the graph by $\lceil \lg n \rceil$ repeated squaring operations. * * The `shortest_path` routine attempts to save a little bit of work * by only repeatedly squaring until two successive matrices are the * same (as indicated by the return value of the `square` routine). */ void shortest_paths(int n, int* restrict l) { // Generate l_{ij}^0 from adjacency matrix representation infinitize(n, l); for (int i = 0; i < n*n; i += n+1) l[i] = 0; // Repeated squaring until nothing changes int* restrict lnew = (int*) calloc(n*n, sizeof(int)); memcpy(lnew, l, n*n * sizeof(int)); for (int done = 0; !done; ) { done = square(n, l, lnew); memcpy(l, lnew, n*n * sizeof(int)); } free(lnew); deinfinitize(n, l); } /** * # The random graph model * * Of course, we need to run the shortest path algorithm on something! * For the sake of keeping things interesting, let's use a simple random graph * model to generate the input data. The $G(n,p)$ model simply includes each * possible edge with probability $p$, drops it otherwise -- doesn't get much * simpler than that. We use a thread-safe version of the Mersenne twister * random number generator in lieu of coin flips. */ int* gen_graph(int n, double p) { int* l = calloc(n*n, sizeof(int)); struct mt19937p state; sgenrand(10302011UL, &state); for (int j = 0; j < n; ++j) { for (int i = 0; i < n; ++i) l[j*n+i] = (genrand(&state) < p); l[j*n+j] = 0; } return l; } /** * # Result checks * * Simple tests are always useful when tuning code, so I have included * two of them. Since this computation doesn't involve floating point * arithmetic, we should get bitwise identical results from run to * run, even if we do optimizations that change the associativity of * our computations. The function `fletcher16` computes a simple * [simple checksum][wiki-fletcher] over the output of the * `shortest_paths` routine, which we can then use to quickly tell * whether something has gone wrong. The `write_matrix` routine * actually writes out a text representation of the matrix, in case we * want to load it into MATLAB to compare results. * * [wiki-fletcher]: http://en.wikipedia.org/wiki/Fletcher's_checksum */ int fletcher16(int* data, int count) { int sum1 = 0; int sum2 = 0; for(int index = 0; index < count; ++index) { sum1 = (sum1 + data[index]) % 255; sum2 = (sum2 + sum1) % 255; } return (sum2 << 8) | sum1; } void write_matrix(const char* fname, int n, int* a) { FILE* fp = fopen(fname, "w+"); if (fp == NULL) { fprintf(stderr, "Could not open output file: %s\n", fname); exit(-1); } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) fprintf(fp, "%d ", a[j*n+i]); fprintf(fp, "\n"); } fclose(fp); } /** * # The `main` event */ const char* usage = "path.x -- Parallel all-pairs shortest path on a random graph\n" "Flags:\n" " - n -- number of nodes (200)\n" " - p -- probability of including edges (0.05)\n" " - i -- file name where adjacency matrix should be stored (none)\n" " - o -- file name where output matrix should be stored (none)\n"; int main(int argc, char** argv) { int n = 200; // Number of nodes double p = 0.05; // Edge probability const char* ifname = NULL; // Adjacency matrix file name const char* ofname = NULL; // Distance matrix file name // Option processing extern char* optarg; const char* optstring = "hn:d:p:o:i:"; int c; while ((c = getopt(argc, argv, optstring)) != -1) { switch (c) { case 'h': fprintf(stderr, "%s", usage); return -1; case 'n': n = atoi(optarg); break; case 'p': p = atof(optarg); break; case 'o': ofname = optarg; break; case 'i': ifname = optarg; break; } } // Graph generation + output int* l = gen_graph(n, p); if (ifname) write_matrix(ifname, n, l); // Time the shortest paths code double t0 = omp_get_wtime(); shortest_paths(n, l); double t1 = omp_get_wtime(); printf("== OpenMP with %d threads\n", atoi(getenv("OMP_NUM_THREADS"))); printf("n: %d\n", n); printf("p: %g\n", p); printf("Time: %g\n", t1-t0); printf("Check: %X\n", fletcher16(l, n*n)); // Generate output file if (ofname) write_matrix(ofname, n, l); // Clean up free(l); return 0; }
inputMaster.c
/* test 'omp master' with preprocessing information also test 'omp barrier' */ #include <stdio.h> #ifdef _OPENMP #include "omp.h" #endif int main() { int nthreads; #pragma omp parallel { #if defined(_OPENMP) #pragma omp master { printf("I am thread %d out of %d threads\n", \ omp_get_thread_num(), omp_get_num_threads()); } #endif #pragma omp barrier #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif } return 0; }
convolution_2x2_pack8.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 conv2x2s1_pack8_avx(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; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); __m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + p * 8) : _mm256_set1_ps(0.f); out0.fill(_bias0); 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* kptr = (const float*)kernel.channel(p).row(q); // const float* kptr = (const float*)kernel + 4 * inch * p * 64; int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 1 < outw; j += 2) { __m256 _sum0 = _mm256_loadu_ps(outptr0); __m256 _sum1 = _mm256_loadu_ps(outptr0 + 8); __m256 _r00 = _mm256_broadcast_ss(r0); __m256 _r01 = _mm256_broadcast_ss(r0 + 1); __m256 _r02 = _mm256_broadcast_ss(r0 + 2); __m256 _r03 = _mm256_broadcast_ss(r0 + 3); __m256 _r04 = _mm256_broadcast_ss(r0 + 4); __m256 _r05 = _mm256_broadcast_ss(r0 + 5); __m256 _r06 = _mm256_broadcast_ss(r0 + 6); __m256 _r07 = _mm256_broadcast_ss(r0 + 7); r0 += 8; __m256 _k00 = _mm256_loadu_ps(kptr); __m256 _k01 = _mm256_loadu_ps(kptr + 8); __m256 _k02 = _mm256_loadu_ps(kptr + 16); __m256 _k03 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_fmadd_ps(_k03, _r03, _sum0); __m256 _k04 = _mm256_loadu_ps(kptr); __m256 _k05 = _mm256_loadu_ps(kptr + 8); __m256 _k06 = _mm256_loadu_ps(kptr + 16); __m256 _k07 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_fmadd_ps(_k04, _r04, _sum0); _sum0 = _mm256_fmadd_ps(_k05, _r05, _sum0); _sum0 = _mm256_fmadd_ps(_k06, _r06, _sum0); _sum0 = _mm256_fmadd_ps(_k07, _r07, _sum0); //======================================== _r00 = _mm256_broadcast_ss(r0); _r01 = _mm256_broadcast_ss(r0 + 1); _r02 = _mm256_broadcast_ss(r0 + 2); _r03 = _mm256_broadcast_ss(r0 + 3); _r04 = _mm256_broadcast_ss(r0 + 4); _r05 = _mm256_broadcast_ss(r0 + 5); _r06 = _mm256_broadcast_ss(r0 + 6); _r07 = _mm256_broadcast_ss(r0 + 7); r0 += 8; _sum1 = _mm256_fmadd_ps(_k00, _r00, _sum1); _sum1 = _mm256_fmadd_ps(_k01, _r01, _sum1); _sum1 = _mm256_fmadd_ps(_k02, _r02, _sum1); _sum1 = _mm256_fmadd_ps(_k03, _r03, _sum1); _sum1 = _mm256_fmadd_ps(_k04, _r04, _sum1); _sum1 = _mm256_fmadd_ps(_k05, _r05, _sum1); _sum1 = _mm256_fmadd_ps(_k06, _r06, _sum1); _sum1 = _mm256_fmadd_ps(_k07, _r07, _sum1); _k00 = _mm256_loadu_ps(kptr); _k01 = _mm256_loadu_ps(kptr + 8); _k02 = _mm256_loadu_ps(kptr + 16); _k03 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_fmadd_ps(_k03, _r03, _sum0); _k04 = _mm256_loadu_ps(kptr); _k05 = _mm256_loadu_ps(kptr + 8); _k06 = _mm256_loadu_ps(kptr + 16); _k07 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_fmadd_ps(_k04, _r04, _sum0); _sum0 = _mm256_fmadd_ps(_k05, _r05, _sum0); _sum0 = _mm256_fmadd_ps(_k06, _r06, _sum0); _sum0 = _mm256_fmadd_ps(_k07, _r07, _sum0); _r00 = _mm256_broadcast_ss(r0); _r01 = _mm256_broadcast_ss(r0 + 1); _r02 = _mm256_broadcast_ss(r0 + 2); _r03 = _mm256_broadcast_ss(r0 + 3); _r04 = _mm256_broadcast_ss(r0 + 4); _r05 = _mm256_broadcast_ss(r0 + 5); _r06 = _mm256_broadcast_ss(r0 + 6); _r07 = _mm256_broadcast_ss(r0 + 7); _sum1 = _mm256_fmadd_ps(_k00, _r00, _sum1); _sum1 = _mm256_fmadd_ps(_k01, _r01, _sum1); _sum1 = _mm256_fmadd_ps(_k02, _r02, _sum1); _sum1 = _mm256_fmadd_ps(_k03, _r03, _sum1); _sum1 = _mm256_fmadd_ps(_k04, _r04, _sum1); _sum1 = _mm256_fmadd_ps(_k05, _r05, _sum1); _sum1 = _mm256_fmadd_ps(_k06, _r06, _sum1); _sum1 = _mm256_fmadd_ps(_k07, _r07, _sum1); //=============== __m256 _r10 = _mm256_broadcast_ss(r1); __m256 _r11 = _mm256_broadcast_ss(r1 + 1); __m256 _r12 = _mm256_broadcast_ss(r1 + 2); __m256 _r13 = _mm256_broadcast_ss(r1 + 3); __m256 _r14 = _mm256_broadcast_ss(r1 + 4); __m256 _r15 = _mm256_broadcast_ss(r1 + 5); __m256 _r16 = _mm256_broadcast_ss(r1 + 6); __m256 _r17 = _mm256_broadcast_ss(r1 + 7); __m256 _k10 = _mm256_loadu_ps(kptr); __m256 _k11 = _mm256_loadu_ps(kptr + 8); __m256 _k12 = _mm256_loadu_ps(kptr + 16); __m256 _k13 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_fmadd_ps(_k13, _r13, _sum0); __m256 _k14 = _mm256_loadu_ps(kptr); __m256 _k15 = _mm256_loadu_ps(kptr + 8); __m256 _k16 = _mm256_loadu_ps(kptr + 16); __m256 _k17 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_fmadd_ps(_k14, _r14, _sum0); _sum0 = _mm256_fmadd_ps(_k15, _r15, _sum0); _sum0 = _mm256_fmadd_ps(_k16, _r16, _sum0); _sum0 = _mm256_fmadd_ps(_k17, _r17, _sum0); //======================================= r1 += 8; _r10 = _mm256_broadcast_ss(r1); _r11 = _mm256_broadcast_ss(r1 + 1); _r12 = _mm256_broadcast_ss(r1 + 2); _r13 = _mm256_broadcast_ss(r1 + 3); _r14 = _mm256_broadcast_ss(r1 + 4); _r15 = _mm256_broadcast_ss(r1 + 5); _r16 = _mm256_broadcast_ss(r1 + 6); _r17 = _mm256_broadcast_ss(r1 + 7); _sum1 = _mm256_fmadd_ps(_k10, _r10, _sum1); _sum1 = _mm256_fmadd_ps(_k11, _r11, _sum1); _sum1 = _mm256_fmadd_ps(_k12, _r12, _sum1); _sum1 = _mm256_fmadd_ps(_k13, _r13, _sum1); _sum1 = _mm256_fmadd_ps(_k14, _r14, _sum1); _sum1 = _mm256_fmadd_ps(_k15, _r15, _sum1); _sum1 = _mm256_fmadd_ps(_k16, _r16, _sum1); _sum1 = _mm256_fmadd_ps(_k17, _r17, _sum1); _k10 = _mm256_loadu_ps(kptr); _k11 = _mm256_loadu_ps(kptr + 8); _k12 = _mm256_loadu_ps(kptr + 16); _k13 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_fmadd_ps(_k13, _r13, _sum0); _k14 = _mm256_loadu_ps(kptr); _k15 = _mm256_loadu_ps(kptr + 8); _k16 = _mm256_loadu_ps(kptr + 16); _k17 = _mm256_loadu_ps(kptr + 24); _sum0 = _mm256_fmadd_ps(_k14, _r14, _sum0); _sum0 = _mm256_fmadd_ps(_k15, _r15, _sum0); _sum0 = _mm256_fmadd_ps(_k16, _r16, _sum0); _sum0 = _mm256_fmadd_ps(_k17, _r17, _sum0); r1 += 8; _r10 = _mm256_broadcast_ss(r1); _r11 = _mm256_broadcast_ss(r1 + 1); _r12 = _mm256_broadcast_ss(r1 + 2); _r13 = _mm256_broadcast_ss(r1 + 3); _r14 = _mm256_broadcast_ss(r1 + 4); _r15 = _mm256_broadcast_ss(r1 + 5); _r16 = _mm256_broadcast_ss(r1 + 6); _r17 = _mm256_broadcast_ss(r1 + 7); _sum1 = _mm256_fmadd_ps(_k10, _r10, _sum1); _sum1 = _mm256_fmadd_ps(_k11, _r11, _sum1); _sum1 = _mm256_fmadd_ps(_k12, _r12, _sum1); _sum1 = _mm256_fmadd_ps(_k13, _r13, _sum1); _sum1 = _mm256_fmadd_ps(_k14, _r14, _sum1); _sum1 = _mm256_fmadd_ps(_k15, _r15, _sum1); _sum1 = _mm256_fmadd_ps(_k16, _r16, _sum1); _sum1 = _mm256_fmadd_ps(_k17, _r17, _sum1); kptr -= 224; _mm256_storeu_ps(outptr0, _sum0); _mm256_storeu_ps(outptr0 + 8, _sum1); outptr0 += 16; } for (; j < outw; j++) { __m256 _sum = _mm256_loadu_ps(outptr0); __m256 _r00 = _mm256_broadcast_ss(r0); __m256 _r01 = _mm256_broadcast_ss(r0 + 1); __m256 _r02 = _mm256_broadcast_ss(r0 + 2); __m256 _r03 = _mm256_broadcast_ss(r0 + 3); __m256 _r04 = _mm256_broadcast_ss(r0 + 4); __m256 _r05 = _mm256_broadcast_ss(r0 + 5); __m256 _r06 = _mm256_broadcast_ss(r0 + 6); __m256 _r07 = _mm256_broadcast_ss(r0 + 7); __m256 _k00 = _mm256_loadu_ps(kptr); __m256 _k01 = _mm256_loadu_ps(kptr + 8); __m256 _k02 = _mm256_loadu_ps(kptr + 16); __m256 _k03 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_fmadd_ps(_k00, _r00, _sum); _sum = _mm256_fmadd_ps(_k01, _r01, _sum); _sum = _mm256_fmadd_ps(_k02, _r02, _sum); _sum = _mm256_fmadd_ps(_k03, _r03, _sum); __m256 _k04 = _mm256_loadu_ps(kptr); __m256 _k05 = _mm256_loadu_ps(kptr + 8); __m256 _k06 = _mm256_loadu_ps(kptr + 16); __m256 _k07 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_fmadd_ps(_k04, _r04, _sum); _sum = _mm256_fmadd_ps(_k05, _r05, _sum); _sum = _mm256_fmadd_ps(_k06, _r06, _sum); _sum = _mm256_fmadd_ps(_k07, _r07, _sum); //======================================== r0 += 8; _r00 = _mm256_broadcast_ss(r0); _r01 = _mm256_broadcast_ss(r0 + 1); _r02 = _mm256_broadcast_ss(r0 + 2); _r03 = _mm256_broadcast_ss(r0 + 3); _r04 = _mm256_broadcast_ss(r0 + 4); _r05 = _mm256_broadcast_ss(r0 + 5); _r06 = _mm256_broadcast_ss(r0 + 6); _r07 = _mm256_broadcast_ss(r0 + 7); _k00 = _mm256_loadu_ps(kptr); _k01 = _mm256_loadu_ps(kptr + 8); _k02 = _mm256_loadu_ps(kptr + 16); _k03 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_fmadd_ps(_k00, _r00, _sum); _sum = _mm256_fmadd_ps(_k01, _r01, _sum); _sum = _mm256_fmadd_ps(_k02, _r02, _sum); _sum = _mm256_fmadd_ps(_k03, _r03, _sum); _k04 = _mm256_loadu_ps(kptr); _k05 = _mm256_loadu_ps(kptr + 8); _k06 = _mm256_loadu_ps(kptr + 16); _k07 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_fmadd_ps(_k04, _r04, _sum); _sum = _mm256_fmadd_ps(_k05, _r05, _sum); _sum = _mm256_fmadd_ps(_k06, _r06, _sum); _sum = _mm256_fmadd_ps(_k07, _r07, _sum); //=============== __m256 _r10 = _mm256_broadcast_ss(r1); __m256 _r11 = _mm256_broadcast_ss(r1 + 1); __m256 _r12 = _mm256_broadcast_ss(r1 + 2); __m256 _r13 = _mm256_broadcast_ss(r1 + 3); __m256 _r14 = _mm256_broadcast_ss(r1 + 4); __m256 _r15 = _mm256_broadcast_ss(r1 + 5); __m256 _r16 = _mm256_broadcast_ss(r1 + 6); __m256 _r17 = _mm256_broadcast_ss(r1 + 7); __m256 _k10 = _mm256_loadu_ps(kptr); __m256 _k11 = _mm256_loadu_ps(kptr + 8); __m256 _k12 = _mm256_loadu_ps(kptr + 16); __m256 _k13 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_fmadd_ps(_k10, _r10, _sum); _sum = _mm256_fmadd_ps(_k11, _r11, _sum); _sum = _mm256_fmadd_ps(_k12, _r12, _sum); _sum = _mm256_fmadd_ps(_k13, _r13, _sum); __m256 _k14 = _mm256_loadu_ps(kptr); __m256 _k15 = _mm256_loadu_ps(kptr + 8); __m256 _k16 = _mm256_loadu_ps(kptr + 16); __m256 _k17 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_fmadd_ps(_k14, _r14, _sum); _sum = _mm256_fmadd_ps(_k15, _r15, _sum); _sum = _mm256_fmadd_ps(_k16, _r16, _sum); _sum = _mm256_fmadd_ps(_k17, _r17, _sum); //======================================= r1 += 8; _r10 = _mm256_broadcast_ss(r1); _r11 = _mm256_broadcast_ss(r1 + 1); _r12 = _mm256_broadcast_ss(r1 + 2); _r13 = _mm256_broadcast_ss(r1 + 3); _r14 = _mm256_broadcast_ss(r1 + 4); _r15 = _mm256_broadcast_ss(r1 + 5); _r16 = _mm256_broadcast_ss(r1 + 6); _r17 = _mm256_broadcast_ss(r1 + 7); _k10 = _mm256_loadu_ps(kptr); _k11 = _mm256_loadu_ps(kptr + 8); _k12 = _mm256_loadu_ps(kptr + 16); _k13 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_fmadd_ps(_k10, _r10, _sum); _sum = _mm256_fmadd_ps(_k11, _r11, _sum); _sum = _mm256_fmadd_ps(_k12, _r12, _sum); _sum = _mm256_fmadd_ps(_k13, _r13, _sum); _k14 = _mm256_loadu_ps(kptr); _k15 = _mm256_loadu_ps(kptr + 8); _k16 = _mm256_loadu_ps(kptr + 16); _k17 = _mm256_loadu_ps(kptr + 24); _sum = _mm256_fmadd_ps(_k14, _r14, _sum); _sum = _mm256_fmadd_ps(_k15, _r15, _sum); _sum = _mm256_fmadd_ps(_k16, _r16, _sum); _sum = _mm256_fmadd_ps(_k17, _r17, _sum); kptr -= 224; _mm256_storeu_ps(outptr0, _sum); outptr0 += 8; } r0 += 8; r1 += 8; } } } }
sample-4.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> int main() { int a[10][10], b[10][10], mul[10][10], r, c, i, j, k; system("cls"); printf("enter the number of row="); scanf("%d", &r); printf("enter the number of column="); scanf("%d", &c); printf("enter the first matrix element=\n"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { scanf("%d", &a[i][j]); } } printf("enter the second matrix element=\n"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { scanf("%d", &b[i][j]); } } int numCols = c; int NUM_THREADS = 12; // use built-in function? int numColsPerThread = floor(numCols / NUM_THREADS); int numColsForLastThread = numCols - (NUM_THREADS - 1) * numColsPerThread; int lastThreadID = NUM_THREADS - 1; int numNonLastThread = NUM_THREADS - 1; #pragma omp parallel { int threadID = omp_get_thread_num(); if (threadID != lastThreadID) { for (int i = 0; i < r; i++) { int nc = (threadID + 1) * numColsPerThread; for (int j = threadID * numColsPerThread; j < nc; j++) { mul[i][j] = 0; for (k = 0; k < nc; k++) { mul[i][j] += a[i][k] * b[k][j]; } } } } else { // last thread. for (int i = 0; i < r; i++) { int nc = numCols; for (int j = threadID * numColsPerThread; j < numCols; j++) { mul[i][j] = 0; for (k = 0; k < nc; k++) { mul[i][j] += a[i][k] * b[k][j]; } } } } } printf("multiply of the matrix=\n"); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { printf("%d\t", mul[i][j]); } printf("\n"); } return 0; }
post_utilities.h
#ifndef POST_UTILITIES_H #define POST_UTILITIES_H #include "utilities/timer.h" #include "includes/define.h" #include "includes/variables.h" #include "custom_utilities/create_and_destroy.h" #include "custom_utilities/GeometryFunctions.h" #include "custom_elements/Particle_Contact_Element.h" #ifdef _OPENMP #include <omp.h> #endif #include "utilities/openmp_utils.h" #include <limits> #include <iostream> #include <iomanip> #include <cmath> namespace Kratos { class PostUtilities { public: typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ModelPart::NodesContainerType NodesContainerType; KRATOS_CLASS_POINTER_DEFINITION(PostUtilities); /// Default constructor. PostUtilities() {}; /// Destructor. virtual ~PostUtilities() {}; void AddModelPartToModelPart(ModelPart& rCompleteModelPart, ModelPart& rModelPartToAdd) { ////WATCH OUT! This function respects the existing Id's! KRATOS_TRY; //preallocate the memory needed int tot_nodes = rCompleteModelPart.Nodes().size() + rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().size(); int tot_elements = rCompleteModelPart.Elements().size() + rModelPartToAdd.GetCommunicator().LocalMesh().Elements().size(); rCompleteModelPart.Nodes().reserve(tot_nodes); rCompleteModelPart.Elements().reserve(tot_elements); for (ModelPart::NodesContainerType::ptr_iterator node_it = rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_begin(); node_it != rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_end(); node_it++) { rCompleteModelPart.Nodes().push_back(*node_it); } for (ModelPart::ElementsContainerType::ptr_iterator elem_it = rModelPartToAdd.GetCommunicator().LocalMesh().Elements().ptr_begin(); elem_it != rModelPartToAdd.GetCommunicator().LocalMesh().Elements().ptr_end(); elem_it++) { rCompleteModelPart.Elements().push_back(*elem_it); } KRATOS_CATCH(""); } void AddSpheresNotBelongingToClustersToMixModelPart(ModelPart& rCompleteModelPart, ModelPart& rModelPartToAdd) { ////WATCH OUT! This function respects the existing Id's! KRATOS_TRY; //preallocate the memory needed int tot_size = rCompleteModelPart.Nodes().size(); for (ModelPart::NodesContainerType::ptr_iterator node_it = rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_begin(); node_it != rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_end(); node_it++) { ModelPart::NodeIterator i_iterator = node_it; Node < 3 > & i = *i_iterator; if (i.IsNot(DEMFlags::BELONGS_TO_A_CLUSTER)) {tot_size += 1;} } rCompleteModelPart.Nodes().reserve(tot_size); rCompleteModelPart.Elements().reserve(tot_size); for (ModelPart::NodesContainerType::ptr_iterator node_it = rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_begin(); node_it != rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_end(); node_it++) { ModelPart::NodeIterator i_iterator = node_it; Node < 3 > & i = *i_iterator; if (i.IsNot(DEMFlags::BELONGS_TO_A_CLUSTER)) {rCompleteModelPart.Nodes().push_back(*node_it);} } for (ModelPart::ElementsContainerType::ptr_iterator elem_it = rModelPartToAdd.GetCommunicator().LocalMesh().Elements().ptr_begin(); elem_it != rModelPartToAdd.GetCommunicator().LocalMesh().Elements().ptr_end(); elem_it++) { Node < 3 >& i = (*elem_it)->GetGeometry()[0]; if (i.IsNot(DEMFlags::BELONGS_TO_A_CLUSTER)) {rCompleteModelPart.Elements().push_back(*elem_it);} } KRATOS_CATCH(""); } array_1d<double,3> VelocityTrap(ModelPart& rModelPart, const array_1d<double,3>& low_point, const array_1d<double,3>& high_point) { ElementsArrayType& pElements = rModelPart.GetCommunicator().LocalMesh().Elements(); OpenMPUtils::CreatePartition(OpenMPUtils::GetNumThreads(), pElements.size(), this->GetElementPartition()); double velocity_X = 0.0, velocity_Y = 0.0, velocity_Z = 0.0; int number_of_elements = 0; #pragma omp parallel for reduction(+: velocity_X, velocity_Y, velocity_Z, number_of_elements) for (int k = 0; k < OpenMPUtils::GetNumThreads(); k++) { ElementsArrayType::iterator it_begin = pElements.ptr_begin() + this->GetElementPartition()[k]; ElementsArrayType::iterator it_end = pElements.ptr_begin() + this->GetElementPartition()[k + 1]; for (ElementsArrayType::iterator it = it_begin; it != it_end; ++it) { array_1d<double,3> coor = (it)->GetGeometry()[0].Coordinates(); if (coor[0] >= low_point[0] && coor[0] <= high_point[0] && coor[1] >= low_point[1] && coor[1] <= high_point[1] && coor[2] >= low_point[2] && coor[2] <= high_point[2]) { velocity_X += (it)->GetGeometry()[0].FastGetSolutionStepValue(VELOCITY_X); velocity_Y += (it)->GetGeometry()[0].FastGetSolutionStepValue(VELOCITY_Y); velocity_Z += (it)->GetGeometry()[0].FastGetSolutionStepValue(VELOCITY_Z); number_of_elements++; } } //elements for for (int i = 0; i < 3; ++i) { if (high_point[i] < low_point[i]) { KRATOS_THROW_ERROR(std::logic_error, "Check the limits of the Velocity Trap Box. Maximum coordinates smaller than minimum coordinates.", ""); } } } //parallel for if (number_of_elements) { velocity_X /= number_of_elements; velocity_Y /= number_of_elements; velocity_Z /= number_of_elements; } array_1d<double,3> velocity; velocity[0] = velocity_X; velocity[1] = velocity_Y; velocity[2] = velocity_Z; return velocity; }//VelocityTrap void IntegrationOfForces(ModelPart::NodesContainerType& mesh_nodes , array_1d<double, 3>& total_forces, array_1d<double, 3>& rotation_center, array_1d<double, 3>& total_moment) { for (ModelPart::NodesContainerType::ptr_iterator node_pointer_it = mesh_nodes.ptr_begin(); node_pointer_it != mesh_nodes.ptr_end(); ++node_pointer_it) { const array_1d<double, 3>& contact_forces_summed_at_structure_point = (*node_pointer_it)->FastGetSolutionStepValue(CONTACT_FORCES); noalias(total_forces) += contact_forces_summed_at_structure_point; array_1d<double, 3> vector_from_structure_center_to_structure_point; noalias(vector_from_structure_center_to_structure_point) = (*node_pointer_it)->Coordinates() - rotation_center; array_1d<double, 3> moment_to_add; GeometryFunctions::CrossProduct(vector_from_structure_center_to_structure_point, contact_forces_summed_at_structure_point, moment_to_add); noalias(total_moment) += moment_to_add; } } void IntegrationOfElasticForces(ModelPart::NodesContainerType& mesh_nodes, array_1d<double, 3>& total_forces) { for (ModelPart::NodesContainerType::ptr_iterator node_pointer_it = mesh_nodes.ptr_begin(); node_pointer_it != mesh_nodes.ptr_end(); ++node_pointer_it) { const array_1d<double, 3> elastic_forces_added_up_at_node = (*node_pointer_it)->FastGetSolutionStepValue(ELASTIC_FORCES); noalias(total_forces) += elastic_forces_added_up_at_node; } } array_1d<double, 3> ComputePoisson(ModelPart& rModelPart) { ElementsArrayType& pElements = rModelPart.GetCommunicator().LocalMesh().Elements(); double total_poisson_value = 0.0; unsigned int number_of_spheres_to_evaluate_poisson = 0; array_1d<double, 3> return_data = ZeroVector(3); // TODO: Add OpenMP code for (unsigned int k = 0; k < pElements.size(); k++) { ElementsArrayType::iterator it = pElements.ptr_begin() + k; Element* raw_p_element = &(*it); SphericParticle* p_sphere = dynamic_cast<SphericParticle*>(raw_p_element); double& particle_poisson_value = p_sphere->GetGeometry()[0].FastGetSolutionStepValue(POISSON_VALUE); particle_poisson_value = 0.0; double epsilon_XY = 0.0; double epsilon_Z = 0.0; unsigned int number_of_neighbors_per_sphere_to_evaluate_poisson = 0; array_1d<double, 3> other_to_me_vector; array_1d<double, 3> initial_other_to_me_vector; unsigned int number_of_neighbors = p_sphere->mNeighbourElements.size(); for (unsigned int i = 0; i < number_of_neighbors; i++) { if (p_sphere->mNeighbourElements[i] == NULL) continue; noalias(other_to_me_vector) = p_sphere->GetGeometry()[0].Coordinates() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].Coordinates(); noalias(initial_other_to_me_vector) = p_sphere->GetGeometry()[0].GetInitialPosition() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].GetInitialPosition(); double initial_distance_XY = sqrt(initial_other_to_me_vector[0] * initial_other_to_me_vector[0] + initial_other_to_me_vector[1] * initial_other_to_me_vector[1]); double initial_distance_Z = initial_other_to_me_vector[2]; if (initial_distance_XY && initial_distance_Z) { epsilon_XY = -1 + sqrt(other_to_me_vector[0] * other_to_me_vector[0] + other_to_me_vector[1] * other_to_me_vector[1]) / initial_distance_XY; epsilon_Z = -1 + fabs(other_to_me_vector[2] / initial_distance_Z); } else continue; if (epsilon_Z) { // Should it be added here 'if p_sphere->Id() < p_sphere->mNeighbourElements[i]->Id()'? if (((-epsilon_XY / epsilon_Z) > 0.5) || ((-epsilon_XY / epsilon_Z) < 0.0)) continue; // TODO: Check this particle_poisson_value -= epsilon_XY / epsilon_Z; number_of_neighbors_per_sphere_to_evaluate_poisson++; } else continue; } if (number_of_neighbors_per_sphere_to_evaluate_poisson) { particle_poisson_value /= number_of_neighbors_per_sphere_to_evaluate_poisson; number_of_spheres_to_evaluate_poisson++; total_poisson_value += particle_poisson_value; } } if (number_of_spheres_to_evaluate_poisson) total_poisson_value /= number_of_spheres_to_evaluate_poisson; return_data[0] = total_poisson_value; return return_data; } //ComputePoisson array_1d<double, 3> ComputePoisson2D(ModelPart& rModelPart) { // TODO: Adjust this function to the new changes made in the 3D version ElementsArrayType& pElements = rModelPart.GetCommunicator().LocalMesh().Elements(); double total_poisson_value = 0.0; unsigned int number_of_bonds_to_evaluate_poisson = 0; array_1d<double, 3> return_data = ZeroVector(3); double total_epsilon_y_value = 0.0; // TODO: Add OpenMP code for (unsigned int k = 0; k < pElements.size(); k++) { ElementsArrayType::iterator it = pElements.ptr_begin() + k; Element* raw_p_element = &(*it); SphericParticle* p_sphere = dynamic_cast<SphericParticle*>(raw_p_element); double& particle_poisson_value = p_sphere->GetGeometry()[0].FastGetSolutionStepValue(POISSON_VALUE); particle_poisson_value = 0.0; double epsilon_X = 0.0; double epsilon_Y = 0.0; unsigned int number_of_neighbors_to_evaluate_poisson = 0; array_1d<double, 3> other_to_me_vector; array_1d<double, 3> initial_other_to_me_vector; double average_sphere_epsilon_y_value = 0.0; unsigned int number_of_neighbors = p_sphere->mNeighbourElements.size(); for (unsigned int i = 0; i < number_of_neighbors; i++) { if (p_sphere->mNeighbourElements[i] == NULL) continue; noalias(other_to_me_vector) = p_sphere->GetGeometry()[0].Coordinates() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].Coordinates(); noalias(initial_other_to_me_vector) = p_sphere->GetGeometry()[0].GetInitialPosition() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].GetInitialPosition(); double initial_distance_X = initial_other_to_me_vector[0]; double initial_distance_Y = initial_other_to_me_vector[1]; if (initial_distance_X && initial_distance_Y) { epsilon_X = -1 + fabs(other_to_me_vector[0] / initial_distance_X); epsilon_Y = -1 + fabs(other_to_me_vector[1] / initial_distance_Y); } if (epsilon_Y) { particle_poisson_value -= epsilon_X / epsilon_Y; number_of_neighbors_to_evaluate_poisson++; total_poisson_value -= epsilon_X / epsilon_Y; number_of_bonds_to_evaluate_poisson++; } average_sphere_epsilon_y_value += epsilon_Y; } if (number_of_neighbors_to_evaluate_poisson) particle_poisson_value /= number_of_neighbors_to_evaluate_poisson; total_epsilon_y_value += average_sphere_epsilon_y_value / number_of_neighbors; } if (number_of_bonds_to_evaluate_poisson) total_poisson_value /= number_of_bonds_to_evaluate_poisson; total_epsilon_y_value /= pElements.size(); return_data[0] = total_poisson_value; return_data[1] = total_epsilon_y_value; return return_data; } //ComputePoisson2D void ComputeEulerAngles(ModelPart& rSpheresModelPart, ModelPart& rClusterModelPart) { ProcessInfo& r_process_info = rSpheresModelPart.GetProcessInfo(); bool if_trihedron_option = (bool) r_process_info[TRIHEDRON_OPTION]; typedef ModelPart::NodesContainerType NodesArrayType; NodesArrayType& pSpheresNodes = rSpheresModelPart.GetCommunicator().LocalMesh().Nodes(); NodesArrayType& pClusterNodes = rClusterModelPart.GetCommunicator().LocalMesh().Nodes(); #pragma omp parallel for for (int k = 0; k < (int) pSpheresNodes.size(); k++) { ModelPart::NodeIterator i_iterator = pSpheresNodes.ptr_begin() + k; Node < 3 > & i = *i_iterator; array_1d<double, 3 >& rotated_angle = i.FastGetSolutionStepValue(PARTICLE_ROTATION_ANGLE); if (if_trihedron_option && i.IsNot(DEMFlags::BELONGS_TO_A_CLUSTER)) { array_1d<double, 3 >& EulerAngles = i.FastGetSolutionStepValue(EULER_ANGLES); GeometryFunctions::EulerAnglesFromRotationAngle(EulerAngles, rotated_angle); } // if_trihedron_option && Not BELONGS_TO_A_CLUSTER }//for Node #pragma omp parallel for for (int k = 0; k < (int) pClusterNodes.size(); k++) { ModelPart::NodeIterator i_iterator = pClusterNodes.ptr_begin() + k; Node < 3 > & i = *i_iterator; Quaternion<double>& Orientation = i.FastGetSolutionStepValue(ORIENTATION); array_1d<double, 3 >& EulerAngles = i.FastGetSolutionStepValue(EULER_ANGLES); GeometryFunctions::QuaternionToGiDEulerAngles(Orientation, EulerAngles); }//for Node } //ComputeEulerAngles double QuasiStaticAdimensionalNumber(ModelPart& rParticlesModelPart, ModelPart& rContactModelPart, ProcessInfo& r_process_info) { double adimensional_value = 0.0; ElementsArrayType& pParticleElements = rParticlesModelPart.GetCommunicator().LocalMesh().Elements(); OpenMPUtils::CreatePartition(OpenMPUtils::GetNumThreads(), pParticleElements.size(), this->GetElementPartition()); array_1d<double,3> particle_forces; const array_1d<double,3>& gravity = r_process_info[GRAVITY]; double total_force = 0.0; //#pragma omp parallel for #pragma omp parallel for reduction(+:total_force) for (int k = 0; k < OpenMPUtils::GetNumThreads(); k++) { ElementsArrayType::iterator it_begin = pParticleElements.ptr_begin() + this->GetElementPartition()[k]; ElementsArrayType::iterator it_end = pParticleElements.ptr_begin() + this->GetElementPartition()[k + 1]; for (ElementsArrayType::iterator it = it_begin; it != it_end; ++it) { Element::GeometryType& geom = it->GetGeometry(); if (geom[0].IsNot(DEMFlags::FIXED_VEL_X) && geom[0].IsNot(DEMFlags::FIXED_VEL_Y) && geom[0].IsNot(DEMFlags::FIXED_VEL_Z)) { particle_forces = geom[0].FastGetSolutionStepValue(TOTAL_FORCES); double mass = geom[0].FastGetSolutionStepValue(NODAL_MASS); particle_forces[0] += mass * gravity[0]; particle_forces[1] += mass * gravity[1]; particle_forces[2] += mass * gravity[2]; double module = 0.0; GeometryFunctions::module(particle_forces, module); total_force += module; } //if }//balls }//paralel ElementsArrayType& pContactElements = rContactModelPart.GetCommunicator().LocalMesh().Elements(); OpenMPUtils::CreatePartition(OpenMPUtils::GetNumThreads(), pContactElements.size(), this->GetElementPartition()); array_1d<double,3> contact_forces; double total_elastic_force = 0.0; #pragma omp parallel for reduction(+:total_elastic_force) for (int k = 0; k < OpenMPUtils::GetNumThreads(); k++) { ElementsArrayType::iterator it_begin = pContactElements.ptr_begin() + this->GetElementPartition()[k]; ElementsArrayType::iterator it_end = pContactElements.ptr_begin() + this->GetElementPartition()[k + 1]; for (ElementsArrayType::iterator it = it_begin; it != it_end; ++it){ Element::GeometryType& geom = it->GetGeometry(); if (geom[0].IsNot(DEMFlags::FIXED_VEL_X) && geom[0].IsNot(DEMFlags::FIXED_VEL_Y) && geom[0].IsNot(DEMFlags::FIXED_VEL_Z) && geom[1].IsNot(DEMFlags::FIXED_VEL_X) && geom[1].IsNot(DEMFlags::FIXED_VEL_Y) && geom[1].IsNot(DEMFlags::FIXED_VEL_Z)) { contact_forces = it->GetValue(LOCAL_CONTACT_FORCE); double module = 0.0; GeometryFunctions::module(contact_forces, module); total_elastic_force += module; } } } if (total_elastic_force != 0.0) { adimensional_value = total_force/total_elastic_force; } else { KRATOS_THROW_ERROR(std::runtime_error,"There are no elastic forces= ", total_elastic_force) } return adimensional_value; }//QuasiStaticAdimensionalNumber std::vector<unsigned int>& GetElementPartition() {return (mElementPartition);}; protected: std::vector<unsigned int> mElementPartition; }; // Class PostUtilities } // namespace Kratos. #endif // POST_UTILITIES_H
GB_binop__rminus_fp32.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__rminus_fp32) // A.*B function (eWiseMult): GB (_AemultB_08__rminus_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__rminus_fp32) // A.*B function (eWiseMult): GB (_AemultB_04__rminus_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_fp32) // A*D function (colscale): GB (_AxD__rminus_fp32) // D*A function (rowscale): GB (_DxB__rminus_fp32) // C+=B function (dense accum): GB (_Cdense_accumB__rminus_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__rminus_fp32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_fp32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_fp32) // C=scalar+B GB (_bind1st__rminus_fp32) // C=scalar+B' GB (_bind1st_tran__rminus_fp32) // C=A+scalar GB (_bind2nd__rminus_fp32) // C=A'+scalar GB (_bind2nd_tran__rminus_fp32) // C type: float // A type: float // A pattern? 0 // B type: float // B pattern? 0 // BinaryOp: cij = (bij - aij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // 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) \ float 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) \ float 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) \ float 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 - x) ; // 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_RMINUS || GxB_NO_FP32 || GxB_NO_RMINUS_FP32) //------------------------------------------------------------------------------ // 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__rminus_fp32) ( 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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( 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 float float bwork = (*((float *) 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__rminus_fp32) ( 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 float *restrict Cx = (float *) 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__rminus_fp32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) 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__rminus_fp32) ( 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) ; float alpha_scalar ; float beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((float *) alpha_scalar_in)) ; beta_scalar = (*((float *) 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__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( 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 float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) 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 ; float bij = GBX (Bx, p, false) ; Cx [p] = (bij - x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rminus_fp32) ( 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 ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = GBX (Ax, p, false) ; Cx [p] = (y - aij) ; } 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) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB (_bind1st_tran__rminus_fp32) ( 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 \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // 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) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (y - aij) ; \ } GrB_Info GB (_bind2nd_tran__rminus_fp32) ( 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 float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
DRB035-truedepscalar-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. */ /* Loop carried true dep between tmp =.. and ..= tmp. Data race pair: tmp@66:12 vs. tmp@67:5 */ #include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; int tmp; tmp = 10; int len=100; int a[100]; #pragma omp parallel for schedule(dynamic) for (i=0;i<len;i++) { a[i] = tmp; tmp =a[i]+i; } printf("a[50]=%d\n", a[50]); return 0; }
support_classes.h
#include <chrono> #include<set> #include "support_func.h" using namespace std; class StopW { std::chrono::steady_clock::time_point time_begin; public: StopW() { time_begin = std::chrono::steady_clock::now(); } float getElapsedTimeMicro() { std::chrono::steady_clock::time_point time_end = std::chrono::steady_clock::now(); return (std::chrono::duration_cast<std::chrono::microseconds>(time_end - time_begin).count()); } void reset() { time_begin = std::chrono::steady_clock::now(); } }; class KLgraph { public: int L; vector< vector <uint32_t> > longmatrixNN; void BuildByNumber(int l, vector<float> dataset, size_t N, size_t d, std::mt19937 random_gen, Metric *metric); void BuildByNumberCustom(int l, vector<float> dataset, size_t N, size_t d, size_t sqrtN, std::mt19937 random_gen, Metric *metric); void BuildByDist(int l, vector<float> dataset, size_t N, size_t d, std::mt19937 random_gen, Metric *metric); }; void KLgraph::BuildByNumber(int l, vector<float> dataset, size_t N, size_t d, std::mt19937 random_gen, Metric *metric){ L = l; vector<uint32_t> sloy; for (int i=0; i < N; ++i) { longmatrixNN.push_back(sloy); } vector<float> custom_prob; for (int i=0; i < N - 1; ++i) { custom_prob.push_back(1. / (i+ 1) ); } discrete_distribution<int> custom_distr (custom_prob.begin(), custom_prob.end()); #pragma omp parallel for for(int i=0; i < N; ++i) { int num; const float *point_i = dataset.data() + i*d; vector<Neighbor> chosen_neigs; set<Neighbor> chn_neigs; for (int j = 0; j < N; ++j) { if (i != j) { const float *point_j = dataset.data() + j * d; float dist = metric->Dist(point_i, point_j, d); Neighbor neig{j, dist}; chosen_neigs.push_back(neig); } } sort(chosen_neigs.begin(), chosen_neigs.end()); unordered_set <int> ll; while (ll.size() < L) { num = custom_distr(random_gen); ll.insert(num); } for (auto el : ll) { longmatrixNN[i].push_back(chosen_neigs[el].number); } } } void KLgraph::BuildByNumberCustom(int l, vector<float> dataset, size_t N, size_t d, size_t sqrtN, std::mt19937 random_gen, Metric *metric){ cout << sqrtN << ' ' << N << endl; L = l; vector<uint32_t> sloy; for (int i=0; i < N; ++i) { longmatrixNN.push_back(sloy); } vector<float> custom_prob; for (int i=0; i < sqrtN; ++i) { custom_prob.push_back(1. / (i+ 1) ); } discrete_distribution<int> custom_distr (custom_prob.begin(), custom_prob.end()); uniform_int_distribution<int> uniform_distr(0, N - 1); #pragma omp parallel for for(int i=0; i < N; ++i) { int num; const float *point_i = dataset.data() + i * d; vector<Neighbor> chosen_neigs; set<Neighbor> chn_neigs; while (chn_neigs.size() < sqrtN) { num = uniform_distr(random_gen); if (num != i) { const float *point_num = dataset.data() + num * d; float dist = metric->Dist(point_i, point_num, d); Neighbor neig{num, dist}; chn_neigs.insert(neig); } } for (auto el : chn_neigs) { chosen_neigs.push_back(el); } sort(chosen_neigs.begin(), chosen_neigs.end()); unordered_set <int> ll; while (ll.size() < L) { num = custom_distr(random_gen); ll.insert(num); } for (auto el : ll) { longmatrixNN[i].push_back(chosen_neigs[el].number); } } } void KLgraph::BuildByDist(int l, vector<float> dataset, size_t N, size_t d, std::mt19937 random_gen, Metric *metric){ L = l; float thr = 0.03; vector<uint32_t> sloy; for (int i=0; i < N; ++i) { longmatrixNN.push_back(sloy); } #pragma omp parallel for for(int i=0; i < N; ++i) { int num; const float *point_i = dataset.data() + i*d; vector<Neighbor> chosen_neigs; for (int j = 0; j < N; ++j) { if (i != j) { const float *point_j = dataset.data() + j * d; float dist = metric->Dist(point_i, point_j, d); if (dist > thr) { Neighbor neig{j, dist}; chosen_neigs.push_back(neig); } } } unordered_set <int> ll; vector<float> custom_prob; for (int j = 0; j < chosen_neigs.size(); ++j) { float dist_cur = chosen_neigs[j].dist; custom_prob.push_back(pow(pow(dist_cur, -1), d)); } discrete_distribution<int> custom_distr (custom_prob.begin(), custom_prob.end()); while (ll.size() < L) { num = custom_distr(random_gen); ll.insert(num); } for (auto el : ll) { longmatrixNN[i].push_back(chosen_neigs[el].number); } } }
GB_binop__bxor_int64.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__bxor_int64) // A.*B function (eWiseMult): GB (_AemultB_08__bxor_int64) // A.*B function (eWiseMult): GB (_AemultB_02__bxor_int64) // A.*B function (eWiseMult): GB (_AemultB_04__bxor_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bxor_int64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bxor_int64) // C+=b function (dense accum): GB (_Cdense_accumb__bxor_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bxor_int64) // C=scalar+B GB (_bind1st__bxor_int64) // C=scalar+B' GB (_bind1st_tran__bxor_int64) // C=A+scalar GB (_bind2nd__bxor_int64) // C=A'+scalar GB (_bind2nd_tran__bxor_int64) // C type: int64_t // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // BinaryOp: cij = (aij) ^ (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) \ int64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ 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 = (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_BXOR || GxB_NO_INT64 || GxB_NO_BXOR_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__bxor_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__bxor_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__bxor_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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bxor_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__bxor_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__bxor_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__bxor_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__bxor_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 //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bxor_int64) ( 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] = (x) ^ (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bxor_int64) ( 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 ; int64_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) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) ^ (aij) ; \ } GrB_Info GB (_bind1st_tran__bxor_int64) ( 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 } //------------------------------------------------------------------------------ // 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) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) ^ (y) ; \ } GrB_Info GB (_bind2nd_tran__bxor_int64) ( 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
idle.c
// RUN: %libomp-compile-and-run | FileCheck %s // REQUIRES: ompt #include "callback.h" #include <omp.h> int main() { int x = 0; #pragma omp parallel num_threads(3) { #pragma omp atomic x++; } #pragma omp parallel num_threads(2) { #pragma omp atomic x++; } printf("x=%d\n", x); // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_idle' // CHECK: 0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_idle_begin: // CHECK: {{^}}[[THREAD_ID]]: ompt_event_idle_end: return 0; }
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 24; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
sapH_fmt_plug.c
/* * this is a SAP-H plugin for john the ripper. * Copyright (c) 2014 JimF, 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. * * The internals of this algorithm were found on the hashcat forum, and * implemented here, whether, it is right or wrong. A link to that post is: * http://hashcat.net/forum/thread-3804.html * There are some things which are unclear, BUT which have been coded as listed * within that post. Things such as the signatures themselves are somewhat * unclear, and do not follow patterns well. The sha1 signature is lower case * and does not contain the 1. The other signatures are upper case. This code * was implemented in the exact manner as described on the forum, and will be * used as such, until we find out that it is right or wrong (i.e. we get sample * hashs from a REAL system in the other formats). If things are not correct, * getting this format corrected will be trivial. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_sapH; #elif FMT_REGISTERS_H john_register_one(&fmt_sapH); #else #include <string.h> #include <ctype.h> #include "arch.h" /* for now, undef this until I get OMP working, then start on SIMD */ //#undef _OPENMP //#undef SIMD_COEF_32 //#undef SIMD_PARA_SHA1 //#undef SIMD_COEF_32 //#undef SIMD_PARA_SHA256 //#undef SIMD_COEF_64 //#undef SIMD_PARA_SHA512 #include "misc.h" #include "common.h" #include "formats.h" #include "base64_convert.h" #include "sha.h" #include "sha2.h" #include "johnswap.h" #if defined(_OPENMP) #include <omp.h> #ifdef SIMD_COEF_32 #ifndef OMP_SCALE #define OMP_SCALE 8 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 64 #endif #endif #endif /* * Assumption is made that SIMD_COEF_32*SIMD_PARA_SHA1 is >= than * SHA256_COEF*PARA and SHA512_COEF*PARA, and that these other 2 * will evenly divide the SIMD_COEF_32*SHA1_SSRE_PARA value. * Works with current code. BUT if SIMD_PARA_SHA1 was 3 and * SIMD_PARA_SHA256 was 2, then we would have problems. */ #ifdef SIMD_COEF_32 #define NBKEYS1 (SIMD_COEF_32 * SIMD_PARA_SHA1) #else #define NBKEYS1 1 #endif #ifdef SIMD_COEF_32 #define NBKEYS256 (SIMD_COEF_32 * SIMD_PARA_SHA256) #else #define NBKEYS256 1 #endif #ifdef SIMD_COEF_64 #define NBKEYS512 (SIMD_COEF_64 * SIMD_PARA_SHA512) #else #define NBKEYS512 1 #endif // the least common multiple of the NBKEYS* above #define NBKEYS (SIMD_COEF_32*SIMD_PARA_SHA1*SIMD_PARA_SHA256*SIMD_PARA_SHA512) #include "simd-intrinsics.h" #define FORMAT_LABEL "saph" #define FORMAT_NAME "SAP CODVN H (PWDSALTEDHASH)" #define FORMAT_TAG "{x-issha, " #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define FORMAT_TAG256 "{x-isSHA256, " #define FORMAT_TAG256_LEN (sizeof(FORMAT_TAG256)-1) #define FORMAT_TAG384 "{x-isSHA384, " #define FORMAT_TAG384_LEN (sizeof(FORMAT_TAG384)-1) #define FORMAT_TAG512 "{x-isSHA512, " #define FORMAT_TAG512_LEN (sizeof(FORMAT_TAG512)-1) #define ALGORITHM_NAME "SHA-1/SHA-2 " SHA1_ALGORITHM_NAME #include "memdbg.h" #define BENCHMARK_COMMENT " (SHA1x1024)" #define BENCHMARK_LENGTH 0 #define SALT_LENGTH 16 /* the max used sized salt */ #define CIPHERTEXT_LENGTH 132 /* max salt+sha512 + 2^32 iterations */ #define BINARY_SIZE 16 /* we cut off all hashes down to 16 bytes */ #define MAX_BINARY_SIZE 64 /* sha512 is 64 byte */ #define SHA1_BINARY_SIZE 20 #define SHA256_BINARY_SIZE 32 #define SHA384_BINARY_SIZE 48 #define SHA512_BINARY_SIZE 64 #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(struct sapH_salt) #define SALT_ALIGN 4 /* NOTE, format is slow enough that endianity conversion is pointless. Just use flat buffers. */ #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT NBKEYS #define MAX_KEYS_PER_CRYPT NBKEYS #define PLAINTEXT_LENGTH 23 /* Real world max. is 40 */ #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define PLAINTEXT_LENGTH 40 #endif static struct fmt_tests tests[] = { /* first 2 hashes are 'default' 1024 iteration with 12 bytes salt so */ /* timings reflect that, and benchmark comment set to (sha1, 1024) */ {"{x-issha, 1024}hmiyJ2a/Z+HRpjQ37Osz+rYax9UxMjM0NTY3ODkwYWI=","OpenWall"}, {"{x-issha, 1024}fRLe9EvN/Le81BDEDZR5SEC0O6BhYmNkZWZnaHVrYWw=","JohnTheRipper"}, {"{x-issha, 1024}L1PHSP1vOwdYh0ASjswI69fQQQhzQXFlWmxnaFA5","booboo"}, {"{x-issha, 1024}dCjaHQ47/WeSwsoSYDR/8puLby5T","booboo"}, /* 1 byte salt */ {"{x-issha, 1024}+q+WSxWXJt7SjV5VJEymEKPUbn1FQWM=","HYulafeE!3"}, {"{x-issha, 6666}7qNFlIR+ZQUpe2DtSBvpvzU5VlBzcG1DVGxvOEFQODI=","dif_iterations"}, {"{x-isSHA256, 3000}UqMnsr5BYN+uornWC7yhGa/Wj0u5tshX19mDUQSlgih6OTFoZjRpMQ==","booboo"}, {"{x-isSHA256, 3000}ydi0JlyU6lX5305Qk/Q3uLBbIFjWuTyGo3tPBZDcGFd6NkFvV1gza3RkNg==","GottaGoWhereNeeded"}, {"{x-isSHA384, 5000}3O/F4YGKNmIYHDu7ZQ7Q+ioCOQi4HRY4yrggKptAU9DtmHigCuGqBiAPVbKbEAfGTzh4YlZLWUM=","booboo"}, {"{x-isSHA384, 5000}XSLo2AKIvACwqW/X416UeVbHOXmio4u27Z7cgXS2rxND+zTpN+x3JNfQcEQX2PT0Z3FPdEY2dHM=","yiPP3rs"}, {"{x-isSHA512, 7500}ctlX6qYsWspafEzwoej6nFp7zRQQjr8y22vE+xeveIX2gUndAw9N2Gep5azNUwuxOe2o7tusF800OfB9tg4taWI4Tg==","booboo"}, {"{x-isSHA512, 7500}Qyrh2JXgGkvIfKYOJRdWFut5/pVnXI/vZvqJ7N+Tz9M1zUTXGWCZSom4az4AhqOuAahBwuhcKqMq/pYPW4h3cThvT2JaWVBw","hapy1CCe!"}, {"{x-isSHA512, 18009}C2+Sij3JyXPPDuQgsF6Zot7XnjRFX86X67tWJpUzXNnFw2dKcGPH6HDEzVJ8HN8+cJe4vZaOYTlmdz09gI7YEwECAwQFBgcICQoLDA0ODwA=","maxlen"}, {NULL} }; static char (*saved_plain)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_key)[BINARY_SIZE/sizeof(uint32_t)]; static struct sapH_salt { int slen; /* actual length of salt ( 1 to 16 bytes) */ int type; /* 1, 256, 384 or 512 for sha1, sha256, sha384 or sha512 */ unsigned iter; /* from 1 to 2^32 rounds */ unsigned char s[SALT_LENGTH]; } *sapH_cur_salt; static void init(struct fmt_main *self) { #if defined (_OPENMP) int 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_plain = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_plain)); crypt_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_key)); } static void done(void) { MEM_FREE(crypt_key); MEM_FREE(saved_plain); } static int valid(char *ciphertext, struct fmt_main *self) { char *cp = ciphertext; char *keeptr; int len, hash_len=0; char tmp[MAX_BINARY_SIZE+SALT_LENGTH]; /* first check for 'simple' signatures before allocation other stuff. */ if (!strncmp(cp, FORMAT_TAG, FORMAT_TAG_LEN)) hash_len = SHA1_BINARY_SIZE; else if (!strncmp(cp, FORMAT_TAG256, FORMAT_TAG256_LEN)) hash_len = SHA256_BINARY_SIZE; else if (!strncmp(cp, FORMAT_TAG384, FORMAT_TAG384_LEN)) hash_len = SHA384_BINARY_SIZE; else if (!strncmp(cp, FORMAT_TAG512, FORMAT_TAG512_LEN)) hash_len = SHA512_BINARY_SIZE; else return 0; keeptr = strdup(cp); cp = keeptr; while (*cp++ != ' ') ; /* skip the "{x-issha?, " */ if ((cp = strtokm(cp, "}")) == NULL) goto err; if (!isdecu(cp)) goto err; // we want the entire rest of the line here, to mime compare. if ((cp = strtokm(NULL, "")) == NULL) goto err; if (strlen(cp) != base64_valid_length(cp, e_b64_mime, flg_Base64_MIME_TRAIL_EQ|flg_Base64_MIME_TRAIL_EQ_CNT, 0)) goto err; len = base64_convert(cp, e_b64_mime, strlen(cp), tmp, e_b64_raw, sizeof(tmp), flg_Base64_MIME_TRAIL_EQ, 0); len -= hash_len; if (len < 1 || len > SALT_LENGTH) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void set_salt(void *salt) { sapH_cur_salt = (struct sapH_salt*)salt; } static void set_key(char *key, int index) { strcpy((char*)saved_plain[index], key); } static char *get_key(int index) { return (char*)saved_plain[index]; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (*(uint32_t*)binary == *(uint32_t*)crypt_key[index]) return 1; return 0; } static int cmp_exact(char *source, int index) { return 1; } static int cmp_one(void * binary, int index) { return !memcmp(binary, crypt_key[index], BINARY_SIZE); } static void crypt_all_1(int count) { int idx=0; #if defined(_OPENMP) #pragma omp parallel for default(none) private(idx) shared(count, sapH_cur_salt, saved_plain, crypt_key) #endif for (idx = 0; idx < count; idx += NBKEYS1) { SHA_CTX ctx; uint32_t i; #if !defined (SIMD_COEF_32) uint32_t len = strlen(saved_plain[idx]); unsigned char tmp[PLAINTEXT_LENGTH+SHA1_BINARY_SIZE], *cp=&tmp[len]; SHA1_Init(&ctx); SHA1_Update(&ctx, saved_plain[idx], len); SHA1_Update(&ctx, sapH_cur_salt->s, sapH_cur_salt->slen); strcpy((char*)tmp, saved_plain[idx]); len += SHA1_BINARY_SIZE; SHA1_Final(cp, &ctx); for (i = 1; i < sapH_cur_salt->iter; ++i) { SHA1_Init(&ctx); SHA1_Update(&ctx, tmp, len); SHA1_Final(cp, &ctx); } memcpy(crypt_key[idx], cp, BINARY_SIZE); #else unsigned char _IBuf[64*NBKEYS1+MEM_ALIGN_SIMD], *keys, tmpBuf[20], _OBuf[20*NBKEYS1+MEM_ALIGN_SIMD], *crypt; uint32_t j, *crypt32, offs[NBKEYS1], len; keys = (unsigned char*)mem_align(_IBuf, MEM_ALIGN_SIMD); crypt = (unsigned char*)mem_align(_OBuf, MEM_ALIGN_SIMD); crypt32 = (uint32_t*)crypt; memset(keys, 0, 64*NBKEYS1); for (i = 0; i < NBKEYS1; ++i) { len = strlen(saved_plain[idx+i]); SHA1_Init(&ctx); SHA1_Update(&ctx, saved_plain[idx+i], len); SHA1_Update(&ctx, sapH_cur_salt->s, sapH_cur_salt->slen); SHA1_Final(tmpBuf, &ctx); memcpy(&keys[i<<6], saved_plain[idx+i], len); memcpy(&keys[(i<<6)+len], tmpBuf, 20); keys[(i<<6)+len+20] = 0x80; offs[i] = len; len += 20; keys[(i<<6)+60] = (len<<3)&0xff; keys[(i<<6)+61] = (len>>5); } for (i = 1; i < sapH_cur_salt->iter; ++i) { uint32_t k; SIMDSHA1body(keys, crypt32, NULL, SSEi_FLAT_IN); for (k = 0; k < NBKEYS1; ++k) { uint32_t *pcrypt = &crypt32[ ((k/SIMD_COEF_32)*(SIMD_COEF_32*5)) + (k&(SIMD_COEF_32-1))]; uint32_t *Icp32 = (uint32_t *)(&keys[(k<<6)+offs[k]]); for (j = 0; j < 5; ++j) { Icp32[j] = JOHNSWAP(*pcrypt); pcrypt += SIMD_COEF_32; } } } // now marshal into crypt_out; for (i = 0; i < NBKEYS1; ++i) { uint32_t *Optr32 = (uint32_t*)(crypt_key[idx+i]); uint32_t *Iptr32 = &crypt32[ ((i/SIMD_COEF_32)*(SIMD_COEF_32*5)) + (i&(SIMD_COEF_32-1))]; // we only want 16 bytes, not 20 for (j = 0; j < 4; ++j) { Optr32[j] = JOHNSWAP(*Iptr32); Iptr32 += SIMD_COEF_32; } } #endif } } static void crypt_all_256(int count) { int idx; #if defined(_OPENMP) #pragma omp parallel for default(none) private(idx) shared(count, sapH_cur_salt, saved_plain, crypt_key) #endif for (idx = 0; idx < count; idx += NBKEYS256) { SHA256_CTX ctx; uint32_t i; #if !defined (SIMD_COEF_32) uint32_t len = strlen(saved_plain[idx]); unsigned char tmp[PLAINTEXT_LENGTH+SHA256_BINARY_SIZE], *cp=&tmp[len]; SHA256_Init(&ctx); SHA256_Update(&ctx, saved_plain[idx], len); SHA256_Update(&ctx, sapH_cur_salt->s, sapH_cur_salt->slen); strcpy((char*)tmp, saved_plain[idx]); len += SHA256_BINARY_SIZE; SHA256_Final(cp, &ctx); for (i = 1; i < sapH_cur_salt->iter; ++i) { SHA256_Init(&ctx); SHA256_Update(&ctx, tmp, len); SHA256_Final(cp, &ctx); } memcpy(crypt_key[idx], cp, BINARY_SIZE); #else unsigned char _IBuf[64*NBKEYS256+MEM_ALIGN_SIMD], *keys, tmpBuf[32], _OBuf[32*NBKEYS256+MEM_ALIGN_SIMD], *crypt; uint32_t j, *crypt32, offs[NBKEYS256], len; keys = (unsigned char*)mem_align(_IBuf, MEM_ALIGN_SIMD); crypt = (unsigned char*)mem_align(_OBuf, MEM_ALIGN_SIMD); crypt32 = (uint32_t*)crypt; memset(keys, 0, 64*NBKEYS256); for (i = 0; i < NBKEYS256; ++i) { len = strlen(saved_plain[idx+i]); SHA256_Init(&ctx); SHA256_Update(&ctx, saved_plain[idx+i], len); SHA256_Update(&ctx, sapH_cur_salt->s, sapH_cur_salt->slen); SHA256_Final(tmpBuf, &ctx); memcpy(&keys[i<<6], saved_plain[idx+i], len); memcpy(&keys[(i<<6)+len], tmpBuf, 32); keys[(i<<6)+len+32] = 0x80; offs[i] = len; len += 32; keys[(i<<6)+60] = (len<<3)&0xff; keys[(i<<6)+61] = (len>>5); } for (i = 1; i < sapH_cur_salt->iter; ++i) { uint32_t k; SIMDSHA256body(keys, crypt32, NULL, SSEi_FLAT_IN); for (k = 0; k < NBKEYS256; ++k) { uint32_t *pcrypt = &crypt32[ ((k/SIMD_COEF_32)*(SIMD_COEF_32*8)) + (k&(SIMD_COEF_32-1))]; uint32_t *Icp32 = (uint32_t *)(&keys[(k<<6)+offs[k]]); for (j = 0; j < 8; ++j) { Icp32[j] = JOHNSWAP(*pcrypt); pcrypt += SIMD_COEF_32; } } } // now marshal into crypt_out; for (i = 0; i < NBKEYS256; ++i) { uint32_t *Optr32 = (uint32_t*)(crypt_key[idx+i]); uint32_t *Iptr32 = &crypt32[ ((i/SIMD_COEF_32)*(SIMD_COEF_32*8)) + (i&(SIMD_COEF_32-1))]; // we only want 16 bytes, not 32 for (j = 0; j < 4; ++j) { Optr32[j] = JOHNSWAP(*Iptr32); Iptr32 += SIMD_COEF_32; } } #endif } } static void crypt_all_384(int count) { int idx; #if defined(_OPENMP) #pragma omp parallel for default(none) private(idx) shared(count, sapH_cur_salt, saved_plain, crypt_key) #endif for (idx = 0; idx < count; idx+=NBKEYS512) { SHA512_CTX ctx; uint32_t i; #if !defined SIMD_COEF_64 uint32_t len = strlen(saved_plain[idx]); unsigned char tmp[PLAINTEXT_LENGTH+SHA384_BINARY_SIZE], *cp=&tmp[len]; SHA384_Init(&ctx); SHA384_Update(&ctx, saved_plain[idx], len); SHA384_Update(&ctx, sapH_cur_salt->s, sapH_cur_salt->slen); strcpy((char*)tmp, saved_plain[idx]); len += SHA384_BINARY_SIZE; SHA384_Final(cp, &ctx); for (i = 1; i < sapH_cur_salt->iter; ++i) { SHA384_Init(&ctx); SHA384_Update(&ctx, tmp, len); SHA384_Final(cp, &ctx); } memcpy(crypt_key[idx], cp, BINARY_SIZE); #else unsigned char _IBuf[128*NBKEYS512+MEM_ALIGN_SIMD], *keys, tmpBuf[64], _OBuf[64*NBKEYS512+MEM_ALIGN_SIMD], *crypt; uint64_t j, *crypt64, offs[NBKEYS512]; uint32_t len; keys = (unsigned char*)mem_align(_IBuf, MEM_ALIGN_SIMD); crypt = (unsigned char*)mem_align(_OBuf, MEM_ALIGN_SIMD); crypt64 = (uint64_t*)crypt; memset(keys, 0, 128*NBKEYS512); for (i = 0; i < NBKEYS512; ++i) { len = strlen(saved_plain[idx+i]); SHA384_Init(&ctx); SHA384_Update(&ctx, saved_plain[idx+i], len); SHA384_Update(&ctx, sapH_cur_salt->s, sapH_cur_salt->slen); SHA384_Final(tmpBuf, &ctx); memcpy(&keys[i<<7], saved_plain[idx+i], len); memcpy(&keys[(i<<7)+len], tmpBuf, 48); keys[(i<<7)+len+48] = 0x80; offs[i] = len; len += 48; keys[(i<<7)+120] = (len<<3)&0xff; keys[(i<<7)+121] = (len>>5); } for (i = 1; i < sapH_cur_salt->iter; ++i) { uint32_t k; SIMDSHA512body(keys, crypt64, NULL, SSEi_FLAT_IN|SSEi_CRYPT_SHA384); for (k = 0; k < NBKEYS512; ++k) { uint64_t *pcrypt = &crypt64[ ((k/SIMD_COEF_64)*(SIMD_COEF_64*8)) + (k&(SIMD_COEF_64-1))]; uint64_t *Icp64 = (uint64_t *)(&keys[(k<<7)+offs[k]]); for (j = 0; j < 6; ++j) { Icp64[j] = JOHNSWAP64(*pcrypt); pcrypt += SIMD_COEF_64; } } } // now marshal into crypt_out; for (i = 0; i < NBKEYS512; ++i) { uint64_t *Optr64 = (uint64_t*)(crypt_key[idx+i]); uint64_t *Iptr64 = &crypt64[ ((i/SIMD_COEF_64)*(SIMD_COEF_64*8)) + (i&(SIMD_COEF_64-1))]; // we only want 16 bytes, not 48 for (j = 0; j < 2; ++j) { Optr64[j] = JOHNSWAP64(*Iptr64); Iptr64 += SIMD_COEF_64; } } #endif } } static void crypt_all_512(int count) { int idx; #if defined(_OPENMP) #pragma omp parallel for default(none) private(idx) shared(count, sapH_cur_salt, saved_plain, crypt_key) #endif for (idx = 0; idx < count; idx+=NBKEYS512) { SHA512_CTX ctx; uint32_t i; #if !defined SIMD_COEF_64 uint32_t len = strlen(saved_plain[idx]); unsigned char tmp[PLAINTEXT_LENGTH+SHA512_BINARY_SIZE], *cp=&tmp[len]; SHA512_Init(&ctx); SHA512_Update(&ctx, saved_plain[idx], len); SHA512_Update(&ctx, sapH_cur_salt->s, sapH_cur_salt->slen); strcpy((char*)tmp, saved_plain[idx]); len += SHA512_BINARY_SIZE; SHA512_Final(cp, &ctx); for (i = 1; i < sapH_cur_salt->iter; ++i) { SHA512_Init(&ctx); SHA512_Update(&ctx, tmp, len); SHA512_Final(cp, &ctx); } memcpy(crypt_key[idx], cp, BINARY_SIZE); #else unsigned char _IBuf[128*NBKEYS512+MEM_ALIGN_SIMD], *keys, tmpBuf[64], _OBuf[64*NBKEYS512+MEM_ALIGN_SIMD], *crypt; uint64_t j, *crypt64, offs[NBKEYS512]; uint32_t len; keys = (unsigned char*)mem_align(_IBuf, MEM_ALIGN_SIMD); crypt = (unsigned char*)mem_align(_OBuf, MEM_ALIGN_SIMD); crypt64 = (uint64_t*)crypt; memset(keys, 0, 128*NBKEYS512); for (i = 0; i < NBKEYS512; ++i) { len = strlen(saved_plain[idx+i]); SHA512_Init(&ctx); SHA512_Update(&ctx, saved_plain[idx+i], len); SHA512_Update(&ctx, sapH_cur_salt->s, sapH_cur_salt->slen); SHA512_Final(tmpBuf, &ctx); memcpy(&keys[i<<7], saved_plain[idx+i], len); memcpy(&keys[(i<<7)+len], tmpBuf, 64); keys[(i<<7)+len+64] = 0x80; offs[i] = len; len += 64; keys[(i<<7)+120] = (len<<3)&0xff; keys[(i<<7)+121] = (len>>5); } for (i = 1; i < sapH_cur_salt->iter; ++i) { uint32_t k; SIMDSHA512body(keys, crypt64, NULL, SSEi_FLAT_IN); for (k = 0; k < NBKEYS512; ++k) { uint64_t *pcrypt = &crypt64[ ((k/SIMD_COEF_64)*(SIMD_COEF_64*8)) + (k&(SIMD_COEF_64-1))]; uint64_t *Icp64 = (uint64_t *)(&keys[(k<<7)+offs[k]]); for (j = 0; j < 8; ++j) { Icp64[j] = JOHNSWAP64(*pcrypt); pcrypt += SIMD_COEF_64; } } } // now marshal into crypt_out; for (i = 0; i < NBKEYS512; ++i) { uint64_t *Optr64 = (uint64_t*)(crypt_key[idx+i]); uint64_t *Iptr64 = &crypt64[((i/SIMD_COEF_64)*(SIMD_COEF_64*8)) + (i&(SIMD_COEF_64-1))]; // we only want 16 bytes, not 64 for (j = 0; j < 2; ++j) { Optr64[j] = JOHNSWAP64(*Iptr64); Iptr64 += SIMD_COEF_64; } } #endif } } static int crypt_all(int *pcount, struct db_salt *salt) { /* * split logic into 4 separate functions, to make the logic more * simplistic, when we start adding OMP + SIMD code */ switch(sapH_cur_salt->type) { case 1: crypt_all_1(*pcount); break; case 2: crypt_all_256(*pcount); break; case 3: crypt_all_384(*pcount); break; case 4: crypt_all_512(*pcount); break; } return *pcount; } static void *get_binary(char *ciphertext) { static union { unsigned char cp[BINARY_SIZE]; /* only stores part the size of each hash */ uint32_t jnk[BINARY_SIZE/4]; } b; char *cp = ciphertext; memset(b.cp, 0, sizeof(b.cp)); if (!strncasecmp(cp, FORMAT_TAG, FORMAT_TAG_LEN)) { cp += FORMAT_TAG_LEN; } else if (!strncasecmp(cp, FORMAT_TAG256, FORMAT_TAG256_LEN)) { cp += FORMAT_TAG256_LEN; } else if (!strncasecmp(cp, FORMAT_TAG384, FORMAT_TAG384_LEN)) { cp += FORMAT_TAG384_LEN; } else if (!strncasecmp(cp, FORMAT_TAG512, FORMAT_TAG512_LEN)) { cp += FORMAT_TAG512_LEN; } else { fprintf(stderr, "error, bad signature in sap-H format!\n"); error(); } while (*cp != '}') ++cp; ++cp; base64_convert(cp, e_b64_mime, strlen(cp), b.cp, e_b64_raw, sizeof(b.cp), flg_Base64_MIME_TRAIL_EQ, 0); return b.cp; } static void *get_salt(char *ciphertext) { static struct sapH_salt s; char *cp = ciphertext; unsigned char tmp[MAX_BINARY_SIZE+SALT_LENGTH]; int total_len, hash_len = 0; memset(&s, 0, sizeof(s)); if (!strncasecmp(cp, FORMAT_TAG, FORMAT_TAG_LEN)) { s.type = 1; cp += FORMAT_TAG_LEN; hash_len = SHA1_BINARY_SIZE; } else if (!strncasecmp(cp, FORMAT_TAG256, FORMAT_TAG256_LEN)) { s.type = 2; cp += FORMAT_TAG256_LEN; hash_len = SHA256_BINARY_SIZE; } else if (!strncasecmp(cp, FORMAT_TAG384, FORMAT_TAG384_LEN)) { s.type = 3; cp += FORMAT_TAG384_LEN; hash_len = SHA384_BINARY_SIZE; } else if (!strncasecmp(cp, FORMAT_TAG512, FORMAT_TAG512_LEN)) { s.type = 4; cp += FORMAT_TAG512_LEN; hash_len = SHA512_BINARY_SIZE; } else { fprintf(stderr, "error, bad signature in sap-H format!\n"); error(); } sscanf(cp, "%u", &s.iter); while (*cp != '}') ++cp; ++cp; total_len = base64_convert(cp, e_b64_mime, strlen(cp), tmp, e_b64_raw, sizeof(tmp), flg_Base64_MIME_TRAIL_EQ, 0); s.slen = total_len-hash_len; memcpy(s.s, &tmp[hash_len], s.slen); return &s; } static char *split(char *ciphertext, int index, struct fmt_main *self) { /* we 'could' cash switch the SHA/sha and unify case. If they an vary, we will have to. */ return ciphertext; } static int get_hash_0(int index) { return *(uint32_t*)crypt_key[index] & PH_MASK_0; } static int get_hash_1(int index) { return *(uint32_t*)crypt_key[index] & PH_MASK_1; } static int get_hash_2(int index) { return *(uint32_t*)crypt_key[index] & PH_MASK_2; } static int get_hash_3(int index) { return *(uint32_t*)crypt_key[index] & PH_MASK_3; } static int get_hash_4(int index) { return *(uint32_t*)crypt_key[index] & PH_MASK_4; } static int get_hash_5(int index) { return *(uint32_t*)crypt_key[index] & PH_MASK_5; } static int get_hash_6(int index) { return *(uint32_t*)crypt_key[index] & PH_MASK_6; } static int salt_hash(void *salt) { unsigned char *cp = (unsigned char*)salt; unsigned int hash = 5381; unsigned int i; for (i = 0; i < sizeof(struct sapH_salt); i++) hash = ((hash << 5) + hash) ^ cp[i]; return hash & (SALT_HASH_SIZE - 1); } static unsigned int sapH_type(void *salt) { struct sapH_salt *my_salt; my_salt = (struct sapH_salt *)salt; return my_salt->type; } static unsigned int iteration_count(void *salt) { struct sapH_salt *my_salt; my_salt = (struct sapH_salt *)salt; return my_salt->iter; } struct fmt_main fmt_sapH = { { 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_OMP | FMT_CASE | FMT_8_BIT | FMT_UTF8, { "hash type [1:SHA1 2:SHA256 3:SHA384 4:SHA512]", "iteration count", }, { FORMAT_TAG, FORMAT_TAG256, FORMAT_TAG384, FORMAT_TAG512 }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, get_salt, { sapH_type, iteration_count, }, 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 }, salt_hash, NULL, 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 */
GB_unop__identity_int16_int16.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 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__(none)) // op(A') function: GB (_unop_tran__identity_int16_int16) // C type: int16_t // A type: int16_t // cast: int16_t cij = aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int16_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int16_t z = aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ #if 0 GrB_Info GB (_unop_apply__(none)) ( int16_t *Cx, // Cx and Ax may be aliased const int16_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++) { int16_t aij = Ax [p] ; int16_t z = aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int16_t aij = Ax [p] ; int16_t z = aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int16_int16) ( 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
pr29965-3.c
/* PR middle-end/29965 */ /* Test that OpenMP construct bodies which never return don't cause ICEs. */ /* { dg-do compile } */ /* { dg-options "-O2 -fopenmp" } */ extern void baz (void) __attribute__ ((noreturn)); void foo1 (void) { #pragma omp single for (;;); } void bar1 (void) { #pragma omp single baz (); } void foo2 (void) { #pragma omp master for (;;); } void bar2 (void) { #pragma omp master baz (); } void foo3 (void) { #pragma omp ordered for (;;); } void bar3 (void) { #pragma omp ordered baz (); } void foo4 (void) { #pragma omp critical for (;;); } void bar4 (void) { #pragma omp critical baz (); }
NlpGPlacer.h
/** * @file NlpGPlacer.h * @brief The global placement solver with non-linear optimization * @author Keren Zhu * @date 03/29/2020 */ #ifndef IDEAPLACE_NLPGPLACER_H_ #define IDEAPLACE_NLPGPLACER_H_ #include <Eigen/Dense> #ifdef IDEAPLACE_TASKFLOR_FOR_GRAD_OBJ_ #include <taskflow/taskflow.hpp> #endif // IDEAPLACE_TASKFLOR_FOR_GRAD_OBJ #include "db/Database.h" #include "place/different.h" #include "place/differentSecondOrder.hpp" #include "place/nlp/nlpOuterOptm.hpp" #include "place/nlp/nlpInitPlace.hpp" #include "place/nlp/nlpTasks.hpp" #include "place/nlp/nlpTypes.hpp" #include "place/nlp/nlpOptmKernels.hpp" #include "place/nlp/nlpFirstOrderKernel.hpp" #include "place/nlp/nlpSecondOrderKernels.hpp" #include "pinassign/VirtualPinAssigner.h" PROJECT_NAMESPACE_BEGIN namespace nlp { /* The wrapper of settings */ struct nlp_default_hyperparamters { }; struct nlp_default_types { typedef RealType nlp_coordinate_type; typedef RealType nlp_numerical_type; typedef Eigen::Matrix<nlp_numerical_type, Eigen::Dynamic, Eigen::Dynamic> EigenMatrix; typedef Eigen::Matrix<nlp_numerical_type, Eigen::Dynamic, 1> EigenVector; typedef Eigen::Map<EigenVector> EigenMap; typedef Eigen::DiagonalMatrix<nlp_numerical_type, Eigen::Dynamic> EigenDiagonalMatrix; typedef diff::LseHpwlDifferentiable<nlp_numerical_type, nlp_coordinate_type> nlp_hpwl_type; typedef diff::CellPairOverlapPenaltyDifferentiable<nlp_numerical_type, nlp_coordinate_type> nlp_ovl_type; typedef diff::CellOutOfBoundaryPenaltyDifferentiable<nlp_numerical_type, nlp_coordinate_type> nlp_oob_type; typedef diff::AsymmetryDifferentiable<nlp_numerical_type, nlp_coordinate_type> nlp_asym_type; typedef diff::CosineDatapathDifferentiable<nlp_numerical_type, nlp_coordinate_type> nlp_cos_type; typedef diff::PowerVerQuadraticWireLengthDifferentiable<nlp_numerical_type, nlp_coordinate_type> nlp_power_wl_type; typedef diff::CurrentFlowDifferentiable<nlp_numerical_type, nlp_coordinate_type> nlp_crf_type; }; struct nlp_default_zero_order_algorithms { typedef outer_stop_condition::stop_condition_list< outer_stop_condition::stop_after_violate_small, outer_stop_condition::stop_after_num_outer_iterations<1000> > stop_condition_type; typedef init_place::init_random_placement_with_normal_distribution_near_center init_place_type; /* multipliers */ typedef outer_multiplier::init::hard_code_init mult_init_type; typedef outer_multiplier::update::subgradient_normalized_by_init<nlp_default_types::nlp_numerical_type> mult_update_type; //typedef outer_multiplier::update::direct_subgradient mult_update_type; typedef outer_multiplier::mult_const_hpwl_cos_and_penalty_by_type<nlp_default_types::nlp_numerical_type, mult_init_type, mult_update_type> mult_type; }; struct nlp_default_first_order_algorithms { typedef converge::converge_list< converge::converge_grad_norm_by_init<nlp_default_types::nlp_numerical_type>, converge::converge_criteria_max_iter<3000> > converge_type; //typedef optm::first_order::naive_gradient_descent<converge_type> optm_type; typedef optm::first_order::adam<converge_type, nlp_default_types::nlp_numerical_type> optm_type; //typedef optm::first_order::nesterov<converge_type, nlp_default_types::nlp_numerical_type> optm_type; //typedef optm::first_order::conjugate_gradient_wnlib optm_type; /* multipliers */ typedef outer_multiplier::init::init_by_matching_gradient_norm mult_init_type; //typedef outer_multiplier::update::subgradient_normalized_by_init<nlp_default_types::nlp_numerical_type> mult_update_type; typedef outer_multiplier::update::direct_subgradient mult_update_type; typedef outer_multiplier::mult_const_hpwl_cos_and_penalty_by_type<nlp_default_types::nlp_numerical_type, mult_init_type, mult_update_type> mult_type; typedef outer_multiplier::update::match_grad_const_multipliers<nlp_default_types::nlp_numerical_type> mult_adjust_type; /* alpha */ typedef alpha::alpha_hpwl_ovl_oob<nlp_default_types::nlp_numerical_type> alpha_type; typedef alpha::update::alpha_update_list< alpha::update::reciprocal_by_obj<nlp_default_types::nlp_numerical_type, 1>, alpha::update::reciprocal_by_obj<nlp_default_types::nlp_numerical_type, 2>, alpha::update::reciprocal_by_obj<nlp_default_types::nlp_numerical_type, 3> > alpha_update_type; }; template<typename nlp_types> struct nlp_default_second_order_settings { typedef diff::jacobi_hessian_approx_trait<typename nlp_types::nlp_hpwl_type> hpwl_hessian_trait; typedef diff::jacobi_hessian_approx_trait<typename nlp_types::nlp_ovl_type> ovl_hessian_trait; typedef diff::jacobi_hessian_approx_trait<typename nlp_types::nlp_oob_type> oob_hessian_trait; typedef diff::jacobi_hessian_approx_trait<typename nlp_types::nlp_asym_type> asym_hessian_trait; typedef diff::jacobi_hessian_approx_trait<typename nlp_types::nlp_cos_type> cos_hessian_trait; typedef diff::jacobi_hessian_approx_trait<typename nlp_types::nlp_power_wl_type> power_wl_hessian_trait; }; struct nlp_default_second_order_algorithms { typedef converge::converge_list< converge::converge_grad_norm_by_init<nlp_default_types::nlp_numerical_type>, converge::converge_criteria_max_iter<3000> > converge_type; //typedef optm::second_order::naive_gradient_descent<converge_type> optm_type; typedef optm::second_order::adam<converge_type, nlp_default_types::nlp_numerical_type> optm_type; //typedef optm::second_order::nesterov<converge_type, nlp_default_types::nlp_numerical_type> optm_type; //typedef optm::first_order::conjugate_gradient_wnlib optm_type; /* multipliers */ typedef outer_multiplier::init::init_by_matching_gradient_norm mult_init_type; //typedef outer_multiplier::update::subgradient_normalized_by_init<nlp_default_types::nlp_numerical_type> mult_update_type; typedef outer_multiplier::update::direct_subgradient mult_update_type; typedef outer_multiplier::mult_const_hpwl_cos_and_penalty_by_type<nlp_default_types::nlp_numerical_type, mult_init_type, mult_update_type> mult_type; typedef outer_multiplier::update::match_grad_const_multipliers<nlp_default_types::nlp_numerical_type> mult_adjust_type; /* alpha */ typedef alpha::alpha_hpwl_ovl_oob<nlp_default_types::nlp_numerical_type> alpha_type; typedef alpha::update::alpha_update_list< alpha::update::reciprocal_by_obj<nlp_default_types::nlp_numerical_type, 1>, alpha::update::reciprocal_by_obj<nlp_default_types::nlp_numerical_type, 2> > alpha_update_type; }; struct nlp_default_settings { typedef nlp_default_zero_order_algorithms nlp_zero_order_algorithms_type; typedef nlp_default_first_order_algorithms nlp_first_order_algorithms_type; typedef nlp_default_hyperparamters nlp_hyperparamters_type; typedef nlp_default_types nlp_types_type; typedef nlp_default_second_order_settings<nlp_types_type> nlp_second_order_setting_type; typedef nlp_default_second_order_algorithms nlp_second_order_algorithms_type; }; }// namespace nlp /// @brief non-linear programming-based analog global placement template<typename nlp_settings> class NlpGPlacerBase { public: typedef typename nlp_settings::nlp_types_type nlp_types; typedef typename nlp_settings::nlp_zero_order_algorithms_type nlp_zero_order_algorithms; typedef typename nlp_settings::nlp_hyperparamters_type nlp_hyperparamters; typedef typename nlp_types::EigenMatrix EigenMatrix; typedef typename nlp_types::EigenVector EigenVector; typedef typename nlp_types::EigenMap EigenMap; typedef typename nlp_types::nlp_coordinate_type nlp_coordinate_type; typedef typename nlp_types::nlp_numerical_type nlp_numerical_type; typedef typename nlp_types::nlp_hpwl_type nlp_hpwl_type; typedef typename nlp_types::nlp_ovl_type nlp_ovl_type; typedef typename nlp_types::nlp_oob_type nlp_oob_type; typedef typename nlp_types::nlp_asym_type nlp_asym_type; typedef typename nlp_types::nlp_cos_type nlp_cos_type; typedef typename nlp_types::nlp_power_wl_type nlp_power_wl_type; typedef typename nlp_types::nlp_crf_type nlp_crf_type; /* algorithms */ typedef typename nlp_zero_order_algorithms::stop_condition_type stop_condition_type; typedef nlp::outer_stop_condition::stop_condition_trait<stop_condition_type> stop_condition_trait; template<typename _T> friend struct nlp::outer_stop_condition::stop_condition_trait; typedef typename nlp_zero_order_algorithms::init_place_type init_placement_type; typedef nlp::init_place::init_place_trait<init_placement_type> init_place_trait; friend init_place_trait; typedef typename nlp_zero_order_algorithms::mult_init_type mult_init_type; typedef nlp::outer_multiplier::init::multiplier_init_trait<mult_init_type> mult_init_trait; friend mult_init_trait; typedef typename nlp_zero_order_algorithms::mult_update_type mult_update_type; typedef nlp::outer_multiplier::update::multiplier_update_trait<mult_update_type> mult_update_trait; friend mult_update_trait; typedef typename nlp_zero_order_algorithms::mult_type mult_type; typedef nlp::outer_multiplier::multiplier_trait<mult_type> mult_trait; friend mult_trait; public: explicit NlpGPlacerBase(Database &db) : _db(db) {} IntType solve(); protected: void assignIoPins(); /* calculating obj */ void calcObj() { _wrapObjAllTask.run(); } /* Init functions */ virtual void initProblem(); void initHyperParams(); void initBoundaryParams(); void initVariables(); void initPlace(); void initOperators(); void initOptimizationKernelMembers(); /* Output functions */ void writeOut(); /* Util functions */ IndexType plIdx(IndexType cellIdx, Orient2DType orient); void alignToSym(); /* construct tasks */ virtual void constructTasks(); // Obj-related void constructObjTasks(); void constructObjectiveCalculationTasks(); void constructSumObjTasks(); #ifdef DEBUG_SINGLE_THREAD_GP void constructWrapObjTask(); #endif /* Optimization kernel */ virtual void optimize(); /* build the computational graph */ /* Debugging function */ #ifdef DEBUG_GR #ifdef DEBUG_DRAW void drawCurrentLayout(const std::string &name); #endif #endif protected: Database &_db; ///< The placement engine database /* NLP problem parameters */ IndexType _numCells; ///< The number of cells RealType _alpha; ///< Used in LSE approximation hyperparameter Box<nlp_coordinate_type> _boundary; ///< The boundary constraint for the placement nlp_coordinate_type _scale = 0.01; /// The scale ratio between float optimization kernel coordinate and placement database coordinate unit nlp_coordinate_type _totalCellArea = 0; ///< The total cell area of the problem nlp_coordinate_type _defaultSymAxis = 0.0; ///< The default symmetric axis IndexType _numVariables = 0; ///< The number of variables /* Optimization internal results */ nlp_numerical_type _objHpwl = 0.0; ///< The current value for hpwl nlp_numerical_type _objOvl = 0.0; ///< The current value for overlapping penalty nlp_numerical_type _objOob = 0.0; ///< The current value for out of boundary penalty nlp_numerical_type _objAsym = 0.0; ///< The current value for asymmetry penalty nlp_numerical_type _objCos = 0.0; ///< The current value for the cosine signal path penalty nlp_numerical_type _objPowerWl = 0.0; ///< power wire length nlp_numerical_type _objCrf = 0.0; ///< Current flow nlp_numerical_type _obj = 0.0; ///< The current value for the total objective penalty nlp_numerical_type _objHpwlRaw = 0.0; ///< The current value for hpwl nlp_numerical_type _objOvlRaw = 0.0; ///< The current value for overlapping penalty nlp_numerical_type _objOobRaw = 0.0; ///< The current value for out of boundary penalty nlp_numerical_type _objAsymRaw = 0.0; ///< The current value for asymmetry penalty nlp_numerical_type _objCosRaw = 0.0; ///< The current value for the cosine signal path penalty nlp_numerical_type _objPowrWlRaw = 0.0; ///< Power wire length nlp_numerical_type _objCrfRaw = 0.0; ///< Current flow /* NLP optimization kernel memebers */ stop_condition_type _stopCondition; /* Optimization data */ EigenVector _pl; ///< The placement solutions /* Tasks */ // Evaluating objectives std::vector<nt::Task<nt::EvaObjTask<nlp_numerical_type>>> _evaHpwlTasks; ///< The tasks for evaluating hpwl objectives std::vector<nt::Task<nt::EvaObjTask<nlp_numerical_type>>> _evaOvlTasks; ///< The tasks for evaluating overlap objectives std::vector<nt::Task<nt::EvaObjTask<nlp_numerical_type>>> _evaOobTasks; ///< The tasks for evaluating out of boundary objectives std::vector<nt::Task<nt::EvaObjTask<nlp_numerical_type>>> _evaAsymTasks; ///< The tasks for evaluating asymmetry objectives std::vector<nt::Task<nt::EvaObjTask<nlp_numerical_type>>> _evaCosTasks; ///< The tasks for evaluating signal path objectives std::vector<nt::Task<nt::EvaObjTask<nlp_numerical_type>>> _evaPowerWlTasks; std::vector<nt::Task<nt::EvaObjTask<nlp_numerical_type>>> _evaCrfTasks; ///< The tasks for evaluating current flow objectives // Sum the objectives nt::Task<nt::FuncTask> _sumObjHpwlTask; ///< The task for summing hpwl objective nt::Task<nt::FuncTask> _sumObjOvlTask; ///< The task for summing the overlapping objective nt::Task<nt::FuncTask> _sumObjOobTask; ///< The task for summing the out of boundary objective nt::Task<nt::FuncTask> _sumObjAsymTask; ///< The task for summing the asymmetry objective nt::Task<nt::FuncTask> _sumObjCosTask; ///< The task for summing the cosine signal path objective nt::Task<nt::FuncTask> _sumObjPowerWlTask; ///< The task for summing the cosine signal path objective nt::Task<nt::FuncTask> _sumObjCrfTask; ///< The task for summing the current flow objective nt::Task<nt::FuncTask> _sumObjAllTask; ///< The task for summing the different objectives together // Wrapper tasks for debugging nt::Task<nt::FuncTask> _wrapObjHpwlTask; ///< The task for wrap the objective nt::Task<nt::FuncTask> _wrapObjOvlTask; nt::Task<nt::FuncTask> _wrapObjOobTask; nt::Task<nt::FuncTask> _wrapObjAsymTask; nt::Task<nt::FuncTask> _wrapObjCosTask; nt::Task<nt::FuncTask> _wrapObjPowerWlTask; nt::Task<nt::FuncTask> _wrapObjCrfTask; ///< The wrapper for caculating the current flow objective nt::Task<nt::FuncTask> _wrapObjAllTask; /* Operators */ std::vector<nlp_hpwl_type> _hpwlOps; ///< The HPWL cost std::vector<nlp_ovl_type> _ovlOps; ///< The cell pair overlapping penalty operators std::vector<nlp_oob_type> _oobOps; ///< The cell out of boundary penalty operators std::vector<nlp_asym_type> _asymOps; ///< The asymmetric penalty operators std::vector<nlp_cos_type> _cosOps; ///< The signal flow operators std::vector<nlp_power_wl_type> _powerWlOps; std::vector<nlp_crf_type> _crfOps; ///< The current flow operators /* run time */ std::unique_ptr<::klib::StopWatch> _calcObjStopWatch; }; template<typename nlp_settings> inline IndexType NlpGPlacerBase<nlp_settings>::plIdx(IndexType cellIdx, Orient2DType orient) { if (orient == Orient2DType::HORIZONTAL) { return cellIdx; } else if (orient == Orient2DType::VERTICAL) { return cellIdx + _numCells; } else { #ifdef MULTI_SYM_GROUP return cellIdx + 2 * _numCells; // here cell index representing the idx of sym grp #else return 2 * _numCells; #endif } } /// @brief first-order optimization template<typename nlp_settings> class NlpGPlacerFirstOrder : public NlpGPlacerBase<nlp_settings> { public: typedef NlpGPlacerBase<nlp_settings> base_type; typedef typename base_type::EigenVector EigenVector; typedef typename base_type::nlp_hpwl_type nlp_hpwl_type; typedef typename base_type::nlp_ovl_type nlp_ovl_type; typedef typename base_type::nlp_oob_type nlp_oob_type; typedef typename base_type::nlp_asym_type nlp_asym_type; typedef typename base_type::nlp_cos_type nlp_cos_type; typedef typename base_type::nlp_power_wl_type nlp_power_wl_type; typedef typename base_type::nlp_crf_type nlp_crf_type; typedef typename nlp_settings::nlp_first_order_algorithms_type nlp_first_order_algorithms; typedef typename nlp_first_order_algorithms::converge_type converge_type; typedef typename nlp::converge::converge_criteria_trait<converge_type> converge_trait; typedef typename nlp_first_order_algorithms::optm_type optm_type; typedef typename nlp::optm::optm_trait<optm_type> optm_trait; friend converge_type; template<typename converge_criteria_type> friend struct nlp::converge::converge_criteria_trait; friend optm_type; friend optm_trait; typedef typename nlp_settings::nlp_first_order_algorithms_type::mult_init_type mult_init_type; typedef nlp::outer_multiplier::init::multiplier_init_trait<mult_init_type> mult_init_trait; friend mult_init_trait; typedef typename nlp_settings::nlp_first_order_algorithms_type::mult_update_type mult_update_type; typedef nlp::outer_multiplier::update::multiplier_update_trait<mult_update_type> mult_update_trait; friend mult_update_trait; typedef typename nlp_settings::nlp_first_order_algorithms_type::mult_type mult_type; typedef nlp::outer_multiplier::multiplier_trait<mult_type> mult_trait; friend mult_trait; typedef typename nlp_settings::nlp_first_order_algorithms_type::mult_adjust_type mult_adjust_type; typedef nlp::outer_multiplier::update::multiplier_update_trait<mult_adjust_type> mult_adjust_trait; friend mult_adjust_trait; /* updating alpha parameters */ typedef typename nlp_settings::nlp_first_order_algorithms_type::alpha_type alpha_type; typedef nlp::alpha::alpha_trait<alpha_type> alpha_trait; template<typename T> friend struct nlp::alpha::alpha_trait; typedef typename nlp_settings::nlp_first_order_algorithms_type::alpha_update_type alpha_update_type; typedef nlp::alpha::update::alpha_update_trait<alpha_update_type> alpha_update_trait; template<typename T> friend struct nlp::alpha::update::alpha_update_trait; NlpGPlacerFirstOrder(Database &db) : NlpGPlacerBase<nlp_settings>(db) {} void writeoutCsv() { std::string ver1f = "ver1.csv"; std::string ver2f = "ver2.csv"; std::ofstream ver1(ver1f.c_str()); std::ofstream ver2(ver2f.c_str()); ver1 << "x y val\n"; ver2 << "x y val\n"; for (RealType x = -8; x < 8; x+=(16.0/300)) { for (RealType y = -8; y < 8; y+=(16.0/300)) { this->_pl(this->plIdx(0, Orient2DType::HORIZONTAL)) = x; this->_pl(this->plIdx(0, Orient2DType::VERTICAL)) = y; this->_wrapObjAllTask.run(); auto obj = this->_obj; ver1 << x << " "<< y << " " << obj << "\n"; } } auto getLambda = [&](){ return 1.0; }; for (auto &op : this->_hpwlOps) { op._getLambdaFunc = [&](){ return 1.0; }; } for (auto &op : this->_cosOps) { op._getLambdaFunc = [&](){ return 1.0; }; } for (auto &op : this->_ovlOps) { op._getLambdaFunc = [&](){ return 1.0; }; } for (auto &op : this->_oobOps) { op._getLambdaFunc = [&](){ return 1.0; }; } for (auto &op : this->_asymOps) { op._getLambdaFunc = [&](){ return 1.0; }; } for (auto &op : this->_powerWlOps) { op._getLambdaFunc = [&](){ return 1.0; }; } for (auto &op : this->_crfOps) { op._getLambdaFunc = [&](){ return 1.0; }; } for (RealType x = -8; x < 8; x+=(16.0/300)) { for (RealType y = -8; y < 8; y+=(16.0/300)) { this->_pl(this->plIdx(0, Orient2DType::HORIZONTAL)) = x; this->_pl(this->plIdx(0, Orient2DType::VERTICAL)) = y; this->_wrapObjAllTask.run(); auto obj = this->_obj; ver2 << x << " "<< y << " " << obj << "\n"; } } } protected: /* calculating gradient */ void calcGrad() { _wrapCalcGradTask.run(); } /* Init */ virtual void initProblem() override; void initFirstOrderGrad(); /* Construct tasks */ virtual void constructTasks() override; void constructFirstOrderTasks(); void constructCalcPartialsTasks(); void constructUpdatePartialsTasks(); void constructClearGradTasks(); void constructSumGradTask(); void constructWrapCalcGradTask(); /* optimization */ virtual void optimize() override; /* Build the computational graph */ #ifdef IDEAPLACE_TASKFLOR_FOR_GRAD_OBJ_ void regCalcHpwlGradTaskFlow(tf::Taskflow &tfFlow); void regCalcOvlGradTaskFlow(tf::Taskflow &tfFlow); void regCalcOobGradTaskFlow(tf::Taskflow &tfFlow); void regCalcAsymGradTaskFlow(tf::Taskflow &tfFlow); void regCalcCosGradTaskFlow(tf::Taskflow &tfFlow); void regCalcAllGradTaskFlow(tf::Taskflow &tfFlow); void regCalcGradForLoop(tf::Taskflow &tfFlow); #endif protected: /* Optimization data */ EigenVector _grad; ///< The first order graident EigenVector _gradHpwl; ///< The first order gradient of hpwl objective EigenVector _gradOvl; ///< The first order gradient of overlapping objective EigenVector _gradOob; ///< The first order gradient of out of boundary objective EigenVector _gradAsym; ///< The first order gradient of asymmetry objective EigenVector _gradCos; ///< The first order gradient of cosine signal path objective EigenVector _gradPowerWl; EigenVector _gradCrf; /* Tasks */ // Calculate the partials std::vector<nt::Task<nt::CalculateOperatorPartialTask<nlp_hpwl_type, EigenVector>>> _calcHpwlPartialTasks; std::vector<nt::Task<nt::CalculateOperatorPartialTask<nlp_ovl_type, EigenVector>>> _calcOvlPartialTasks; std::vector<nt::Task<nt::CalculateOperatorPartialTask<nlp_oob_type, EigenVector>>> _calcOobPartialTasks; std::vector<nt::Task<nt::CalculateOperatorPartialTask<nlp_asym_type, EigenVector>>> _calcAsymPartialTasks; std::vector<nt::Task<nt::CalculateOperatorPartialTask<nlp_cos_type, EigenVector>>> _calcCosPartialTasks; std::vector<nt::Task<nt::CalculateOperatorPartialTask<nlp_power_wl_type, EigenVector>>> _calcPowerWlPartialTasks; std::vector<nt::Task<nt::CalculateOperatorPartialTask<nlp_crf_type, EigenVector>>> _calcCrfPartialTasks; // Update the partials std::vector<nt::Task<nt::UpdateGradientFromPartialTask<nlp_hpwl_type, EigenVector>>> _updateHpwlPartialTasks; std::vector<nt::Task<nt::UpdateGradientFromPartialTask<nlp_ovl_type, EigenVector>>> _updateOvlPartialTasks; std::vector<nt::Task<nt::UpdateGradientFromPartialTask<nlp_oob_type, EigenVector>>> _updateOobPartialTasks; std::vector<nt::Task<nt::UpdateGradientFromPartialTask<nlp_asym_type, EigenVector>>> _updateAsymPartialTasks; std::vector<nt::Task<nt::UpdateGradientFromPartialTask<nlp_cos_type, EigenVector>>> _updateCosPartialTasks; std::vector<nt::Task<nt::UpdateGradientFromPartialTask<nlp_power_wl_type, EigenVector>>> _updatePowerWlPartialTasks; std::vector<nt::Task<nt::UpdateGradientFromPartialTask<nlp_crf_type, EigenVector>>> _updateCrfPartialTasks; // Clear the gradient. Use to clear the _gradxxx records. Needs to call before updating the partials nt::Task<nt::FuncTask> _clearGradTask; //FIXME: not used right noe nt::Task<nt::FuncTask> _clearHpwlGradTask; nt::Task<nt::FuncTask> _clearOvlGradTask; nt::Task<nt::FuncTask> _clearOobGradTask; nt::Task<nt::FuncTask> _clearAsymGradTask; nt::Task<nt::FuncTask> _clearCosGradTask; nt::Task<nt::FuncTask> _clearPowerWlGradTask; nt::Task<nt::FuncTask> _clearCrfGradTask; // Sum the _grad from individual nt::Task<nt::FuncTask> _sumGradTask; nt::Task<nt::FuncTask> _sumHpwlGradTask; nt::Task<nt::FuncTask> _sumOvlGradTask; nt::Task<nt::FuncTask> _sumOobGradTask; nt::Task<nt::FuncTask> _sumAsymGradTask; nt::Task<nt::FuncTask> _sumCosGradTask; nt::Task<nt::FuncTask> _sumPowerWlTaskGradTask; nt::Task<nt::FuncTask> _sumCrfGradTask; // all the grads has been calculated but have not updated nt::Task<nt::FuncTask> _wrapCalcGradTask; ///< calculating the gradient and sum them /* run time */ std::unique_ptr<::klib::StopWatch> _calcGradStopWatch; std::unique_ptr<::klib::StopWatch> _optimizerKernelStopWatch; }; //// @brief some helper function for NlpGPlacerSecondOrder namespace _nlp_second_order_details { template<typename nlp_settings, BoolType is_diagonal> struct is_diagonal_select {}; template<typename nlp_settings> struct is_diagonal_select<nlp_settings, true> { typedef typename nlp_settings::nlp_types_type::EigenMatrix matrix_type; static void resize(matrix_type &matrix, IntType size) { matrix.resize(size, size); } static decltype(auto) inverse(matrix_type &matrix) { return matrix.diagonal().cwiseInverse().asDiagonal(); } }; template<typename nlp_settings> struct is_diagonal_select<nlp_settings, false> { typedef typename nlp_settings::nlp_types_type::EigenMatrix matrix_type; static void resize(matrix_type &matrix, IntType size) { matrix.resize(size, size); } static decltype(auto) inverse(matrix_type &matrix) { Assert(false); return matrix.diagonal().cwiseInverse(); } }; template<typename hessian_target_type> struct update_hessian { hessian_target_type &target; }; }; /// @brief first-order optimization template<typename nlp_settings> class NlpGPlacerSecondOrder : public NlpGPlacerFirstOrder<nlp_settings> { public: typedef typename NlpGPlacerFirstOrder<nlp_settings>::base_type base_type; typedef NlpGPlacerFirstOrder<nlp_settings> first_order_type; typedef typename first_order_type::nlp_numerical_type nlp_numerical_type; typedef typename first_order_type::nlp_coordinate_type nlp_coordinate_type; typedef typename nlp_settings::nlp_second_order_setting_type second_order_setting_type; typedef typename first_order_type::EigenMatrix EigenMatrix; typedef typename first_order_type::nlp_hpwl_type nlp_hpwl_type; typedef typename first_order_type::nlp_ovl_type nlp_ovl_type; typedef typename first_order_type::nlp_oob_type nlp_oob_type; typedef typename first_order_type::nlp_asym_type nlp_asym_type; typedef typename first_order_type::nlp_cos_type nlp_cos_type; typedef typename first_order_type::nlp_power_wl_type nlp_power_wl_type; typedef typename second_order_setting_type::hpwl_hessian_trait hpwl_hessian_trait; typedef typename second_order_setting_type::ovl_hessian_trait ovl_hessian_trait; typedef typename second_order_setting_type::oob_hessian_trait oob_hessian_trait; typedef typename second_order_setting_type::asym_hessian_trait asym_hessian_trait; typedef typename second_order_setting_type::cos_hessian_trait cos_hessian_trait; typedef typename second_order_setting_type::power_wl_hessian_trait power_wl_hessian_trait; /* figure out the types for storing the hessian */ // Determine whether the operators are return a diagonal hessian constexpr static BoolType isHpwlHessianDiagonal = diff::is_diagnol_matrix<hpwl_hessian_trait>::value; constexpr static BoolType isOvlHessianDiagonal = diff::is_diagnol_matrix<ovl_hessian_trait>::value; constexpr static BoolType isOobHessianDiagonal = diff::is_diagnol_matrix<oob_hessian_trait>::value; constexpr static BoolType isAsymHessianDiagonal = diff::is_diagnol_matrix<asym_hessian_trait>::value; constexpr static BoolType isCosHessianDiagonal = diff::is_diagnol_matrix<cos_hessian_trait>::value; constexpr static BoolType isPowerWlHessianDiagonal = diff::is_diagnol_matrix<power_wl_hessian_trait>::value; constexpr static BoolType isHessianDiagonal = isHpwlHessianDiagonal and isOvlHessianDiagonal and isOobHessianDiagonal and isAsymHessianDiagonal and isCosHessianDiagonal and isPowerWlHessianDiagonal; // define the supporting trait typedef _nlp_second_order_details::is_diagonal_select<nlp_settings, isHpwlHessianDiagonal> hpwl_hessian_diagonal_selector; friend hpwl_hessian_diagonal_selector; typedef _nlp_second_order_details::is_diagonal_select<nlp_settings, isOvlHessianDiagonal> ovl_hessian_diagonal_selector; friend ovl_hessian_diagonal_selector; typedef _nlp_second_order_details::is_diagonal_select<nlp_settings, isOobHessianDiagonal> oob_hessian_diagonal_selector; friend oob_hessian_diagonal_selector; typedef _nlp_second_order_details::is_diagonal_select<nlp_settings, isAsymHessianDiagonal> asym_hessian_diagonal_selector; friend asym_hessian_diagonal_selector; typedef _nlp_second_order_details::is_diagonal_select<nlp_settings, isCosHessianDiagonal> cos_hessian_diagonal_selector; friend cos_hessian_diagonal_selector; typedef _nlp_second_order_details::is_diagonal_select<nlp_settings, isPowerWlHessianDiagonal> power_wl_hessian_diagonal_selector; friend cos_hessian_diagonal_selector; typedef _nlp_second_order_details::is_diagonal_select<nlp_settings, isHessianDiagonal> hessian_diagonal_selector; friend hessian_diagonal_selector; typedef typename hpwl_hessian_diagonal_selector::matrix_type hpwl_hessian_matrix; typedef typename ovl_hessian_diagonal_selector::matrix_type ovl_hessian_matrix; typedef typename oob_hessian_diagonal_selector::matrix_type oob_hessian_matrix; typedef typename asym_hessian_diagonal_selector::matrix_type asym_hessian_matrix; typedef typename cos_hessian_diagonal_selector::matrix_type cos_hessian_matrix; typedef typename power_wl_hessian_diagonal_selector::matrix_type power_wl_hessian_matrix; typedef typename hessian_diagonal_selector::matrix_type hessian_matrix; /* define the algorithms */ typedef typename nlp_settings::nlp_second_order_algorithms_type nlp_second_order_algorithms; typedef typename nlp_second_order_algorithms::converge_type converge_type; typedef typename nlp::converge::converge_criteria_trait<converge_type> converge_trait; typedef typename nlp_second_order_algorithms::optm_type optm_type; typedef typename nlp::optm::optm_trait<optm_type> optm_trait; friend converge_type; template<typename converge_criteria_type> friend struct nlp::converge::converge_criteria_trait; friend optm_type; friend optm_trait; typedef typename nlp_settings::nlp_second_order_algorithms_type::mult_init_type mult_init_type; typedef nlp::outer_multiplier::init::multiplier_init_trait<mult_init_type> mult_init_trait; friend mult_init_trait; typedef typename nlp_settings::nlp_second_order_algorithms_type::mult_update_type mult_update_type; typedef nlp::outer_multiplier::update::multiplier_update_trait<mult_update_type> mult_update_trait; friend mult_update_trait; typedef typename nlp_settings::nlp_second_order_algorithms_type::mult_type mult_type; typedef nlp::outer_multiplier::multiplier_trait<mult_type> mult_trait; friend mult_trait; typedef typename nlp_settings::nlp_second_order_algorithms_type::mult_adjust_type mult_adjust_type; typedef nlp::outer_multiplier::update::multiplier_update_trait<mult_adjust_type> mult_adjust_trait; friend mult_adjust_trait; /* updating alpha parameters */ typedef typename nlp_settings::nlp_second_order_algorithms_type::alpha_type alpha_type; typedef nlp::alpha::alpha_trait<alpha_type> alpha_trait; template<typename T> friend struct nlp::alpha::alpha_trait; typedef typename nlp_settings::nlp_second_order_algorithms_type::alpha_update_type alpha_update_type; typedef nlp::alpha::update::alpha_update_trait<alpha_update_type> alpha_update_trait; template<typename T> friend struct nlp::alpha::update::alpha_update_trait; static constexpr nlp_numerical_type hessianMinBound = 0.01; static constexpr nlp_numerical_type hessianMaxBound = 10; NlpGPlacerSecondOrder(Database &db) : NlpGPlacerFirstOrder<nlp_settings>(db) {} public: decltype(auto) inverseHessian() { return hessian_diagonal_selector::inverse(_hessian); } void calcHessian() { _clearHessian(); _calcAllHessians(); _updateAllHessian(); clipHessian(); } protected: virtual void initProblem() override { first_order_type::initProblem(); initSecondOrder(); } void initSecondOrder(); /* Construct tasks */ virtual void optimize() override { WATCH_QUICK_START(); // setting up the multipliers this->assignIoPins(); this->_wrapObjAllTask.run(); this->_wrapCalcGradTask.run(); calcHessian(); optm_type optm; mult_type multiplier = mult_trait::construct(*this); mult_trait::init(*this, multiplier); mult_trait::recordRaw(*this, multiplier); mult_adjust_type multAdjuster = mult_adjust_trait::construct(*this, multiplier); mult_adjust_trait::init(*this, multiplier, multAdjuster); alpha_type alpha = alpha_trait::construct(*this); alpha_trait::init(*this, alpha); alpha_update_type alphaUpdate = alpha_update_trait::construct(*this, alpha); alpha_update_trait::init(*this, alpha, alphaUpdate); DBG("np \n"); std::cout<<"nlp address " <<this <<std::endl; IntType iter = 0; do { std::string debugGdsFilename = "./debug/"; debugGdsFilename += "gp_iter_" + std::to_string(iter)+".gds"; DBG("iter %d \n", iter); optm_trait::optimize(*this, optm); mult_trait::update(*this, multiplier); mult_trait::recordRaw(*this, multiplier); mult_adjust_trait::update(*this, multiplier, multAdjuster); alpha_update_trait::update(*this, alpha, alphaUpdate); this->assignIoPins(); DBG("obj %f hpwl %f ovl %f oob %f asym %f cos %f \n", this->_obj, this->_objHpwl, this->_objOvl, this->_objOob, this->_objAsym, this->_objCos); ++iter; } while (not base_type::stop_condition_trait::stopPlaceCondition(*this, this->_stopCondition)); auto end = WATCH_QUICK_END(); //std::cout<<"grad"<<"\n"<< _grad <<std::endl; std::cout<<"time "<< end / 1000 <<" ms" <<std::endl; this->writeOut(); } private: void constructCalcHessianTasks() { using hpwl = nt::CalculateOperatorHessianTask<nlp_hpwl_type, hpwl_hessian_trait, EigenMatrix, hpwl_hessian_matrix>; using ovl = nt::CalculateOperatorHessianTask<nlp_ovl_type, ovl_hessian_trait, EigenMatrix, ovl_hessian_matrix>; using oob = nt::CalculateOperatorHessianTask<nlp_oob_type, oob_hessian_trait, EigenMatrix, oob_hessian_matrix>; using asym = nt::CalculateOperatorHessianTask<nlp_asym_type, asym_hessian_trait, EigenMatrix, asym_hessian_matrix>; using cos = nt::CalculateOperatorHessianTask<nlp_cos_type, cos_hessian_trait, EigenMatrix, cos_hessian_matrix>; using pwl = nt::CalculateOperatorHessianTask<nlp_power_wl_type, power_wl_hessian_trait, EigenMatrix, power_wl_hessian_matrix>; auto getIdxFunc = [&](IndexType cellIdx, Orient2DType orient) { return this->plIdx(cellIdx, orient); }; // wrapper the convert cell idx to pl idx for (IndexType i = 0; i < this->_hpwlOps.size(); ++i) { _calcHpwlHessianTasks.emplace_back(hpwl(&this->_hpwlOps[i], &_hessianHpwl, getIdxFunc)); } for (auto &op : this->_ovlOps) { _calcOvlHessianTasks.emplace_back(ovl(&op, &_hessianOvl, getIdxFunc)); } for (auto &op : this->_oobOps) { _calcOobHessianTasks.emplace_back(oob(&op, &_hessianOob, getIdxFunc)); } for (auto &op : this->_asymOps) { _calcAsymHessianTasks.emplace_back(asym(&op, &_hessianAsym, getIdxFunc)); } for (auto &op : this->_cosOps) { _calcCosHessianTasks.emplace_back(cos(&op, &_hessianCos, getIdxFunc)); } for (auto &op : this->_powerWlOps) { _calcPowerWlHessianTasks.emplace_back(pwl(&op, &_hessianPowerWl, getIdxFunc)); } } void _clearHessian() { _hessian.setZero(); _hessianHpwl.setZero(); _hessianOvl.setZero(); _hessianOob.setZero(); _hessianAsym.setZero(); _hessianCos.setZero(); _hessianPowerWl.setZero(); } void _calcAllHessians() { #pragma omp parallel for schedule(static) for (IndexType i = 0; i < _calcHpwlHessianTasks.size(); ++i) { _calcHpwlHessianTasks[i].calc(); } #pragma omp parallel for schedule(static) for (IndexType i = 0; i < _calcOvlHessianTasks.size(); ++i) { _calcOvlHessianTasks[i].calc(); } #pragma omp parallel for schedule(static) for (IndexType i = 0; i < _calcOobHessianTasks.size(); ++i) { _calcOobHessianTasks[i].calc(); } #pragma omp parallel for schedule(static) for (IndexType i = 0; i < _calcAsymHessianTasks.size(); ++i) { _calcAsymHessianTasks[i].calc(); } #pragma omp parallel for schedule(static) for (IndexType i = 0; i < _calcCosHessianTasks.size(); ++i) { _calcCosHessianTasks[i].calc(); } #pragma omp parallel for schedule(static) for (IndexType i = 0; i < _calcPowerWlHessianTasks.size(); ++i) { _calcPowerWlHessianTasks[i].calc(); } } void _updateAllHessian() { #pragma omp parallel for schedule(static) for (IndexType i = 0; i < 6; ++i) { if (i == 0) { for (auto & calc : _calcHpwlHessianTasks) { calc.update(); } } else if (i == 1) { for (auto & calc : _calcOvlHessianTasks) { calc.update(); } } else if (i == 2) { for (auto & calc : _calcOobHessianTasks) { calc.update(); } } else if (i == 3) { for (auto & calc : _calcAsymHessianTasks) { calc.update(); } } else if (i == 4) { for (auto & calc : _calcCosHessianTasks) { calc.update(); } } else { for (auto & calc : _calcPowerWlHessianTasks) { calc.update(); } } } _hessian = _hessianHpwl + _hessianOvl + _hessianOob + _hessianAsym + _hessianCos + _hessianPowerWl; } void clipHessian() { _hessian = _hessian.cwiseMin(hessianMinBound).cwiseMax(hessianMaxBound); } virtual void constructTasks() override { first_order_type::constructTasks(); this->constructCalcHessianTasks(); } protected: hessian_matrix _hessian; ///< The hessian for the objective function hpwl_hessian_matrix _hessianHpwl; ///< The hessian for the hpwl function ovl_hessian_matrix _hessianOvl; ///< The hessian for the overlapping function oob_hessian_matrix _hessianOob; ///< The hessian for the out of boundary function asym_hessian_matrix _hessianAsym; ///< The hessian for the asymmetry function cos_hessian_matrix _hessianCos; ///< The hessian for the signal path function power_wl_hessian_matrix _hessianPowerWl; /* Tasks */ std::vector<nt::CalculateOperatorHessianTask<nlp_hpwl_type, hpwl_hessian_trait, EigenMatrix, hpwl_hessian_matrix>> _calcHpwlHessianTasks; ///< calculate and update the hessian std::vector<nt::CalculateOperatorHessianTask<nlp_ovl_type, ovl_hessian_trait, EigenMatrix, ovl_hessian_matrix>> _calcOvlHessianTasks; ///< calculate and update the hessian std::vector<nt::CalculateOperatorHessianTask<nlp_oob_type, oob_hessian_trait, EigenMatrix, oob_hessian_matrix>> _calcOobHessianTasks; ///< calculate and update the hessian std::vector<nt::CalculateOperatorHessianTask<nlp_asym_type, asym_hessian_trait, EigenMatrix, asym_hessian_matrix>> _calcAsymHessianTasks; ///< calculate and update the hessian std::vector<nt::CalculateOperatorHessianTask<nlp_cos_type, cos_hessian_trait, EigenMatrix, cos_hessian_matrix>> _calcCosHessianTasks; ///< calculate and update the hessian std::vector<nt::CalculateOperatorHessianTask<nlp_power_wl_type, power_wl_hessian_trait, EigenMatrix, power_wl_hessian_matrix>> _calcPowerWlHessianTasks; ///< calculate and update the hessian }; template<typename nlp_settings> inline void NlpGPlacerSecondOrder<nlp_settings>::initSecondOrder() { const IntType size = this->_numVariables; DBG("resize hessian to %d \n", size); hpwl_hessian_diagonal_selector::resize(_hessianHpwl, size); ovl_hessian_diagonal_selector::resize(_hessianOvl, size); oob_hessian_diagonal_selector::resize(_hessianOob, size); asym_hessian_diagonal_selector::resize(_hessianAsym, size); cos_hessian_diagonal_selector::resize(_hessianCos, size); power_wl_hessian_diagonal_selector::resize(_hessianPowerWl , size); } PROJECT_NAMESPACE_END #endif //IDEAPLACE_NLPGPLACER_H_
LinearAlgebra.h
namespace tom { /** Devide the given `matrix` by its element-sum, i.e., normalize the matrix to have an element-sum of one, and return the element-sum. */ template<typename T> double normalize(const DenseBase<T> &matrix) { double mat_sum = matrix.sum(); const_cast< DenseBase<T> & >(matrix) /= mat_sum; return mat_sum; } SWIGCODE(%template(normalize) normalize<MatrixMd>;) /** Devide each column of the given `matrix` by its sum, i.e., normalize the columns to have column-sum one. Return `true` if successful, or `false` if a column could not be normalized due to a zero column-sum. */ template<typename T> bool normalizeCols(const DenseBase<T> &matrix) { double col_sum; bool success = true; for (int j = 0; j < matrix.cols(); ++j) { col_sum = matrix.col(j).sum(); if (col_sum == 0) { success = false; } const_cast< DenseBase<T> & >(matrix).col(j) /= col_sum; } return success; } SWIGCODE(%template(normalizeCols) normalizeCols<MatrixMd>;) /** Devide each row of the given `matrix` by its sum, i.e., normalize the rows to have row-sum one. Return `true` if successful, or `false` if a row could not be normalized due to a zero row-sum. */ template<typename T> bool normalizeRows(const DenseBase<T> &matrix) { double row_sum; bool success = true; for (int i = 0; i < matrix.rows(); ++i) { row_sum = matrix.row(i).sum(); if (row_sum == 0) { success = false; } const_cast< DenseBase<T> & >(matrix).row(i) /= row_sum; } return success; } SWIGCODE(%template(normalizeRows) normalizeRows<MatrixMd>;) /** * Return the Kronecker-product \f$A\otimes B\f$ of the matrices `A` and `B`. */ template< typename D1, typename D2 > MatrixXd kron(const MatrixBase<D1>& A, const MatrixBase<D2>& B) { MatrixXd result(A.rows() * B.rows(), A.cols() * B.cols()); for (long j = 0; j < A.cols(); ++j) { for (long i = 0; i < A.rows(); ++i) { result.block(i * B.rows(), j * B.cols(), B.rows(), B.cols()) = A(i,j) * B; } } return result; } SWIGCODE(%template(kron) kron<MatrixMd, MatrixMd>;) SWIGCODE(%kwargs;) /** Return the column-wise generalized mean with exponent `p` (default 1) of the given `matrix`. For `p` = 1, 0, -1 this is the arithmetic, geometric and harmonic mean, respectively. * * Note that for values of `p` other than {1, 2k} this requires all matrix entries to be positive. */ template<typename T> RowVectorXd colwiseMean(const MatrixBase <T> &matrix, double p = 1.0) { RowVectorXd result(matrix.cols()); if (p == std::numeric_limits<double>::infinity()) { result = matrix.array().colwise().maxCoeff(); } else if (p == - std::numeric_limits<double>::infinity()) { result = matrix.array().colwise().minCoeff(); } else if (p == 0) { // geometric mean result = matrix.array().abs().log().colwise().sum() / matrix.rows(); result = result.array().exp(); } else if (p == 1) { // arithmetic mean result = matrix.array().colwise().sum() / matrix.rows(); } else { result = matrix.array().pow(p).colwise().sum() / matrix.rows(); result = result.array().pow(1.0 / p); } return result; } SWIGCODE(%template(colwiseMean) colwiseMean<MatrixMd>;) /** Return the row-wise generalized mean with exponent `p` (default 1) of the given `matrix`. For `p` = 1, 0, -1 this is the arithmetic, geometric and harmonic mean, respectively. * * Note that for values of `p` other than {1, 2k} this requires all matrix entries to be positive. */ template<typename T> VectorXd rowwiseMean(const MatrixBase <T> &matrix, double p = 1.0) { return colwiseMean(matrix.transpose(), p).transpose(); } SWIGCODE(%template(rowwiseMean) rowwiseMean<MatrixMd>;) /** Return the weighted norm of `M` with weights given in `W`, or the squared weighted norm if `squared` is set to `true`. * Depending on the size of `W`, the given weights are interpreted in different ways, assuming `M` is of size m x n: * * - if `W` is of size zero, then no weights are used and the Frobenius norm |M|_F is computed * - if `W` is of size m+n x 1, then row and column weights [w_r; w_c] = W are assumed and |M|_D(w_r w_c^T) is computed * - if `W` is of size m x n, then element-wise weights are assumed and |M|_D(W) is computed * - if `W` is of size m x mn, then a block-diagonal weight matrix is assumed and |M|_D(W1,...,Wn) is computed * - if `W` is of size mn x mn, then a full weight matrix is assumed and |M|_W is computed */ template<typename T, typename T1> double weightedNorm(const MatrixBase<T> &M, const MatrixBase<T1> &W, bool squared = false) throw(std::invalid_argument) { double result = 0; if (W.size() == 0) { result = M.squaredNorm(); } else if (W.cols() == 1 and W.rows() == M.rows() + M.cols()) { result = (W.col(0).head(M.rows()).asDiagonal() * M * W.col(0).tail(M.cols()).asDiagonal()).squaredNorm(); } else if (W.rows() == M.rows()) { if (W.cols() == M.cols()) { result = (W.array() * M.array().square()).sum(); } else if (W.cols() == M.cols() * W.rows()) { for (long j = 0; j < M.cols(); ++j) { result += M.col(j).transpose() * W.middleCols(j * W.rows(), W.rows()) * M.col(j); } } else { throw std::invalid_argument("size mismatch for W and M"); } } else if (W.cols() == M.size() and W.rows() == M.size()) { MatrixXd Mcopy = M; Map<VectorXd, 1> vecM(Mcopy.data(), Mcopy.size()); result = vecM.transpose() * W * vecM; } else { throw std::invalid_argument("size mismatch for W and M"); } result /= M.size(); return squared ? result : std::sqrt(result); } SWIGCODE(%template(weightedNorm) weightedNorm<MatrixMd, MatrixMd>;) SWIGCODE(%apply const MatrixBase<MatrixXd>& OUTPUT { const MatrixBase<MatrixXd>& X };) //<editor-fold desc="Solve implementations"> /** * Return * \ifnot PY * in the output-argument `X` * \endif * the ordinary least-squares (OLS) solution to the problem `A` * `X` = `M` (or if `transposed` to `X` * `A` = `M`) using a `method` from {"Cholesky", "LDLT", "QR" (default), "SVD", "JacobiSVD"}. * * The "Cholesky" method solves the normal equations using a Cholesky decomposition. This is the fastest method, but loses most precision and requires the problem to be overdetermined and `A` to have full rank. * * The "LDLT" method is essentially the same as "Cholesky", but uses a more robust Cholesky decomposition with pivoting that also avoids taking a square root. This method is recommended over "Cholesky" by Eigen3. * * The "QR" method uses a QR decomposition. This is slower than "Cholesky", but gives more precision. The marix `A` should have full rank. * * The "SVD" uses an SVD decomposition. This is the slowest, but gives best precision. Also, the matrix `A` does not need to have full rank, and in the case of an underdetermined problem, the least-squares solution with the smallest norm is returned. * * The "JacobiSVD" method is similar to the "SVD" method, but uses a different (slower, but potentially more accurate) svd algorithm. */ template< typename D, typename D1, typename D2 > C1(void) PY1(MatrixXd) solveOLS(C2(const MatrixBase<D> &X,) const MatrixBase<D1> &A, const MatrixBase<D2> &M, bool transposed = false, const std::string& method = "QR") { if (transposed) { if (method == "Cholesky" or method == "iCholesky") { const_cast<MatrixBase<D> &>(X).derived().noalias() = (A * A.transpose()).llt().solve(A * M.transpose()).transpose(); } else if (method == "LDLT") { const_cast<MatrixBase<D> &>(X).derived().noalias() = (A * A.transpose()).ldlt().solve(A * M.transpose()).transpose(); } else if (method == "QR") { const_cast<MatrixBase<D> &>(X).derived().noalias() = A.transpose().colPivHouseholderQr().solve(M.transpose()).transpose(); } else if (method == "SVD") { const_cast<MatrixBase<D> &>(X).derived().noalias() = A.transpose().bdcSvd(ComputeThinU | ComputeThinV).solve(M.transpose()).transpose(); } else if (method == "JacobiSVD") { const_cast<MatrixBase<D> &>(X).derived().noalias() = A.transpose().jacobiSvd(ComputeThinU | ComputeThinV).solve(M.transpose()).transpose(); } else { throw std::invalid_argument("unrecognized method"); } } else { if (method == "Cholesky" or method == "iCholesky") { const_cast<MatrixBase<D> &>(X).derived().noalias() = (A.transpose() * A).llt().solve(A.transpose() * M); } else if (method == "LDLT") { const_cast<MatrixBase<D> &>(X).derived().noalias() = (A.transpose() * A).ldlt().solve(A.transpose() * M); } else if (method == "QR") { const_cast<MatrixBase<D> &>(X).derived().noalias() = A.colPivHouseholderQr().solve(M); } else if (method == "SVD") { const_cast<MatrixBase<D> &>(X).derived().noalias() = A.bdcSvd(ComputeThinU | ComputeThinV).solve(M); } else if (method == "JacobiSVD") { const_cast<MatrixBase<D> &>(X).derived().noalias() = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(M); } else { throw std::invalid_argument("unrecognized method"); } } } SWIGCODE(%template(solveOLS) solveOLS<MatrixXd, MatrixMd, MatrixMd>;) /** * Return * \ifnot PY * in the output-argument `X`, * \endif * the row or column weighted least-squares solution to the problem `A` * `X` = `M` with row-weights given in the column vector `W` (or if `transposed` to `X` * `A` = `M` with column-weights given in the row vector `W`) using a `method` from {"Cholesky", "LDLT" (default), "QR", "SVD", "JacobiSVD"}. * * This computes `X` that minimizes |D(sqrt_W) * (`A` * `X` - `M`)|_F (or |(`X` * `A` - `M`) * D(sqrt_W)|_F if `transposed`), where `sqrt_W` is the element-wise square-root of `W`, i.e., `W` = `sqrt_W` .* `sqrt_W`, and `.*` denotes the element-wise product. The computation is done by reducing the problem to an OLS problem that is then solved according to the given `method` as detailed below (see also `solveOLS()`). Note that the weights in `W` must be strictly greater than zero. * * Note that column weights have no effect in the default case, and row weight have no effect if `transposed`, and are therefore ommitted. * * The "Cholesky" method solves the normal equations using a Cholesky decomposition. This is the fastest method, but loses most precision and requires the problem to be overdetermined and `A` to have full rank. * * The "LDLT" method is essentially the same as "Cholesky", but uses a more robust Cholesky decomposition with pivoting that also avoids taking a square root. This method is recommended over "Cholesky" by Eigen3. * * The "QR" method uses a QR decomposition. This is slower than "Cholesky", but gives more precision. The marix `A` should have full rank. * * The "SVD" uses an SVD decomposition. This is the slowest, but gives best precision. Also, the matrix `A` does not need to have full rank, and in the case of an underdetermined problem, the least-squares solution with the smallest norm is returned. * * The "JacobiSVD" method is similar to the "SVD" method, but uses a different (slower, but potentially more accurate) svd algorithm. */ template< typename D, typename D1, typename D2, typename D3> C1(void) PY1(MatrixXd) solveRowColWLS(C2(const MatrixBase<D> &X,) const MatrixBase<D1>&A, const MatrixBase<D2>& M, const MatrixBase<D3>& W, bool transposed = false, const std::string &method = "LDLT") { if (transposed) { if (method == "Cholesky" or method == "iCholesky") { const_cast<MatrixBase<D> &>(X).derived().noalias() = (A * W.asDiagonal() * A.transpose()).llt().solve( A * W.asDiagonal() * M.transpose()).transpose(); } else if (method == "LDLT") { const_cast<MatrixBase<D> &>(X).derived().noalias() = (A * W.asDiagonal() * A.transpose()).ldlt().solve( A * W.asDiagonal() * M.transpose()).transpose(); } else { RowVectorXd sqrt_W = W.cwiseSqrt(); solveOLS(X, A * sqrt_W.asDiagonal(), M * sqrt_W.asDiagonal(), transposed, method); } } else { if (method == "Cholesky" or method == "iCholesky") { const_cast<MatrixBase<D> &>(X).derived().noalias() = (A.transpose() * W.asDiagonal() * A).llt().solve( A.transpose() * W.asDiagonal() * M); } else if (method == "LDLT") { const_cast<MatrixBase<D> &>(X).derived().noalias() = (A.transpose() * W.asDiagonal() * A).ldlt().solve( A.transpose() * W.asDiagonal() * M); } else { VectorXd sqrt_W = W.cwiseSqrt(); solveOLS(X, sqrt_W.asDiagonal() * A, sqrt_W.asDiagonal() * M, transposed, method); } } } SWIGCODE(%template(solveRowColWLS) solveRowColWLS<MatrixXd, MatrixMd, MatrixMd, MatrixMd>;) /** * Return * \ifnot PY * in the output-argument `X`, * \endif * the (element-wise) D(`W`)-weighted least-squares (WLS) solution to the problem `A` * `X` = `M` (or to `X` * `A` = `M` if `transposed`) using a `method` from {"Cholesky", "LDLT" (default), "QR", "SVD", "JacobiSVD"}. * * This computes `X` that minimizes |`A` * `X` - `M`|_D(`W`) (or |`X` * `A` - `M`|_D(`W`) if `transposed`). The computation is done by reducing the problem to a set of OLS problems that are then solved according to the given `method` as detailed below (see also `solveOLS()`). Note that the weights in `W` must be strictly greater than zero. * * The "Cholesky" method solves the normal equations using a Cholesky decomposition. This is the fastest method, but loses most precision and requires the problem to be overdetermined and `A` to have full rank. * * The "LDLT" method is essentially the same as "Cholesky", but uses a more robust Cholesky decomposition with pivoting that also avoids taking a square root. This method is recommended over "Cholesky" by Eigen3. * * The "QR" method uses a QR decomposition. This is slower than "Cholesky", but gives more precision. The marix `A` should have full rank. * * The "SVD" uses an SVD decomposition. This is the slowest, but gives best precision. Also, the matrix `A` does not need to have full rank, and in the case of an underdetermined problem, the least-squares solution with the smallest norm is returned. * * The "JacobiSVD" method is similar to the "SVD" method, but uses a different (slower, but potentially more accurate) svd algorithm. */ template< typename D, typename D1, typename D2, typename D3> C1(void) PY1(MatrixXd) solveWLS(C2(const MatrixBase<D> &X,) const MatrixBase<D1>& A, const MatrixBase<D2>& M, const MatrixBase<D3>& W, bool transposed = false, const std::string &method = "LDLT") { if (transposed) { const_cast<MatrixBase<D> &>(X).derived().resize(M.rows(), A.rows()); if (method == "Cholesky" or method == "iCholesky") { LLT<MatrixXd> llt; MatrixXd A_WMT = A * (W.array() * M.array()).matrix().transpose(); for (int i = 0; i < M.rows(); ++i) { llt.compute(A * W.row(i).asDiagonal() * A.transpose()); const_cast<MatrixBase<D> &>(X).row(i).noalias() = llt.solve(A_WMT.col(i)).transpose(); } } else if (method == "LDLT") { LDLT<MatrixXd> ldlt; MatrixXd A_WMT = A * (W.array() * M.array()).matrix().transpose(); for (int i = 0; i < M.rows(); ++i) { ldlt.compute(A * W.row(i).asDiagonal() * A.transpose()); const_cast<MatrixBase<D> &>(X).row(i).noalias() = ldlt.solve(A_WMT.col(i)).transpose(); } } else { MatrixXd sqrt_W = W.cwiseSqrt(); for (int i = 0; i < M.rows(); ++i) { solveOLS(const_cast<MatrixBase<D> &>(X).row(i), A * sqrt_W.row(i).asDiagonal(), M.row(i) * sqrt_W.row(i).asDiagonal(), transposed, method); } } } else { const_cast<MatrixBase<D> &>(X).derived().resize(A.cols(), M.cols()); if (method == "Cholesky" or method == "iCholesky") { LLT<MatrixXd> llt; MatrixXd AT_WM = A.transpose() * (W.array() * M.array()).matrix(); for (int j = 0; j < M.cols(); ++j) { llt.compute(A.transpose() * W.col(j).asDiagonal() * A); const_cast<MatrixBase<D> &>(X).col(j).noalias() = llt.solve(AT_WM.col(j)); } } else if (method == "LDLT") { LDLT<MatrixXd> ldlt; MatrixXd AT_WM = A.transpose() * (W.array() * M.array()).matrix(); for (int j = 0; j < M.cols(); ++j) { ldlt.compute(A.transpose() * W.col(j).asDiagonal() * A); const_cast<MatrixBase<D> &>(X).col(j).noalias() = ldlt.solve(AT_WM.col(j)); } } else { MatrixXd sqrt_W = W.cwiseSqrt(); for (int j = 0; j < M.cols(); ++j) { solveOLS(const_cast<MatrixBase<D> &>(X).col(j), sqrt_W.col(j).asDiagonal() * A, sqrt_W.col(j).asDiagonal() * M.col(j), transposed, method); } } } } SWIGCODE(%template(solveWLS) solveWLS<MatrixXd, MatrixXd, MatrixXd, MatrixXd>;) /** * Return * \ifnot PY * in the output-argument `X`, * \endif * the D(W1,..., Wm)-weighted least-squares (GLS) solution to the overdetermined problem `A` * `X` = `M` (or to `X` * `A` = `M` if `transposed`) using a `method` from {"Cholesky", "LDLT" (default)}, where the block-diagonal symmetric and positive definite weight matrix is given by: * `W` = [[W1]_1,...,[Wn]_1, ..., [W1]_m,...,[Wn]_m], where each `Wj` is the full weight matrix for the column j of `M`. * * This computes `X` that minimizes |`A` * `X` - `M`|_D(W1,...,Wn) (or |`X` * `A` - `M`|_D(W1,...,Wn) if `transposed`). * * Note that the "LDLT" method is essentially the same as "Cholesky", but uses a more robust Cholesky decomposition with pivoting that also avoids taking a square root. This method is recommended over "Cholesky" by Eigen3. */ template< typename D, typename D1, typename D2, typename D3> C1(void) PY1(MatrixXd) solveGLS(C2(const MatrixBase<D> &X,) const MatrixBase<D1> &A, const MatrixBase<D2>& M, const MatrixBase<D3>& W, bool transposed = false, const std::string &method = "LDLT") { assert(W.rows() == M.rows() and W.cols() == M.cols() * M.rows()); // Block-diagonal weight matrix Map<const MatrixXd> W_reshaped(W.derived().data(), W.cols(), W.rows()); if (transposed) { // solve XA≈M by solving [\sum_j AjAj^T ⊗ Wj] vec(X) = vec( [W1M1, W2M2, ..., WnMn] A^T ) MatrixXd AT = A.transpose(); MatrixXd AtI_W_ATtI(A.rows() * W.rows(), A.rows() * W.rows()); // we only compute lower triagonal part #ifdef _OPENMP #pragma omp parallel #endif { VectorXd ATii_ATjj(W.rows()); for (long jj = 0; jj < A.rows(); ++jj) { for (long j = 0; j < M.rows(); ++j) { #ifdef _OPENMP #pragma omp for #endif for (long ii = jj; ii < A.rows(); ++ii) { ATii_ATjj = AT.col(ii).cwiseProduct(AT.col(jj)); AtI_W_ATtI.block(ii * W.rows(), jj * W.rows() + j, W.rows(), 1).noalias() = W.middleCols(j * M.cols(), M.cols()) * ATii_ATjj; } } } } MatrixXd WM = MatrixXd(W.rows(), M.cols()); for (int j = 0; j < M.cols(); ++j) { WM.col(j).noalias() = W_reshaped.middleRows(j*W.rows(), W.rows()) * M.col(j); } WM *= A.transpose(); const Map<const VectorXd> vecWMAT(WM.data(),WM.size()); MatrixXd vecX; if (method == "LDLT") { vecX.noalias() = AtI_W_ATtI.ldlt().solve(vecWMAT); } else if (method == "Cholesky") { vecX.noalias() = AtI_W_ATtI.llt().solve(vecWMAT); } else if (method == "iCholesky") { LLT<Ref<MatrixXd> > llt(AtI_W_ATtI); vecX.noalias() = llt.solve(vecWMAT); } else { throw std::invalid_argument("unrecognized method"); } vecX.resize(M.rows(), A.rows()); const_cast<MatrixBase<D>&>(X).derived() = std::move(vecX); } else { // solve AX≈M by solving SjAXj ≈ SjMj for each column j if (method == "Cholesky" or method == "iCholesky") { LLT<MatrixXd> llt; const_cast<MatrixBase<D> &>(X).derived().resize(A.cols(), M.cols()); for (int j = 0; j < X.cols(); ++j) { llt.compute(A.transpose() * W_reshaped.middleRows(j * W.rows(), W.rows()) * A); const_cast<MatrixBase<D> &>(X).col(j).noalias() = llt.solve( A.transpose() * (W_reshaped.middleRows(j * W.rows(), W.rows()) * M.col(j))); } } else if (method == "LDLT") { LDLT<MatrixXd> ldlt; const_cast<MatrixBase<D> &>(X).derived().resize(A.cols(), M.cols()); for (int j = 0; j < X.cols(); ++j) { ldlt.compute(A.transpose() * W_reshaped.middleRows(j * W.rows(), W.rows()) * A); const_cast<MatrixBase<D> &>(X).col(j).noalias() = ldlt.solve( A.transpose() * (W_reshaped.middleRows(j * W.rows(), W.rows()) * M.col(j))); } } } } SWIGCODE(%template(solveGLS) solveGLS<MatrixXd, MatrixXd, MatrixXd, MatrixXd>;) //</editor-fold> /** * Return * \ifnot PY * in the output-argument `X`, * \endif * the generalized weighted least-squares (GLS) solution to the overdetermined problem `A` * `X` = `M` (or to the problem `X` * `A` = `M` if `transposed`) with the given weights `W` using a `method` from {"Cholesky", "LDLT" (default), "QR", "SVD", "JacobiSVD"}. * * This computes `X` that minimizes the weighted norm |`A` * `X` - `M`|_W (or |`X` * `A` - `M`|_W if `transposed`), utilizing the structure of W that depends on the size of the supplied weights `W` in the following way, assuming `M` is of size m x n: * * - If `W` is of size zero (default), then no weights are used and the ordinary least squares (OLS) solution minimizing the Frobenius norm is returned. * - If `W` is of size m x n, then element-wise weights are assumed, i.e., W = D(`W`), resulting in the weighted least squares (WLS) solution. * - If `W` is of size m x nm, then a block-diagonal structure for W is assumed, i.e., W = D(`W`_1, ..., `W`_m), where `W`_j is the j-th (m x m)-block of `W` corresponding to the weights for [`M`]_j, which must be symmetric an positive definite. * - If `W` is of size m x 1, then these are regarded as row-weights, which only make sense if not `transposed`. * - If `W` is of size 1 x n, then these are regarded as column-weights, which only make sense if `transposed`. * - If `W` is of size m+n x 1 then `W`[:m] are regarded as row-weights and `W`[m:] as column-weights. If `transposed` the row-weights, else the column-weights, have no effect. * * Note that solving GLS with full weight matrix is expensive, and therefore only solving with block-diagonal structured weight matrix is supported, and then only the methods "Cholesky" and "LDLT" which can make use of extra simplifications. * * The computation is done by reducing the problem to a set of OLS problems that are then solved according to the given `method` as detailed below. Note that the weights in `W` must be strictly greater than zero. * * The "Cholesky" method solves the normal equations using a Cholesky decomposition. This is the fastest method, but loses most precision and requires the problem to be overdetermined and `A` to have full rank. * * The "LDLT" method is essentially the same as "Cholesky", but uses a more robust Cholesky decomposition with pivoting that also avoids taking a square root. This method is recommended over "Cholesky" by Eigen3. * * The "QR" method uses a QR decomposition. This is slower than "Cholesky", but gives more precision. The marix `A` should have full rank. * * The "SVD" uses an SVD decomposition. This is the slowest, but gives best precision. Also, the matrix `A` does not need to have full rank in which case the least-squares solution with the smallest norm is returned. * * The "JacobiSVD" method is similar to the "SVD" method, but uses a different (slower, but potentially more accurate) svd algorithm. * */ template< typename D> C1(void) PY1(MatrixXd) solveLS(C2(const MatrixBase<D> &X,) const MatrixXd &A, const MatrixXd &M, const MatrixXd &W = MatrixXd(), bool transposed = false, std::string method = "LDLT") throw(std::invalid_argument) { if (not (method == "Cholesky" or method == "iCholesky" or method == "LDLT" or method == "QR" or method == "SVD" or method == "JacobiSVD")) throw std::invalid_argument("method not recognized"); if (not transposed) { // solve AX=M if (A.rows() != M.rows()) throw std::invalid_argument("LHS rows != RHS rows"); if (A.cols() > A.rows()) throw std::invalid_argument("system must be overdetermined"); if (W.size() == 0) { solveOLS(X, A, M, transposed, method); } else if (W.rows() == M.rows() and W.cols() == M.cols()) { solveWLS(X, A, M, W, transposed, method); } else if (W.rows() == M.rows() and W.cols() == M.rows() * M.cols()) { if (method != "Cholesky" and method != "LDLT" and method != "iCholesky") throw std::invalid_argument("GLS only supported with method 'Cholesky' or 'LDLT'"); solveGLS(X, A, M, W, transposed, method); } else if (W.rows() == W.cols() and W.cols() == M.rows() * M.cols()) throw std::invalid_argument("GLS with full weight matrix not implemented"); else if (W.rows() == M.rows() and W.cols() == 1) { solveRowColWLS(X, A, M, W, transposed, method); } else if (W.cols() == 1 and W.rows() == M.rows() + M.cols()) { solveRowColWLS(X, A, M, W.col(0).head(M.rows()), transposed, method); } else { throw std::invalid_argument("size mismatch for M and W"); } } else { // solve XA=M if (A.cols() != M.cols()) throw std::invalid_argument("LHS cols != RHS cols"); if (A.rows() > A.cols()) throw std::invalid_argument("system must be overdetermined"); if (W.size() == 0) { solveOLS(X, A, M, transposed, method); } else if (W.rows() == M.rows() and W.cols() == M.cols()) { solveWLS(X, A, M, W, transposed, method); } else if (W.rows() == M.rows() and W.cols() == M.rows() * M.cols()) { if (method != "Cholesky" and method != "LDLT" and method != "iCholesky") throw std::invalid_argument("GLS only supported with method 'Cholesky' or 'LDLT'"); solveGLS(X, A, M, W, transposed, method); } else if (W.rows() == W.cols() and W.cols() == M.rows() * M.cols()) throw std::invalid_argument("LS with full weight matrix not implemented"); else if (W.rows() == 1 and W.cols() == M.cols()) { solveRowColWLS(X, A, M, W, transposed, method); } else if (W.cols() == 1 and W.rows() == M.rows() + M.cols()) { solveRowColWLS(X, A, M, W.col(0).tail(M.cols()).transpose(), transposed, method); } else { throw std::invalid_argument("size mismatch for M and W"); } } } SWIGCODE(%template(solveLS) solveLS<MatrixXd>;) /** * Return a new weight matrix for `X`, assuming `X` is a solution to the D(`W`)-weighted WLS problem `B` * `X` = `M`. * * Note that the columns of `X` can be regarded as coordinate representations for the columns of `M` with respect to a basis given by the columns of `B`. This function transforms the given weights for the columns of `M` to appropriate weights for the coordinates in the columns of `X`. The resulting weight matrix for `X` will therefore be block-diagonal in general, but if `covariances` is set to `false`, the off-diagonal weights are ignored, resulting in element-wise weights for `X`. * * The returned matrix will therefore be * * - [[tW_1]_1, ..., [tW_m]_1, ..., [tW_1]_{B.cols}, ..., [tW_m]_{B.cols}] of size (B.cols x M.cols) * B.cols if `covariances`, where * tW_j = B^T * D([W]_j) * B * - [diag(B^T * D([W]_1) * B), ..., diag(B^T * D([W]_m) * B)] of size B.cols() x M.cols() otherwise. */ template< typename D1, typename D2 > MatrixXd transformWeights(const MatrixBase<D1> &W, const MatrixBase<D2> &B, bool covariances = true) { MatrixXd newWeights(B.cols(), W.cols() * (covariances ? B.cols() : 1)); for (int j = 0; j < W.cols(); ++j) { if (covariances) { MatrixXd::Map(newWeights.data(), B.cols() * W.cols(), B.cols()).middleRows(j * B.cols(), B.cols()).noalias() = B.transpose() * W.col(j).asDiagonal() * B; } else { newWeights.col(j).noalias() = (B.transpose() * W.col(j).asDiagonal() * B).diagonal(); } } return newWeights; } SWIGCODE(%template(transformWeights) transformWeights<MatrixMd, MatrixMd>;) /** * \ifnot PY * Compute in the arguments `U`,`s` and `VT` * \else * Return in a tuple [U,s,VT] * \endif * the singular value decomposition of the given matrix `M`, such that `M = U D(s) VT`, using the given `method` ('bdc' | 'jacobi'). */ SWIGCODE(%apply const MatrixXd& OUTPUT { const MatrixXd &U, const MatrixXd &VT };) SWIGCODE(%apply const ArrayXd& OUTPUT { const ArrayXd &s };) template<typename D > C1(void) PY3(tuple<MatrixXd, ArrayXd, MatrixXd>) svd(C4(const MatrixXd &U, const ArrayXd &s, const MatrixXd &VT,) const MatrixBase<D> &M, const std::string &method="bdc") { if (method == "bdc") { BDCSVD<MatrixXd> svd(M, ComputeThinU | ComputeThinV); const_cast<MatrixXd&>(U) = svd.matrixU(); const_cast<ArrayXd&>(s) = svd.singularValues(); const_cast<MatrixXd&>(VT) = svd.matrixV().transpose(); } else if (method == "jacobi") { JacobiSVD<MatrixXd> svd(M, ComputeThinU | ComputeThinV); const_cast<MatrixXd&>(U) = svd.matrixU(); const_cast<ArrayXd&>(s) = svd.singularValues(); const_cast<MatrixXd&>(VT) = svd.matrixV().transpose(); } } SWIGCODE(%template(svd) svd<MatrixMd >;) SWIGCODE(%clear const MatrixXd &U, const ArrayXd &s, const MatrixXd &VT;) /** * Return the pseudo-inverse of the given matrix `M` computed according to the given `method` from {"Cholesky", "QR", "SVD" (default), "JacobiSVD"}. * * If `method` is "SVD" or "JacobiSVD", the classical pseudo-inverse is computed from the svd of `M`. * * If `method` is "QR", the pseudo-inverse is computed from the QR-factorization of `M`, which requires `M` to have full rank. * * If `method` is "Cholesky" or "LDLT", the pseudo-inverse is computed as \f$(M^\top M)^{-1} M^\top\f$ or \f$M^\top (M M^\top)^{-1}\f$ depending on the size of `M`, which requires `M` to have full rank. */ template<typename D> MatrixXd pinv(const MatrixBase<D> &M, const std::string &method = "SVD") { MatrixXd result; unsigned long I_size = M.rows(); bool transpose = false; if ((method == "LDLT" or method == "Cholesky" or method == "iCholesky" or method == "QR") and (M.rows() < M.cols())) { I_size = M.cols(); transpose = true; } solveOLS(result, M, MatrixXd::Identity(I_size, I_size), transpose, method); return result; } SWIGCODE(%template(pinv) pinv<MatrixMd>;) /** * Compute in the arguments `B` and `A` (an approximation to) the best weighted rank-d approximation to `M` with element-wise weights `W` such that |`B` * `A` - `M`|_D(W) is minimized. This is computed iteratively starting from an initial approximation given by `B` * `A` using "alternating projections" solved via the given `method`. The termination of the iteration is controlled by the given `stopCondition`. * \ifnot PY * See `StopCondition`. * \else * See `tom.util.StopCondition`. * \endif */ template<typename D1, typename D2, typename D3, typename D4> void improveWLRA(const MatrixBase<D1> &B, const MatrixBase<D2> &A, const MatrixBase<D3> &M, const MatrixBase<D4> &W, const StopCondition& stopCondition = StopCondition(50, 1e-5, 1e-12), const std::string &method = "Cholesky") { const_cast<StopCondition&>(stopCondition).reset(); while (not const_cast<StopCondition&>(stopCondition)(weightedNorm(M - B * A, W))) { solveWLS(B, A, M, W, true, method); solveWLS(A, B, M, W, false, method); } } SWIGCODE(%template(improveWLRA) improveWLRA<MatrixMd, MatrixMd, MatrixXd, MatrixXd >;) /** * \ifnot PY * Compute in the arguments `B` and `A` * \else * Return in a tuple [B,A] * \endif * (an approximation to) the best weighted rank-d approximation to `M` with element-wise weights `W` such that |`B` * `A` - `M`|_D(vect(W)) is minimized. This is computed iteratively starting from an initial approximation given by `B_init` using "alternating projections", which are in turn solved via the given `method`. The termination of the iteration is controlled by the given `stopCondition`. * \ifnot PY * See `StopCondition`. * \else * See `tom.util.StopCondition`. * \endif */ SWIGCODE(%apply const MatrixBase<MatrixXd>& OUTPUT { const MatrixBase<MatrixXd> &B, const MatrixBase<MatrixXd> &A };) template<typename D1, typename D2, typename D3, typename D4, typename D5> C1(void) PY2(tuple<MatrixXd, MatrixXd>) computeWLRA(C3(const MatrixBase<D1> &B, const MatrixBase<D2> &A,) const MatrixBase<D3> &M, const MatrixBase<D4> &W, const MatrixBase<D5> &B_init, const StopCondition& stopCondition = StopCondition(50, 1e-5, 1e-12), const std::string &method = "Cholesky") throw(std::invalid_argument) { if (W.rows() != M.rows() or W.cols() != M.cols() or B_init.rows() != M.rows() or B_init.cols() > M.cols()) { throw std::invalid_argument("size mismatch"); } const_cast<MatrixBase<D1>&>(B).derived() = B_init; solveWLS(A, B, M, W, false, method); improveWLRA(B, A, M, W, stopCondition, method); } SWIGCODE(%template(computeWLRA) computeWLRA<MatrixXd, MatrixXd, MatrixXd, MatrixXd, MatrixXd >;) SWIGCODE(%clear const MatrixBase<MatrixXd> &X, const MatrixBase<MatrixXd> &B, const MatrixBase<MatrixXd> &A;) SWIGCODE(%clearkwargs;) } // namespace tom
val_omp.c
/* This file performs the following test: each OMP thread measures flops for its provided tasks, and compares this to expected flop counts, each thread having been provided with a random amount of work, such that the time and order that they complete their measurements varies. Specifically tested is the case where the value returned for some threads actually corresponds to that for another thread reading its counter values at the same time. - It is based on zero_omp.c but ignored much of its functionality. - It attempts to use the following two counters. It may use less depending on hardware counter resource limitations. These are counted in the default counting domain and default granularity, depending on the platform. Usually this is the user domain (PAPI_DOM_USER) and thread context (PAPI_GRN_THR). + PAPI_FP_INS + PAPI_TOT_CYC Each thread inside the Thread routine: - Do prework (MAX_FLOPS - flops) - Get cyc. - Get us. - Start counters - Do flops - Stop and read counters - Get us. - Get cyc. - Return flops */ #include "papi_test.h" #ifdef _OPENMP #include <omp.h> #else #error "This compiler does not understand OPENMP" #endif const int MAX_FLOPS = NUM_FLOPS; extern int TESTS_QUIET; /* Declared in test_utils.c */ const PAPI_hw_info_t *hw_info = NULL; long long Thread( int n ) { int retval, num_tests = 1; int EventSet1 = PAPI_NULL; int PAPI_event, mask1; int num_events1; long long flops; long long **values; long long elapsed_us, elapsed_cyc; char event_name[PAPI_MAX_STR_LEN]; /* printf("Thread(n=%d) %#x started\n", n, omp_get_thread_num()); */ num_events1 = 2; /* add PAPI_TOT_CYC and one of the events in PAPI_FP_INS, PAPI_FP_OPS or PAPI_TOT_INS, depending on the availability of the event on the platform */ EventSet1 = add_two_events( &num_events1, &PAPI_event, &mask1 ); retval = PAPI_event_code_to_name( PAPI_event, event_name ); if ( retval != PAPI_OK ) test_fail( __FILE__, __LINE__, "PAPI_event_code_to_name", retval ); values = allocate_test_space( num_tests, num_events1 ); do_flops( MAX_FLOPS - n ); /* prework for balance */ elapsed_us = PAPI_get_real_usec( ); elapsed_cyc = PAPI_get_real_cyc( ); retval = PAPI_start( EventSet1 ); if ( retval != PAPI_OK ) test_fail( __FILE__, __LINE__, "PAPI_start", retval ); do_flops( n ); retval = PAPI_stop( EventSet1, values[0] ); if ( retval != PAPI_OK ) test_fail( __FILE__, __LINE__, "PAPI_stop", retval ); flops = ( values[0] )[0]; elapsed_us = PAPI_get_real_usec( ) - elapsed_us; elapsed_cyc = PAPI_get_real_cyc( ) - elapsed_cyc; remove_test_events( &EventSet1, mask1 ); if ( !TESTS_QUIET ) { /*printf("Thread %#x %-12s : \t%lld\t%d\n", omp_get_thread_num(), event_name, (values[0])[0], n); */ #if 0 printf( "Thread %#x PAPI_TOT_CYC: \t%lld\n", omp_get_thread_num( ), values[0][0] ); printf( "Thread %#x Real usec : \t%lld\n", omp_get_thread_num( ), elapsed_us ); printf( "Thread %#x Real cycles : \t%lld\n", omp_get_thread_num( ), elapsed_cyc ); #endif } /* It is illegal for the threads to exit in OpenMP */ /* test_pass(__FILE__,0,0); */ free_test_space( values, num_tests ); PAPI_unregister_thread( ); /* printf("Thread %#x finished\n", omp_get_thread_num()); */ return flops; } int main( int argc, char **argv ) { int tid, retval; int maxthr = omp_get_max_threads( ); int flopper = 0; long long *flops = calloc( maxthr, sizeof ( long long ) ); long long *flopi = calloc( maxthr, sizeof ( long long ) ); tests_quiet( argc, argv ); /* Set TESTS_QUIET variable */ if ( maxthr < 2 ) test_skip( __FILE__, __LINE__, "omp_get_num_threads < 2", PAPI_EINVAL ); if ( ( flops == NULL ) || ( flopi == NULL ) ) test_fail( __FILE__, __LINE__, "calloc", PAPI_ENOMEM ); retval = PAPI_library_init( PAPI_VER_CURRENT ); if ( retval != PAPI_VER_CURRENT ) test_fail( __FILE__, __LINE__, "PAPI_library_init", retval ); hw_info = PAPI_get_hardware_info( ); if ( hw_info == NULL ) test_fail( __FILE__, __LINE__, "PAPI_get_hardware_info", 2 ); retval = PAPI_thread_init( ( unsigned long ( * )( void ) ) ( omp_get_thread_num ) ); if ( retval != PAPI_OK ) if ( retval == PAPI_ECMP ) test_skip( __FILE__, __LINE__, "PAPI_thread_init", retval ); else test_fail( __FILE__, __LINE__, "PAPI_thread_init", retval ); flopper = Thread( 65536 ) / 65536; printf( "flopper=%d\n", flopper ); for ( int i = 0; i < 100000; i++ ) #pragma omp parallel private(tid) { tid = omp_get_thread_num( ); flopi[tid] = rand( ) * 3; flops[tid] = Thread( ( flopi[tid] / flopper ) % MAX_FLOPS ); #pragma omp barrier #pragma omp master if ( flops[tid] < flopi[tid] ) { printf( "test iteration=%d\n", i ); for ( int j = 0; j < omp_get_num_threads( ); j++ ) { printf( "Thread %#x Value %6lld %c %6lld", j, flops[j], ( flops[j] < flopi[j] ) ? '<' : '=', flopi[j] ); for ( int k = 0; k < omp_get_num_threads( ); k++ ) if ( ( k != j ) && ( flops[k] == flops[j] ) ) printf( " == Thread %#x!", k ); printf( "\n" ); } test_fail( __FILE__, __LINE__, "value returned for thread", PAPI_EBUG ); } } test_pass( __FILE__, NULL, 0 ); exit( 0 ); }
OpenMPClause.h
//===- OpenMPClause.h - Classes for OpenMP clauses --------------*- 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 // //===----------------------------------------------------------------------===// // /// \file /// This file defines OpenMP AST classes for clauses. /// There are clauses for executable directives, clauses for declarative /// directives and clauses which can be used in both kinds of directives. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_OPENMPCLAUSE_H #define LLVM_CLANG_AST_OPENMPCLAUSE_H #include "clang/AST/Decl.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/Stmt.h" #include "clang/AST/StmtIterator.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/iterator.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/TrailingObjects.h" #include <cassert> #include <cstddef> #include <iterator> #include <utility> namespace clang { class ASTContext; //===----------------------------------------------------------------------===// // AST classes for clauses. //===----------------------------------------------------------------------===// /// This is a basic class for representing single OpenMP clause. class OMPClause { /// Starting location of the clause (the clause keyword). SourceLocation StartLoc; /// Ending location of the clause. SourceLocation EndLoc; /// Kind of the clause. OpenMPClauseKind Kind; protected: OMPClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation EndLoc) : StartLoc(StartLoc), EndLoc(EndLoc), Kind(K) {} public: /// Returns the starting location of the clause. SourceLocation getBeginLoc() const { return StartLoc; } /// Returns the ending location of the clause. SourceLocation getEndLoc() const { return EndLoc; } /// Sets the starting location of the clause. void setLocStart(SourceLocation Loc) { StartLoc = Loc; } /// Sets the ending location of the clause. void setLocEnd(SourceLocation Loc) { EndLoc = Loc; } /// Returns kind of OpenMP clause (private, shared, reduction, etc.). OpenMPClauseKind getClauseKind() const { return Kind; } bool isImplicit() const { return StartLoc.isInvalid(); } using child_iterator = StmtIterator; using const_child_iterator = ConstStmtIterator; using child_range = llvm::iterator_range<child_iterator>; using const_child_range = llvm::iterator_range<const_child_iterator>; child_range children(); const_child_range children() const { auto Children = const_cast<OMPClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } /// Get the iterator range for the expressions used in the clauses. Used /// expressions include only the children that must be evaluated at the /// runtime before entering the construct. child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *) { return true; } }; /// Class that handles pre-initialization statement for some clauses, like /// 'shedule', 'firstprivate' etc. class OMPClauseWithPreInit { friend class OMPClauseReader; /// Pre-initialization statement for the clause. Stmt *PreInit = nullptr; /// Region that captures the associated stmt. OpenMPDirectiveKind CaptureRegion = llvm::omp::OMPD_unknown; protected: OMPClauseWithPreInit(const OMPClause *This) { assert(get(This) && "get is not tuned for pre-init."); } /// Set pre-initialization statement for the clause. void setPreInitStmt(Stmt *S, OpenMPDirectiveKind ThisRegion = llvm::omp::OMPD_unknown) { PreInit = S; CaptureRegion = ThisRegion; } public: /// Get pre-initialization statement for the clause. const Stmt *getPreInitStmt() const { return PreInit; } /// Get pre-initialization statement for the clause. Stmt *getPreInitStmt() { return PreInit; } /// Get capture region for the stmt in the clause. OpenMPDirectiveKind getCaptureRegion() const { return CaptureRegion; } static OMPClauseWithPreInit *get(OMPClause *C); static const OMPClauseWithPreInit *get(const OMPClause *C); }; /// Class that handles post-update expression for some clauses, like /// 'lastprivate', 'reduction' etc. class OMPClauseWithPostUpdate : public OMPClauseWithPreInit { friend class OMPClauseReader; /// Post-update expression for the clause. Expr *PostUpdate = nullptr; protected: OMPClauseWithPostUpdate(const OMPClause *This) : OMPClauseWithPreInit(This) { assert(get(This) && "get is not tuned for post-update."); } /// Set pre-initialization statement for the clause. void setPostUpdateExpr(Expr *S) { PostUpdate = S; } public: /// Get post-update expression for the clause. const Expr *getPostUpdateExpr() const { return PostUpdate; } /// Get post-update expression for the clause. Expr *getPostUpdateExpr() { return PostUpdate; } static OMPClauseWithPostUpdate *get(OMPClause *C); static const OMPClauseWithPostUpdate *get(const OMPClause *C); }; /// This structure contains most locations needed for by an OMPVarListClause. struct OMPVarListLocTy { /// Starting location of the clause (the clause keyword). SourceLocation StartLoc; /// Location of '('. SourceLocation LParenLoc; /// Ending location of the clause. SourceLocation EndLoc; OMPVarListLocTy() = default; OMPVarListLocTy(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : StartLoc(StartLoc), LParenLoc(LParenLoc), EndLoc(EndLoc) {} }; /// This represents clauses with the list of variables like 'private', /// 'firstprivate', 'copyin', 'shared', or 'reduction' clauses in the /// '#pragma omp ...' directives. template <class T> class OMPVarListClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Number of variables in the list. unsigned NumVars; protected: /// Build a clause with \a N variables /// /// \param K Kind of the clause. /// \param StartLoc Starting location of the clause (the clause keyword). /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPVarListClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPClause(K, StartLoc, EndLoc), LParenLoc(LParenLoc), NumVars(N) {} /// Fetches list of variables associated with this clause. MutableArrayRef<Expr *> getVarRefs() { return MutableArrayRef<Expr *>( static_cast<T *>(this)->template getTrailingObjects<Expr *>(), NumVars); } /// Sets the list of variables for this clause. void setVarRefs(ArrayRef<Expr *> VL) { assert(VL.size() == NumVars && "Number of variables is not the same as the preallocated buffer"); std::copy(VL.begin(), VL.end(), static_cast<T *>(this)->template getTrailingObjects<Expr *>()); } public: using varlist_iterator = MutableArrayRef<Expr *>::iterator; using varlist_const_iterator = ArrayRef<const Expr *>::iterator; using varlist_range = llvm::iterator_range<varlist_iterator>; using varlist_const_range = llvm::iterator_range<varlist_const_iterator>; unsigned varlist_size() const { return NumVars; } bool varlist_empty() const { return NumVars == 0; } varlist_range varlists() { return varlist_range(varlist_begin(), varlist_end()); } varlist_const_range varlists() const { return varlist_const_range(varlist_begin(), varlist_end()); } varlist_iterator varlist_begin() { return getVarRefs().begin(); } varlist_iterator varlist_end() { return getVarRefs().end(); } varlist_const_iterator varlist_begin() const { return getVarRefs().begin(); } varlist_const_iterator varlist_end() const { return getVarRefs().end(); } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Fetches list of all variables in the clause. ArrayRef<const Expr *> getVarRefs() const { return llvm::makeArrayRef( static_cast<const T *>(this)->template getTrailingObjects<Expr *>(), NumVars); } }; /// This represents 'allocator' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp allocate(a) allocator(omp_default_mem_alloc) /// \endcode /// In this example directive '#pragma omp allocate' has simple 'allocator' /// clause with the allocator 'omp_default_mem_alloc'. class OMPAllocatorClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Expression with the allocator. Stmt *Allocator = nullptr; /// Set allocator. void setAllocator(Expr *A) { Allocator = A; } public: /// Build 'allocator' clause with the given allocator. /// /// \param A Allocator. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPAllocatorClause(Expr *A, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_allocator, StartLoc, EndLoc), LParenLoc(LParenLoc), Allocator(A) {} /// Build an empty clause. OMPAllocatorClause() : OMPClause(llvm::omp::OMPC_allocator, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns allocator. Expr *getAllocator() const { return cast_or_null<Expr>(Allocator); } child_range children() { return child_range(&Allocator, &Allocator + 1); } const_child_range children() const { return const_child_range(&Allocator, &Allocator + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_allocator; } }; /// This represents clause 'allocate' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel private(a) allocate(omp_default_mem_alloc :a) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'private' /// and clause 'allocate' for the variable 'a'. class OMPAllocateClause final : public OMPVarListClause<OMPAllocateClause>, private llvm::TrailingObjects<OMPAllocateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Allocator specified in the clause, or 'nullptr' if the default one is /// used. Expr *Allocator = nullptr; /// Position of the ':' delimiter in the clause; SourceLocation ColonLoc; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Allocator Allocator expression. /// \param ColonLoc Location of ':' delimiter. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPAllocateClause(SourceLocation StartLoc, SourceLocation LParenLoc, Expr *Allocator, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPAllocateClause>(llvm::omp::OMPC_allocate, StartLoc, LParenLoc, EndLoc, N), Allocator(Allocator), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPAllocateClause(unsigned N) : OMPVarListClause<OMPAllocateClause>(llvm::omp::OMPC_allocate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } void setAllocator(Expr *A) { Allocator = A; } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Allocator Allocator expression. /// \param ColonLoc Location of ':' delimiter. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPAllocateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, Expr *Allocator, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Returns the allocator expression or nullptr, if no allocator is specified. Expr *getAllocator() const { return Allocator; } /// Returns the location of the ':' delimiter. SourceLocation getColonLoc() const { return ColonLoc; } /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPAllocateClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPAllocateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_allocate; } }; /// This represents 'if' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel if(parallel:a > 5) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'if' clause with /// condition 'a > 5' and directive name modifier 'parallel'. class OMPIfClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'if' clause. Stmt *Condition = nullptr; /// Location of ':' (if any). SourceLocation ColonLoc; /// Directive name modifier for the clause. OpenMPDirectiveKind NameModifier = llvm::omp::OMPD_unknown; /// Name modifier location. SourceLocation NameModifierLoc; /// Set condition. void setCondition(Expr *Cond) { Condition = Cond; } /// Set directive name modifier for the clause. void setNameModifier(OpenMPDirectiveKind NM) { NameModifier = NM; } /// Set location of directive name modifier for the clause. void setNameModifierLoc(SourceLocation Loc) { NameModifierLoc = Loc; } /// Set location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Build 'if' clause with condition \a Cond. /// /// \param NameModifier [OpenMP 4.1] Directive name modifier of clause. /// \param Cond Condition of the clause. /// \param HelperCond Helper condition for the clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param NameModifierLoc Location of directive name modifier. /// \param ColonLoc [OpenMP 4.1] Location of ':'. /// \param EndLoc Ending location of the clause. OMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Cond, Stmt *HelperCond, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_if, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond), ColonLoc(ColonLoc), NameModifier(NameModifier), NameModifierLoc(NameModifierLoc) { setPreInitStmt(HelperCond, CaptureRegion); } /// Build an empty clause. OMPIfClause() : OMPClause(llvm::omp::OMPC_if, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } /// Return directive name modifier associated with the clause. OpenMPDirectiveKind getNameModifier() const { return NameModifier; } /// Return the location of directive name modifier. SourceLocation getNameModifierLoc() const { return NameModifierLoc; } child_range children() { return child_range(&Condition, &Condition + 1); } const_child_range children() const { return const_child_range(&Condition, &Condition + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPIfClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_if; } }; /// This represents 'final' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task final(a > 5) /// \endcode /// In this example directive '#pragma omp task' has simple 'final' /// clause with condition 'a > 5'. class OMPFinalClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'if' clause. Stmt *Condition = nullptr; /// Set condition. void setCondition(Expr *Cond) { Condition = Cond; } public: /// Build 'final' clause with condition \a Cond. /// /// \param Cond Condition of the clause. /// \param HelperCond Helper condition for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPFinalClause(Expr *Cond, Stmt *HelperCond, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_final, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond) { setPreInitStmt(HelperCond, CaptureRegion); } /// Build an empty clause. OMPFinalClause() : OMPClause(llvm::omp::OMPC_final, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } child_range children() { return child_range(&Condition, &Condition + 1); } const_child_range children() const { return const_child_range(&Condition, &Condition + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPFinalClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_final; } }; /// This represents 'num_threads' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel num_threads(6) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'num_threads' /// clause with number of threads '6'. class OMPNumThreadsClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'num_threads' clause. Stmt *NumThreads = nullptr; /// Set condition. void setNumThreads(Expr *NThreads) { NumThreads = NThreads; } public: /// Build 'num_threads' clause with condition \a NumThreads. /// /// \param NumThreads Number of threads for the construct. /// \param HelperNumThreads Helper Number of threads for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPNumThreadsClause(Expr *NumThreads, Stmt *HelperNumThreads, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_num_threads, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumThreads(NumThreads) { setPreInitStmt(HelperNumThreads, CaptureRegion); } /// Build an empty clause. OMPNumThreadsClause() : OMPClause(llvm::omp::OMPC_num_threads, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns number of threads. Expr *getNumThreads() const { return cast_or_null<Expr>(NumThreads); } child_range children() { return child_range(&NumThreads, &NumThreads + 1); } const_child_range children() const { return const_child_range(&NumThreads, &NumThreads + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_num_threads; } }; /// This represents 'safelen' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd safelen(4) /// \endcode /// In this example directive '#pragma omp simd' has clause 'safelen' /// with single expression '4'. /// If the safelen clause is used then no two iterations executed /// concurrently with SIMD instructions can have a greater distance /// in the logical iteration space than its value. The parameter of /// the safelen clause must be a constant positive integer expression. class OMPSafelenClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *Safelen = nullptr; /// Set safelen. void setSafelen(Expr *Len) { Safelen = Len; } public: /// Build 'safelen' clause. /// /// \param Len Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSafelenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_safelen, StartLoc, EndLoc), LParenLoc(LParenLoc), Safelen(Len) {} /// Build an empty clause. explicit OMPSafelenClause() : OMPClause(llvm::omp::OMPC_safelen, SourceLocation(), SourceLocation()) { } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getSafelen() const { return cast_or_null<Expr>(Safelen); } child_range children() { return child_range(&Safelen, &Safelen + 1); } const_child_range children() const { return const_child_range(&Safelen, &Safelen + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_safelen; } }; /// This represents 'simdlen' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd simdlen(4) /// \endcode /// In this example directive '#pragma omp simd' has clause 'simdlen' /// with single expression '4'. /// If the 'simdlen' clause is used then it specifies the preferred number of /// iterations to be executed concurrently. The parameter of the 'simdlen' /// clause must be a constant positive integer expression. class OMPSimdlenClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *Simdlen = nullptr; /// Set simdlen. void setSimdlen(Expr *Len) { Simdlen = Len; } public: /// Build 'simdlen' clause. /// /// \param Len Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSimdlenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_simdlen, StartLoc, EndLoc), LParenLoc(LParenLoc), Simdlen(Len) {} /// Build an empty clause. explicit OMPSimdlenClause() : OMPClause(llvm::omp::OMPC_simdlen, SourceLocation(), SourceLocation()) { } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getSimdlen() const { return cast_or_null<Expr>(Simdlen); } child_range children() { return child_range(&Simdlen, &Simdlen + 1); } const_child_range children() const { return const_child_range(&Simdlen, &Simdlen + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_simdlen; } }; /// This represents 'collapse' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd collapse(3) /// \endcode /// In this example directive '#pragma omp simd' has clause 'collapse' /// with single expression '3'. /// The parameter must be a constant positive integer expression, it specifies /// the number of nested loops that should be collapsed into a single iteration /// space. class OMPCollapseClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Number of for-loops. Stmt *NumForLoops = nullptr; /// Set the number of associated for-loops. void setNumForLoops(Expr *Num) { NumForLoops = Num; } public: /// Build 'collapse' clause. /// /// \param Num Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPCollapseClause(Expr *Num, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_collapse, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num) {} /// Build an empty clause. explicit OMPCollapseClause() : OMPClause(llvm::omp::OMPC_collapse, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return the number of associated for-loops. Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); } child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); } const_child_range children() const { return const_child_range(&NumForLoops, &NumForLoops + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_collapse; } }; /// This represents 'default' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel default(shared) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'default' /// clause with kind 'shared'. class OMPDefaultClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'default' clause. llvm::omp::DefaultKind Kind = llvm::omp::OMP_DEFAULT_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clauses. /// /// \param K Argument of clause. void setDefaultKind(llvm::omp::DefaultKind K) { Kind = K; } /// Set argument location. /// /// \param KLoc Argument location. void setDefaultKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'default' clause with argument \a A ('none' or 'shared'). /// /// \param A Argument of the clause ('none' or 'shared'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDefaultClause(llvm::omp::DefaultKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_default, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPDefaultClause() : OMPClause(llvm::omp::OMPC_default, SourceLocation(), SourceLocation()) { } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. llvm::omp::DefaultKind getDefaultKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getDefaultKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_default; } }; /// This represents 'proc_bind' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel proc_bind(master) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'proc_bind' /// clause with kind 'master'. class OMPProcBindClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'proc_bind' clause. llvm::omp::ProcBindKind Kind = llvm::omp::OMP_PROC_BIND_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clause. /// /// \param K Kind of clause. void setProcBindKind(llvm::omp::ProcBindKind K) { Kind = K; } /// Set clause kind location. /// /// \param KLoc Kind location. void setProcBindKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'proc_bind' clause with argument \a A ('master', 'close' or /// 'spread'). /// /// \param A Argument of the clause ('master', 'close' or 'spread'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPProcBindClause(llvm::omp::ProcBindKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_proc_bind, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPProcBindClause() : OMPClause(llvm::omp::OMPC_proc_bind, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. llvm::omp::ProcBindKind getProcBindKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getProcBindKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_proc_bind; } }; /// This represents 'unified_address' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires unified_address /// \endcode /// In this example directive '#pragma omp requires' has 'unified_address' /// clause. class OMPUnifiedAddressClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'unified_address' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_unified_address, StartLoc, EndLoc) {} /// Build an empty clause. OMPUnifiedAddressClause() : OMPClause(llvm::omp::OMPC_unified_address, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_unified_address; } }; /// This represents 'unified_shared_memory' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires unified_shared_memory /// \endcode /// In this example directive '#pragma omp requires' has 'unified_shared_memory' /// clause. class OMPUnifiedSharedMemoryClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'unified_shared_memory' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_unified_shared_memory, StartLoc, EndLoc) {} /// Build an empty clause. OMPUnifiedSharedMemoryClause() : OMPClause(llvm::omp::OMPC_unified_shared_memory, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_unified_shared_memory; } }; /// This represents 'reverse_offload' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires reverse_offload /// \endcode /// In this example directive '#pragma omp requires' has 'reverse_offload' /// clause. class OMPReverseOffloadClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'reverse_offload' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_reverse_offload, StartLoc, EndLoc) {} /// Build an empty clause. OMPReverseOffloadClause() : OMPClause(llvm::omp::OMPC_reverse_offload, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_reverse_offload; } }; /// This represents 'dynamic_allocators' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires dynamic_allocators /// \endcode /// In this example directive '#pragma omp requires' has 'dynamic_allocators' /// clause. class OMPDynamicAllocatorsClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'dynamic_allocators' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_dynamic_allocators, StartLoc, EndLoc) {} /// Build an empty clause. OMPDynamicAllocatorsClause() : OMPClause(llvm::omp::OMPC_dynamic_allocators, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_dynamic_allocators; } }; /// This represents 'atomic_default_mem_order' clause in the '#pragma omp /// requires' directive. /// /// \code /// #pragma omp requires atomic_default_mem_order(seq_cst) /// \endcode /// In this example directive '#pragma omp requires' has simple /// atomic_default_mem_order' clause with kind 'seq_cst'. class OMPAtomicDefaultMemOrderClause final : public OMPClause { friend class OMPClauseReader; /// Location of '(' SourceLocation LParenLoc; /// A kind of the 'atomic_default_mem_order' clause. OpenMPAtomicDefaultMemOrderClauseKind Kind = OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clause. /// /// \param K Kind of clause. void setAtomicDefaultMemOrderKind(OpenMPAtomicDefaultMemOrderClauseKind K) { Kind = K; } /// Set clause kind location. /// /// \param KLoc Kind location. void setAtomicDefaultMemOrderKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'atomic_default_mem_order' clause with argument \a A ('seq_cst', /// 'acq_rel' or 'relaxed'). /// /// \param A Argument of the clause ('seq_cst', 'acq_rel' or 'relaxed'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPAtomicDefaultMemOrderClause(OpenMPAtomicDefaultMemOrderClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_atomic_default_mem_order, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPAtomicDefaultMemOrderClause() : OMPClause(llvm::omp::OMPC_atomic_default_mem_order, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the locaiton of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. OpenMPAtomicDefaultMemOrderClauseKind getAtomicDefaultMemOrderKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getAtomicDefaultMemOrderKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_atomic_default_mem_order; } }; /// This represents 'schedule' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for schedule(static, 3) /// \endcode /// In this example directive '#pragma omp for' has 'schedule' clause with /// arguments 'static' and '3'. class OMPScheduleClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'schedule' clause. OpenMPScheduleClauseKind Kind = OMPC_SCHEDULE_unknown; /// Modifiers for 'schedule' clause. enum {FIRST, SECOND, NUM_MODIFIERS}; OpenMPScheduleClauseModifier Modifiers[NUM_MODIFIERS]; /// Locations of modifiers. SourceLocation ModifiersLoc[NUM_MODIFIERS]; /// Start location of the schedule ind in source code. SourceLocation KindLoc; /// Location of ',' (if any). SourceLocation CommaLoc; /// Chunk size. Expr *ChunkSize = nullptr; /// Set schedule kind. /// /// \param K Schedule kind. void setScheduleKind(OpenMPScheduleClauseKind K) { Kind = K; } /// Set the first schedule modifier. /// /// \param M Schedule modifier. void setFirstScheduleModifier(OpenMPScheduleClauseModifier M) { Modifiers[FIRST] = M; } /// Set the second schedule modifier. /// /// \param M Schedule modifier. void setSecondScheduleModifier(OpenMPScheduleClauseModifier M) { Modifiers[SECOND] = M; } /// Set location of the first schedule modifier. void setFirstScheduleModifierLoc(SourceLocation Loc) { ModifiersLoc[FIRST] = Loc; } /// Set location of the second schedule modifier. void setSecondScheduleModifierLoc(SourceLocation Loc) { ModifiersLoc[SECOND] = Loc; } /// Set schedule modifier location. /// /// \param M Schedule modifier location. void setScheduleModifer(OpenMPScheduleClauseModifier M) { if (Modifiers[FIRST] == OMPC_SCHEDULE_MODIFIER_unknown) Modifiers[FIRST] = M; else { assert(Modifiers[SECOND] == OMPC_SCHEDULE_MODIFIER_unknown); Modifiers[SECOND] = M; } } /// Sets the location of '('. /// /// \param Loc Location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set schedule kind start location. /// /// \param KLoc Schedule kind location. void setScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } /// Set location of ','. /// /// \param Loc Location of ','. void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; } /// Set chunk size. /// /// \param E Chunk size. void setChunkSize(Expr *E) { ChunkSize = E; } public: /// Build 'schedule' clause with schedule kind \a Kind and chunk size /// expression \a ChunkSize. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param CommaLoc Location of ','. /// \param EndLoc Ending location of the clause. /// \param Kind Schedule kind. /// \param ChunkSize Chunk size. /// \param HelperChunkSize Helper chunk size for combined directives. /// \param M1 The first modifier applied to 'schedule' clause. /// \param M1Loc Location of the first modifier /// \param M2 The second modifier applied to 'schedule' clause. /// \param M2Loc Location of the second modifier OMPScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KLoc, SourceLocation CommaLoc, SourceLocation EndLoc, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, Stmt *HelperChunkSize, OpenMPScheduleClauseModifier M1, SourceLocation M1Loc, OpenMPScheduleClauseModifier M2, SourceLocation M2Loc) : OMPClause(llvm::omp::OMPC_schedule, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Kind(Kind), KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) { setPreInitStmt(HelperChunkSize); Modifiers[FIRST] = M1; Modifiers[SECOND] = M2; ModifiersLoc[FIRST] = M1Loc; ModifiersLoc[SECOND] = M2Loc; } /// Build an empty clause. explicit OMPScheduleClause() : OMPClause(llvm::omp::OMPC_schedule, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) { Modifiers[FIRST] = OMPC_SCHEDULE_MODIFIER_unknown; Modifiers[SECOND] = OMPC_SCHEDULE_MODIFIER_unknown; } /// Get kind of the clause. OpenMPScheduleClauseKind getScheduleKind() const { return Kind; } /// Get the first modifier of the clause. OpenMPScheduleClauseModifier getFirstScheduleModifier() const { return Modifiers[FIRST]; } /// Get the second modifier of the clause. OpenMPScheduleClauseModifier getSecondScheduleModifier() const { return Modifiers[SECOND]; } /// Get location of '('. SourceLocation getLParenLoc() { return LParenLoc; } /// Get kind location. SourceLocation getScheduleKindLoc() { return KindLoc; } /// Get the first modifier location. SourceLocation getFirstScheduleModifierLoc() const { return ModifiersLoc[FIRST]; } /// Get the second modifier location. SourceLocation getSecondScheduleModifierLoc() const { return ModifiersLoc[SECOND]; } /// Get location of ','. SourceLocation getCommaLoc() { return CommaLoc; } /// Get chunk size. Expr *getChunkSize() { return ChunkSize; } /// Get chunk size. const Expr *getChunkSize() const { return ChunkSize; } child_range children() { return child_range(reinterpret_cast<Stmt **>(&ChunkSize), reinterpret_cast<Stmt **>(&ChunkSize) + 1); } const_child_range children() const { auto Children = const_cast<OMPScheduleClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_schedule; } }; /// This represents 'ordered' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for ordered (2) /// \endcode /// In this example directive '#pragma omp for' has 'ordered' clause with /// parameter 2. class OMPOrderedClause final : public OMPClause, private llvm::TrailingObjects<OMPOrderedClause, Expr *> { friend class OMPClauseReader; friend TrailingObjects; /// Location of '('. SourceLocation LParenLoc; /// Number of for-loops. Stmt *NumForLoops = nullptr; /// Real number of loops. unsigned NumberOfLoops = 0; /// Build 'ordered' clause. /// /// \param Num Expression, possibly associated with this clause. /// \param NumLoops Number of loops, associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPOrderedClause(Expr *Num, unsigned NumLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_ordered, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num), NumberOfLoops(NumLoops) {} /// Build an empty clause. explicit OMPOrderedClause(unsigned NumLoops) : OMPClause(llvm::omp::OMPC_ordered, SourceLocation(), SourceLocation()), NumberOfLoops(NumLoops) {} /// Set the number of associated for-loops. void setNumForLoops(Expr *Num) { NumForLoops = Num; } public: /// Build 'ordered' clause. /// /// \param Num Expression, possibly associated with this clause. /// \param NumLoops Number of loops, associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. static OMPOrderedClause *Create(const ASTContext &C, Expr *Num, unsigned NumLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Build an empty clause. static OMPOrderedClause* CreateEmpty(const ASTContext &C, unsigned NumLoops); /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return the number of associated for-loops. Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); } /// Set number of iterations for the specified loop. void setLoopNumIterations(unsigned NumLoop, Expr *NumIterations); /// Get number of iterations for all the loops. ArrayRef<Expr *> getLoopNumIterations() const; /// Set loop counter for the specified loop. void setLoopCounter(unsigned NumLoop, Expr *Counter); /// Get loops counter for the specified loop. Expr *getLoopCounter(unsigned NumLoop); const Expr *getLoopCounter(unsigned NumLoop) const; child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); } const_child_range children() const { return const_child_range(&NumForLoops, &NumForLoops + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_ordered; } }; /// This represents 'nowait' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for nowait /// \endcode /// In this example directive '#pragma omp for' has 'nowait' clause. class OMPNowaitClause : public OMPClause { public: /// Build 'nowait' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_nowait, StartLoc, EndLoc) {} /// Build an empty clause. OMPNowaitClause() : OMPClause(llvm::omp::OMPC_nowait, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nowait; } }; /// This represents 'untied' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task untied /// \endcode /// In this example directive '#pragma omp task' has 'untied' clause. class OMPUntiedClause : public OMPClause { public: /// Build 'untied' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_untied, StartLoc, EndLoc) {} /// Build an empty clause. OMPUntiedClause() : OMPClause(llvm::omp::OMPC_untied, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_untied; } }; /// This represents 'mergeable' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp task mergeable /// \endcode /// In this example directive '#pragma omp task' has 'mergeable' clause. class OMPMergeableClause : public OMPClause { public: /// Build 'mergeable' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_mergeable, StartLoc, EndLoc) {} /// Build an empty clause. OMPMergeableClause() : OMPClause(llvm::omp::OMPC_mergeable, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_mergeable; } }; /// This represents 'read' clause in the '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic read /// \endcode /// In this example directive '#pragma omp atomic' has 'read' clause. class OMPReadClause : public OMPClause { public: /// Build 'read' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_read, StartLoc, EndLoc) {} /// Build an empty clause. OMPReadClause() : OMPClause(llvm::omp::OMPC_read, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_read; } }; /// This represents 'write' clause in the '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic write /// \endcode /// In this example directive '#pragma omp atomic' has 'write' clause. class OMPWriteClause : public OMPClause { public: /// Build 'write' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_write, StartLoc, EndLoc) {} /// Build an empty clause. OMPWriteClause() : OMPClause(llvm::omp::OMPC_write, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_write; } }; /// This represents 'update' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic update /// \endcode /// In this example directive '#pragma omp atomic' has 'update' clause. /// Also, this class represents 'update' clause in '#pragma omp depobj' /// directive. /// /// \code /// #pragma omp depobj(a) update(in) /// \endcode /// In this example directive '#pragma omp depobj' has 'update' clause with 'in' /// dependence kind. class OMPUpdateClause final : public OMPClause, private llvm::TrailingObjects<OMPUpdateClause, SourceLocation, OpenMPDependClauseKind> { friend class OMPClauseReader; friend TrailingObjects; /// true if extended version of the clause for 'depobj' directive. bool IsExtended = false; /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<SourceLocation>) const { // 2 locations: for '(' and argument location. return IsExtended ? 2 : 0; } /// Sets the the location of '(' in clause for 'depobj' directive. void setLParenLoc(SourceLocation Loc) { assert(IsExtended && "Expected extended clause."); *getTrailingObjects<SourceLocation>() = Loc; } /// Sets the the location of '(' in clause for 'depobj' directive. void setArgumentLoc(SourceLocation Loc) { assert(IsExtended && "Expected extended clause."); *std::next(getTrailingObjects<SourceLocation>(), 1) = Loc; } /// Sets the dependence kind for the clause for 'depobj' directive. void setDependencyKind(OpenMPDependClauseKind DK) { assert(IsExtended && "Expected extended clause."); *getTrailingObjects<OpenMPDependClauseKind>() = DK; } /// Build 'update' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc, bool IsExtended) : OMPClause(llvm::omp::OMPC_update, StartLoc, EndLoc), IsExtended(IsExtended) {} /// Build an empty clause. OMPUpdateClause(bool IsExtended) : OMPClause(llvm::omp::OMPC_update, SourceLocation(), SourceLocation()), IsExtended(IsExtended) {} public: /// Creates clause for 'atomic' directive. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. static OMPUpdateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Creates clause for 'depobj' directive. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ArgumentLoc Location of the argument. /// \param DK Dependence kind. /// \param EndLoc Ending location of the clause. static OMPUpdateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ArgumentLoc, OpenMPDependClauseKind DK, SourceLocation EndLoc); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param IsExtended true if extended clause for 'depobj' directive must be /// created. static OMPUpdateClause *CreateEmpty(const ASTContext &C, bool IsExtended); /// Checks if the clause is the extended clauses for 'depobj' directive. bool isExtended() const { return IsExtended; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } /// Gets the the location of '(' in clause for 'depobj' directive. SourceLocation getLParenLoc() const { assert(IsExtended && "Expected extended clause."); return *getTrailingObjects<SourceLocation>(); } /// Gets the the location of argument in clause for 'depobj' directive. SourceLocation getArgumentLoc() const { assert(IsExtended && "Expected extended clause."); return *std::next(getTrailingObjects<SourceLocation>(), 1); } /// Gets the dependence kind in clause for 'depobj' directive. OpenMPDependClauseKind getDependencyKind() const { assert(IsExtended && "Expected extended clause."); return *getTrailingObjects<OpenMPDependClauseKind>(); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_update; } }; /// This represents 'capture' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic capture /// \endcode /// In this example directive '#pragma omp atomic' has 'capture' clause. class OMPCaptureClause : public OMPClause { public: /// Build 'capture' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_capture, StartLoc, EndLoc) {} /// Build an empty clause. OMPCaptureClause() : OMPClause(llvm::omp::OMPC_capture, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_capture; } }; /// This represents 'seq_cst' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic seq_cst /// \endcode /// In this example directive '#pragma omp atomic' has 'seq_cst' clause. class OMPSeqCstClause : public OMPClause { public: /// Build 'seq_cst' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_seq_cst, StartLoc, EndLoc) {} /// Build an empty clause. OMPSeqCstClause() : OMPClause(llvm::omp::OMPC_seq_cst, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_seq_cst; } }; /// This represents 'acq_rel' clause in the '#pragma omp atomic|flush' /// directives. /// /// \code /// #pragma omp flush acq_rel /// \endcode /// In this example directive '#pragma omp flush' has 'acq_rel' clause. class OMPAcqRelClause final : public OMPClause { public: /// Build 'ack_rel' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_acq_rel, StartLoc, EndLoc) {} /// Build an empty clause. OMPAcqRelClause() : OMPClause(llvm::omp::OMPC_acq_rel, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_acq_rel; } }; /// This represents 'acquire' clause in the '#pragma omp atomic|flush' /// directives. /// /// \code /// #pragma omp flush acquire /// \endcode /// In this example directive '#pragma omp flush' has 'acquire' clause. class OMPAcquireClause final : public OMPClause { public: /// Build 'acquire' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_acquire, StartLoc, EndLoc) {} /// Build an empty clause. OMPAcquireClause() : OMPClause(llvm::omp::OMPC_acquire, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_acquire; } }; /// This represents 'release' clause in the '#pragma omp atomic|flush' /// directives. /// /// \code /// #pragma omp flush release /// \endcode /// In this example directive '#pragma omp flush' has 'release' clause. class OMPReleaseClause final : public OMPClause { public: /// Build 'release' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_release, StartLoc, EndLoc) {} /// Build an empty clause. OMPReleaseClause() : OMPClause(llvm::omp::OMPC_release, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_release; } }; /// This represents 'relaxed' clause in the '#pragma omp atomic' /// directives. /// /// \code /// #pragma omp atomic relaxed /// \endcode /// In this example directive '#pragma omp atomic' has 'relaxed' clause. class OMPRelaxedClause final : public OMPClause { public: /// Build 'relaxed' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_relaxed, StartLoc, EndLoc) {} /// Build an empty clause. OMPRelaxedClause() : OMPClause(llvm::omp::OMPC_relaxed, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_relaxed; } }; /// This represents clause 'private' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel private(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'private' /// with the variables 'a' and 'b'. class OMPPrivateClause final : public OMPVarListClause<OMPPrivateClause>, private llvm::TrailingObjects<OMPPrivateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPPrivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPPrivateClause>(llvm::omp::OMPC_private, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPPrivateClause(unsigned N) : OMPVarListClause<OMPPrivateClause>(llvm::omp::OMPC_private, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Sets the list of references to private copies with initializers for /// new private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// Gets the list of references to private copies with initializers for /// new private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param PrivateVL List of references to private copies with initializers. static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N); using private_copies_iterator = MutableArrayRef<Expr *>::iterator; using private_copies_const_iterator = ArrayRef<const Expr *>::iterator; using private_copies_range = llvm::iterator_range<private_copies_iterator>; using private_copies_const_range = llvm::iterator_range<private_copies_const_iterator>; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPPrivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_private; } }; /// This represents clause 'firstprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel firstprivate(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'firstprivate' /// with the variables 'a' and 'b'. class OMPFirstprivateClause final : public OMPVarListClause<OMPFirstprivateClause>, public OMPClauseWithPreInit, private llvm::TrailingObjects<OMPFirstprivateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPFirstprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFirstprivateClause>(llvm::omp::OMPC_firstprivate, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPreInit(this) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPFirstprivateClause(unsigned N) : OMPVarListClause<OMPFirstprivateClause>( llvm::omp::OMPC_firstprivate, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPreInit(this) {} /// Sets the list of references to private copies with initializers for /// new private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// Gets the list of references to private copies with initializers for /// new private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Sets the list of references to initializer variables for new /// private variables. /// \param VL List of references. void setInits(ArrayRef<Expr *> VL); /// Gets the list of references to initializer variables for new /// private variables. MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. /// \param PrivateVL List of references to private copies with initializers. /// \param InitVL List of references to auto generated variables used for /// initialization of a single array element. Used if firstprivate variable is /// of array type. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. static OMPFirstprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL, ArrayRef<Expr *> InitVL, Stmt *PreInit); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N); using private_copies_iterator = MutableArrayRef<Expr *>::iterator; using private_copies_const_iterator = ArrayRef<const Expr *>::iterator; using private_copies_range = llvm::iterator_range<private_copies_iterator>; using private_copies_const_range = llvm::iterator_range<private_copies_const_iterator>; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } using inits_iterator = MutableArrayRef<Expr *>::iterator; using inits_const_iterator = ArrayRef<const Expr *>::iterator; using inits_range = llvm::iterator_range<inits_iterator>; using inits_const_range = llvm::iterator_range<inits_const_iterator>; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPFirstprivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range used_children() const { auto Children = const_cast<OMPFirstprivateClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_firstprivate; } }; /// This represents clause 'lastprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd lastprivate(a,b) /// \endcode /// In this example directive '#pragma omp simd' has clause 'lastprivate' /// with the variables 'a' and 'b'. class OMPLastprivateClause final : public OMPVarListClause<OMPLastprivateClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPLastprivateClause, Expr *> { // There are 4 additional tail-allocated arrays at the end of the class: // 1. Contains list of pseudo variables with the default initialization for // each non-firstprivate variables. Used in codegen for initialization of // lastprivate copies. // 2. List of helper expressions for proper generation of assignment operation // required for lastprivate clause. This list represents private variables // (for arrays, single array element). // 3. List of helper expressions for proper generation of assignment operation // required for lastprivate clause. This list represents original variables // (for arrays, single array element). // 4. List of helper expressions that represents assignment operation: // \code // DstExprs = SrcExprs; // \endcode // Required for proper codegen of final assignment performed by the // lastprivate clause. friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Optional lastprivate kind, e.g. 'conditional', if specified by user. OpenMPLastprivateModifier LPKind; /// Optional location of the lasptrivate kind, if specified by user. SourceLocation LPKindLoc; /// Optional colon location, if specified by user. SourceLocation ColonLoc; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPLastprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, unsigned N) : OMPVarListClause<OMPLastprivateClause>(llvm::omp::OMPC_lastprivate, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), LPKind(LPKind), LPKindLoc(LPKindLoc), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPLastprivateClause(unsigned N) : OMPVarListClause<OMPLastprivateClause>( llvm::omp::OMPC_lastprivate, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Get the list of helper expressions for initialization of private /// copies for lastprivate variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent private variables (for arrays, single /// array element) in the final assignment statement performed by the /// lastprivate clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent original variables (for arrays, single /// array element) in the final assignment statement performed by the /// lastprivate clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign private copy of the variable to original variable. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } /// Sets lastprivate kind. void setKind(OpenMPLastprivateModifier Kind) { LPKind = Kind; } /// Sets location of the lastprivate kind. void setKindLoc(SourceLocation Loc) { LPKindLoc = Loc; } /// Sets colon symbol location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for lastprivate clause. This list represents /// private variables (for arrays, single array element). /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for lastprivate clause. This list represents /// original variables (for arrays, single array element). /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of final assignment performed by the /// lastprivate clause. /// \param LPKind Lastprivate kind, e.g. 'conditional'. /// \param LPKindLoc Location of the lastprivate kind. /// \param ColonLoc Location of the ':' symbol if lastprivate kind is used. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPLastprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPLastprivateClause *CreateEmpty(const ASTContext &C, unsigned N); /// Lastprivate kind. OpenMPLastprivateModifier getKind() const { return LPKind; } /// Returns the location of the lastprivate kind. SourceLocation getKindLoc() const { return LPKindLoc; } /// Returns the location of the ':' symbol, if any. SourceLocation getColonLoc() const { return ColonLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; /// Set list of helper expressions, required for generation of private /// copies of original lastprivate variables. void setPrivateCopies(ArrayRef<Expr *> PrivateCopies); helper_expr_const_range private_copies() const { return helper_expr_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } helper_expr_range private_copies() { return helper_expr_range(getPrivateCopies().begin(), getPrivateCopies().end()); } helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPLastprivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_lastprivate; } }; /// This represents clause 'shared' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel shared(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'shared' /// with the variables 'a' and 'b'. class OMPSharedClause final : public OMPVarListClause<OMPSharedClause>, private llvm::TrailingObjects<OMPSharedClause, Expr *> { friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPSharedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPSharedClause>(llvm::omp::OMPC_shared, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPSharedClause(unsigned N) : OMPVarListClause<OMPSharedClause>(llvm::omp::OMPC_shared, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPSharedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPSharedClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPSharedClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_shared; } }; /// This represents clause 'reduction' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'reduction' /// with operator '+' and the variables 'a' and 'b'. class OMPReductionClause final : public OMPVarListClause<OMPReductionClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPReductionClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Reduction modifier. OpenMPReductionClauseModifier Modifier = OMPC_REDUCTION_unknown; /// Reduction modifier location. SourceLocation ModifierLoc; /// Location of ':'. SourceLocation ColonLoc; /// Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// Name of custom operator. DeclarationNameInfo NameInfo; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ModifierLoc Modifier location. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. OMPReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, OpenMPReductionClauseModifier Modifier, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPReductionClause>(llvm::omp::OMPC_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), Modifier(Modifier), ModifierLoc(ModifierLoc), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPReductionClause(unsigned N) : OMPVarListClause<OMPReductionClause>(llvm::omp::OMPC_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Sets reduction modifier. void setModifier(OpenMPReductionClauseModifier M) { Modifier = M; } /// Sets location of the modifier. void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent private copy of the reduction /// variable. void setPrivates(ArrayRef<Expr *> Privates); /// Get the list of helper privates. MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent LHS expression in the final /// reduction expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent RHS expression in the final /// reduction expression performed by the reduction clause. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ModifierLoc Modifier location. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param Privates List of helper expressions for proper generation of /// private copies. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, OpenMPReductionClauseModifier Modifier, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPReductionClause *CreateEmpty(const ASTContext &C, unsigned N); /// Returns modifier. OpenMPReductionClauseModifier getModifier() const { return Modifier; } /// Returns modifier location. SourceLocation getModifierLoc() const { return ModifierLoc; } /// Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range privates() const { return helper_expr_const_range(getPrivates().begin(), getPrivates().end()); } helper_expr_range privates() { return helper_expr_range(getPrivates().begin(), getPrivates().end()); } helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPReductionClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range used_children() const { auto Children = const_cast<OMPReductionClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_reduction; } }; /// This represents clause 'task_reduction' in the '#pragma omp taskgroup' /// directives. /// /// \code /// #pragma omp taskgroup task_reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp taskgroup' has clause /// 'task_reduction' with operator '+' and the variables 'a' and 'b'. class OMPTaskReductionClause final : public OMPVarListClause<OMPTaskReductionClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPTaskReductionClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':'. SourceLocation ColonLoc; /// Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// Name of custom operator. DeclarationNameInfo NameInfo; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param ColonLoc Location of ':'. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. OMPTaskReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPTaskReductionClause>( llvm::omp::OMPC_task_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPTaskReductionClause(unsigned N) : OMPVarListClause<OMPTaskReductionClause>( llvm::omp::OMPC_task_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent private copy of the reduction variable. void setPrivates(ArrayRef<Expr *> Privates); /// Get the list of helper privates. MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent LHS expression in the final reduction /// expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent RHS expression in the final reduction /// expression performed by the reduction clause. Also, variables in these /// expressions are used for proper initialization of reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param Privates List of helper expressions for proper generation of /// private copies. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPTaskReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPTaskReductionClause *CreateEmpty(const ASTContext &C, unsigned N); /// Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range privates() const { return helper_expr_const_range(getPrivates().begin(), getPrivates().end()); } helper_expr_range privates() { return helper_expr_range(getPrivates().begin(), getPrivates().end()); } helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPTaskReductionClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_task_reduction; } }; /// This represents clause 'in_reduction' in the '#pragma omp task' directives. /// /// \code /// #pragma omp task in_reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp task' has clause 'in_reduction' with /// operator '+' and the variables 'a' and 'b'. class OMPInReductionClause final : public OMPVarListClause<OMPInReductionClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPInReductionClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':'. SourceLocation ColonLoc; /// Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// Name of custom operator. DeclarationNameInfo NameInfo; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param ColonLoc Location of ':'. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. OMPInReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPInReductionClause>(llvm::omp::OMPC_in_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPInReductionClause(unsigned N) : OMPVarListClause<OMPInReductionClause>( llvm::omp::OMPC_in_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent private copy of the reduction variable. void setPrivates(ArrayRef<Expr *> Privates); /// Get the list of helper privates. MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent LHS expression in the final reduction /// expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent RHS expression in the final reduction /// expression performed by the reduction clause. Also, variables in these /// expressions are used for proper initialization of reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } /// Set list of helper reduction taskgroup descriptors. void setTaskgroupDescriptors(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction taskgroup descriptors. MutableArrayRef<Expr *> getTaskgroupDescriptors() { return MutableArrayRef<Expr *>(getReductionOps().end(), varlist_size()); } ArrayRef<const Expr *> getTaskgroupDescriptors() const { return llvm::makeArrayRef(getReductionOps().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param Privates List of helper expressions for proper generation of /// private copies. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// \param TaskgroupDescriptors List of helper taskgroup descriptors for /// corresponding items in parent taskgroup task_reduction clause. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPInReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps, ArrayRef<Expr *> TaskgroupDescriptors, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPInReductionClause *CreateEmpty(const ASTContext &C, unsigned N); /// Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range privates() const { return helper_expr_const_range(getPrivates().begin(), getPrivates().end()); } helper_expr_range privates() { return helper_expr_range(getPrivates().begin(), getPrivates().end()); } helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_const_range taskgroup_descriptors() const { return helper_expr_const_range(getTaskgroupDescriptors().begin(), getTaskgroupDescriptors().end()); } helper_expr_range taskgroup_descriptors() { return helper_expr_range(getTaskgroupDescriptors().begin(), getTaskgroupDescriptors().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPInReductionClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_in_reduction; } }; /// This represents clause 'linear' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd linear(a,b : 2) /// \endcode /// In this example directive '#pragma omp simd' has clause 'linear' /// with variables 'a', 'b' and linear step '2'. class OMPLinearClause final : public OMPVarListClause<OMPLinearClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPLinearClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Modifier of 'linear' clause. OpenMPLinearClauseKind Modifier = OMPC_LINEAR_val; /// Location of linear modifier if any. SourceLocation ModifierLoc; /// Location of ':'. SourceLocation ColonLoc; /// Sets the linear step for clause. void setStep(Expr *Step) { *(getFinals().end()) = Step; } /// Sets the expression to calculate linear step for clause. void setCalcStep(Expr *CalcStep) { *(getFinals().end() + 1) = CalcStep; } /// Build 'linear' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. OMPLinearClause(SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPLinearClause>(llvm::omp::OMPC_linear, StartLoc, LParenLoc, EndLoc, NumVars), OMPClauseWithPostUpdate(this), Modifier(Modifier), ModifierLoc(ModifierLoc), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param NumVars Number of variables. explicit OMPLinearClause(unsigned NumVars) : OMPVarListClause<OMPLinearClause>(llvm::omp::OMPC_linear, SourceLocation(), SourceLocation(), SourceLocation(), NumVars), OMPClauseWithPostUpdate(this) {} /// Gets the list of initial values for linear variables. /// /// There are NumVars expressions with initial values allocated after the /// varlist, they are followed by NumVars update expressions (used to update /// the linear variable's value on current iteration) and they are followed by /// NumVars final expressions (used to calculate the linear variable's /// value after the loop body). After these lists, there are 2 helper /// expressions - linear step and a helper to calculate it before the /// loop body (used when the linear step is not constant): /// /// { Vars[] /* in OMPVarListClause */; Privates[]; Inits[]; Updates[]; /// Finals[]; Step; CalcStep; } MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Sets the list of update expressions for linear variables. MutableArrayRef<Expr *> getUpdates() { return MutableArrayRef<Expr *>(getInits().end(), varlist_size()); } ArrayRef<const Expr *> getUpdates() const { return llvm::makeArrayRef(getInits().end(), varlist_size()); } /// Sets the list of final update expressions for linear variables. MutableArrayRef<Expr *> getFinals() { return MutableArrayRef<Expr *>(getUpdates().end(), varlist_size()); } ArrayRef<const Expr *> getFinals() const { return llvm::makeArrayRef(getUpdates().end(), varlist_size()); } /// Gets the list of used expressions for linear variables. MutableArrayRef<Expr *> getUsedExprs() { return MutableArrayRef<Expr *>(getFinals().end() + 2, varlist_size() + 1); } ArrayRef<const Expr *> getUsedExprs() const { return llvm::makeArrayRef(getFinals().end() + 2, varlist_size() + 1); } /// Sets the list of the copies of original linear variables. /// \param PL List of expressions. void setPrivates(ArrayRef<Expr *> PL); /// Sets the list of the initial values for linear variables. /// \param IL List of expressions. void setInits(ArrayRef<Expr *> IL); public: /// Creates clause with a list of variables \a VL and a linear step /// \a Step. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Modifier Modifier of 'linear' clause. /// \param ModifierLoc Modifier location. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param PL List of private copies of original variables. /// \param IL List of initial values for the variables. /// \param Step Linear step. /// \param CalcStep Calculation of the linear step. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PL, ArrayRef<Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. static OMPLinearClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// Set modifier. void setModifier(OpenMPLinearClauseKind Kind) { Modifier = Kind; } /// Return modifier. OpenMPLinearClauseKind getModifier() const { return Modifier; } /// Set modifier location. void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } /// Return modifier location. SourceLocation getModifierLoc() const { return ModifierLoc; } /// Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Returns the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// Returns linear step. Expr *getStep() { return *(getFinals().end()); } /// Returns linear step. const Expr *getStep() const { return *(getFinals().end()); } /// Returns expression to calculate linear step. Expr *getCalcStep() { return *(getFinals().end() + 1); } /// Returns expression to calculate linear step. const Expr *getCalcStep() const { return *(getFinals().end() + 1); } /// Sets the list of update expressions for linear variables. /// \param UL List of expressions. void setUpdates(ArrayRef<Expr *> UL); /// Sets the list of final update expressions for linear variables. /// \param FL List of expressions. void setFinals(ArrayRef<Expr *> FL); /// Sets the list of used expressions for the linear clause. void setUsedExprs(ArrayRef<Expr *> UE); using privates_iterator = MutableArrayRef<Expr *>::iterator; using privates_const_iterator = ArrayRef<const Expr *>::iterator; using privates_range = llvm::iterator_range<privates_iterator>; using privates_const_range = llvm::iterator_range<privates_const_iterator>; privates_range privates() { return privates_range(getPrivates().begin(), getPrivates().end()); } privates_const_range privates() const { return privates_const_range(getPrivates().begin(), getPrivates().end()); } using inits_iterator = MutableArrayRef<Expr *>::iterator; using inits_const_iterator = ArrayRef<const Expr *>::iterator; using inits_range = llvm::iterator_range<inits_iterator>; using inits_const_range = llvm::iterator_range<inits_const_iterator>; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } using updates_iterator = MutableArrayRef<Expr *>::iterator; using updates_const_iterator = ArrayRef<const Expr *>::iterator; using updates_range = llvm::iterator_range<updates_iterator>; using updates_const_range = llvm::iterator_range<updates_const_iterator>; updates_range updates() { return updates_range(getUpdates().begin(), getUpdates().end()); } updates_const_range updates() const { return updates_const_range(getUpdates().begin(), getUpdates().end()); } using finals_iterator = MutableArrayRef<Expr *>::iterator; using finals_const_iterator = ArrayRef<const Expr *>::iterator; using finals_range = llvm::iterator_range<finals_iterator>; using finals_const_range = llvm::iterator_range<finals_const_iterator>; finals_range finals() { return finals_range(getFinals().begin(), getFinals().end()); } finals_const_range finals() const { return finals_const_range(getFinals().begin(), getFinals().end()); } using used_expressions_iterator = MutableArrayRef<Expr *>::iterator; using used_expressions_const_iterator = ArrayRef<const Expr *>::iterator; using used_expressions_range = llvm::iterator_range<used_expressions_iterator>; using used_expressions_const_range = llvm::iterator_range<used_expressions_const_iterator>; used_expressions_range used_expressions() { return finals_range(getUsedExprs().begin(), getUsedExprs().end()); } used_expressions_const_range used_expressions() const { return finals_const_range(getUsedExprs().begin(), getUsedExprs().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPLinearClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPLinearClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_linear; } }; /// This represents clause 'aligned' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd aligned(a,b : 8) /// \endcode /// In this example directive '#pragma omp simd' has clause 'aligned' /// with variables 'a', 'b' and alignment '8'. class OMPAlignedClause final : public OMPVarListClause<OMPAlignedClause>, private llvm::TrailingObjects<OMPAlignedClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':'. SourceLocation ColonLoc; /// Sets the alignment for clause. void setAlignment(Expr *A) { *varlist_end() = A; } /// Build 'aligned' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. OMPAlignedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(llvm::omp::OMPC_aligned, StartLoc, LParenLoc, EndLoc, NumVars), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param NumVars Number of variables. explicit OMPAlignedClause(unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(llvm::omp::OMPC_aligned, SourceLocation(), SourceLocation(), SourceLocation(), NumVars) {} public: /// Creates clause with a list of variables \a VL and alignment \a A. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param A Alignment. static OMPAlignedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, Expr *A); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. static OMPAlignedClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Returns the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// Returns alignment. Expr *getAlignment() { return *varlist_end(); } /// Returns alignment. const Expr *getAlignment() const { return *varlist_end(); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPAlignedClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_aligned; } }; /// This represents clause 'copyin' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel copyin(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'copyin' /// with the variables 'a' and 'b'. class OMPCopyinClause final : public OMPVarListClause<OMPCopyinClause>, private llvm::TrailingObjects<OMPCopyinClause, Expr *> { // Class has 3 additional tail allocated arrays: // 1. List of helper expressions for proper generation of assignment operation // required for copyin clause. This list represents sources. // 2. List of helper expressions for proper generation of assignment operation // required for copyin clause. This list represents destinations. // 3. List of helper expressions that represents assignment operation: // \code // DstExprs = SrcExprs; // \endcode // Required for proper codegen of propagation of master's thread values of // threadprivate variables to local instances of that variables in other // implicit threads. friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPCopyinClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyinClause>(llvm::omp::OMPC_copyin, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPCopyinClause(unsigned N) : OMPVarListClause<OMPCopyinClause>(llvm::omp::OMPC_copyin, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent source expression in the final /// assignment statement performed by the copyin clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent destination expression in the final /// assignment statement performed by the copyin clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign source helper expressions to destination helper expressions /// correspondingly. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for copyin clause. This list represents /// sources. /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for copyin clause. This list represents /// destinations. /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of propagation of master's thread values of /// threadprivate variables to local instances of that variables in other /// implicit threads. static OMPCopyinClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPCopyinClause *CreateEmpty(const ASTContext &C, unsigned N); using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPCopyinClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_copyin; } }; /// This represents clause 'copyprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp single copyprivate(a,b) /// \endcode /// In this example directive '#pragma omp single' has clause 'copyprivate' /// with the variables 'a' and 'b'. class OMPCopyprivateClause final : public OMPVarListClause<OMPCopyprivateClause>, private llvm::TrailingObjects<OMPCopyprivateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPCopyprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyprivateClause>(llvm::omp::OMPC_copyprivate, StartLoc, LParenLoc, EndLoc, N) { } /// Build an empty clause. /// /// \param N Number of variables. explicit OMPCopyprivateClause(unsigned N) : OMPVarListClause<OMPCopyprivateClause>( llvm::omp::OMPC_copyprivate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent source expression in the final /// assignment statement performed by the copyprivate clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent destination expression in the final /// assignment statement performed by the copyprivate clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign source helper expressions to destination helper expressions /// correspondingly. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// sources. /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// destinations. /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of final assignment performed by the /// copyprivate clause. static OMPCopyprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPCopyprivateClause *CreateEmpty(const ASTContext &C, unsigned N); using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPCopyprivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_copyprivate; } }; /// This represents implicit clause 'flush' for the '#pragma omp flush' /// directive. /// This clause does not exist by itself, it can be only as a part of 'omp /// flush' directive. This clause is introduced to keep the original structure /// of \a OMPExecutableDirective class and its derivatives and to use the /// existing infrastructure of clauses with the list of variables. /// /// \code /// #pragma omp flush(a,b) /// \endcode /// In this example directive '#pragma omp flush' has implicit clause 'flush' /// with the variables 'a' and 'b'. class OMPFlushClause final : public OMPVarListClause<OMPFlushClause>, private llvm::TrailingObjects<OMPFlushClause, Expr *> { friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPFlushClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFlushClause>(llvm::omp::OMPC_flush, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPFlushClause(unsigned N) : OMPVarListClause<OMPFlushClause>(llvm::omp::OMPC_flush, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPFlushClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPFlushClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPFlushClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_flush; } }; /// This represents implicit clause 'depobj' for the '#pragma omp depobj' /// directive. /// This clause does not exist by itself, it can be only as a part of 'omp /// depobj' directive. This clause is introduced to keep the original structure /// of \a OMPExecutableDirective class and its derivatives and to use the /// existing infrastructure of clauses with the list of variables. /// /// \code /// #pragma omp depobj(a) destroy /// \endcode /// In this example directive '#pragma omp depobj' has implicit clause 'depobj' /// with the depobj 'a'. class OMPDepobjClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Chunk size. Expr *Depobj = nullptr; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDepobjClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_depobj, StartLoc, EndLoc), LParenLoc(LParenLoc) {} /// Build an empty clause. /// explicit OMPDepobjClause() : OMPClause(llvm::omp::OMPC_depobj, SourceLocation(), SourceLocation()) {} void setDepobj(Expr *E) { Depobj = E; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Creates clause. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param Depobj depobj expression associated with the 'depobj' directive. static OMPDepobjClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, Expr *Depobj); /// Creates an empty clause. /// /// \param C AST context. static OMPDepobjClause *CreateEmpty(const ASTContext &C); /// Returns depobj expression associated with the clause. Expr *getDepobj() { return Depobj; } const Expr *getDepobj() const { return Depobj; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } child_range children() { return child_range(reinterpret_cast<Stmt **>(&Depobj), reinterpret_cast<Stmt **>(&Depobj) + 1); } const_child_range children() const { auto Children = const_cast<OMPDepobjClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_depobj; } }; /// This represents implicit clause 'depend' for the '#pragma omp task' /// directive. /// /// \code /// #pragma omp task depend(in:a,b) /// \endcode /// In this example directive '#pragma omp task' with clause 'depend' with the /// variables 'a' and 'b' with dependency 'in'. class OMPDependClause final : public OMPVarListClause<OMPDependClause>, private llvm::TrailingObjects<OMPDependClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Dependency type (one of in, out, inout). OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; /// Dependency type location. SourceLocation DepLoc; /// Colon location. SourceLocation ColonLoc; /// Number of loops, associated with the depend clause. unsigned NumLoops = 0; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// \param NumLoops Number of loops that is associated with this depend /// clause. OMPDependClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N, unsigned NumLoops) : OMPVarListClause<OMPDependClause>(llvm::omp::OMPC_depend, StartLoc, LParenLoc, EndLoc, N), NumLoops(NumLoops) {} /// Build an empty clause. /// /// \param N Number of variables. /// \param NumLoops Number of loops that is associated with this depend /// clause. explicit OMPDependClause(unsigned N, unsigned NumLoops) : OMPVarListClause<OMPDependClause>(llvm::omp::OMPC_depend, SourceLocation(), SourceLocation(), SourceLocation(), N), NumLoops(NumLoops) {} /// Set dependency kind. void setDependencyKind(OpenMPDependClauseKind K) { DepKind = K; } /// Set dependency kind and its location. void setDependencyLoc(SourceLocation Loc) { DepLoc = Loc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Sets optional dependency modifier. void setModifier(Expr *DepModifier); public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param DepKind Dependency type. /// \param DepLoc Location of the dependency type. /// \param ColonLoc Colon location. /// \param VL List of references to the variables. /// \param NumLoops Number of loops that is associated with this depend /// clause. static OMPDependClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VL, unsigned NumLoops); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// \param NumLoops Number of loops that is associated with this depend /// clause. static OMPDependClause *CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops); /// Get dependency type. OpenMPDependClauseKind getDependencyKind() const { return DepKind; } /// Return optional depend modifier. Expr *getModifier(); const Expr *getModifier() const { return const_cast<OMPDependClause *>(this)->getModifier(); } /// Get dependency type location. SourceLocation getDependencyLoc() const { return DepLoc; } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } /// Get number of loops associated with the clause. unsigned getNumLoops() const { return NumLoops; } /// Set the loop data for the depend clauses with 'sink|source' kind of /// dependency. void setLoopData(unsigned NumLoop, Expr *Cnt); /// Get the loop data. Expr *getLoopData(unsigned NumLoop); const Expr *getLoopData(unsigned NumLoop) const; child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPDependClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_depend; } }; /// This represents 'device' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp target device(a) /// \endcode /// In this example directive '#pragma omp target' has clause 'device' /// with single expression 'a'. class OMPDeviceClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Device clause modifier. OpenMPDeviceClauseModifier Modifier = OMPC_DEVICE_unknown; /// Location of the modifier. SourceLocation ModifierLoc; /// Device number. Stmt *Device = nullptr; /// Set the device number. /// /// \param E Device number. void setDevice(Expr *E) { Device = E; } /// Sets modifier. void setModifier(OpenMPDeviceClauseModifier M) { Modifier = M; } /// Setst modifier location. void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } public: /// Build 'device' clause. /// /// \param Modifier Clause modifier. /// \param E Expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param ModifierLoc Modifier location. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_device, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Modifier(Modifier), ModifierLoc(ModifierLoc), Device(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPDeviceClause() : OMPClause(llvm::omp::OMPC_device, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return device number. Expr *getDevice() { return cast<Expr>(Device); } /// Return device number. Expr *getDevice() const { return cast<Expr>(Device); } /// Gets modifier. OpenMPDeviceClauseModifier getModifier() const { return Modifier; } /// Gets modifier location. SourceLocation getModifierLoc() const { return ModifierLoc; } child_range children() { return child_range(&Device, &Device + 1); } const_child_range children() const { return const_child_range(&Device, &Device + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_device; } }; /// This represents 'threads' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp ordered threads /// \endcode /// In this example directive '#pragma omp ordered' has simple 'threads' clause. class OMPThreadsClause : public OMPClause { public: /// Build 'threads' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_threads, StartLoc, EndLoc) {} /// Build an empty clause. OMPThreadsClause() : OMPClause(llvm::omp::OMPC_threads, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_threads; } }; /// This represents 'simd' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp ordered simd /// \endcode /// In this example directive '#pragma omp ordered' has simple 'simd' clause. class OMPSIMDClause : public OMPClause { public: /// Build 'simd' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_simd, StartLoc, EndLoc) {} /// Build an empty clause. OMPSIMDClause() : OMPClause(llvm::omp::OMPC_simd, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_simd; } }; /// Struct that defines common infrastructure to handle mappable /// expressions used in OpenMP clauses. class OMPClauseMappableExprCommon { public: /// Class that represents a component of a mappable expression. E.g. /// for an expression S.a, the first component is a declaration reference /// expression associated with 'S' and the second is a member expression /// associated with the field declaration 'a'. If the expression is an array /// subscript it may not have any associated declaration. In that case the /// associated declaration is set to nullptr. class MappableComponent { /// Expression associated with the component. Expr *AssociatedExpression = nullptr; /// Declaration associated with the declaration. If the component does /// not have a declaration (e.g. array subscripts or section), this is set /// to nullptr. ValueDecl *AssociatedDeclaration = nullptr; public: explicit MappableComponent() = default; explicit MappableComponent(Expr *AssociatedExpression, ValueDecl *AssociatedDeclaration) : AssociatedExpression(AssociatedExpression), AssociatedDeclaration( AssociatedDeclaration ? cast<ValueDecl>(AssociatedDeclaration->getCanonicalDecl()) : nullptr) {} Expr *getAssociatedExpression() const { return AssociatedExpression; } ValueDecl *getAssociatedDeclaration() const { return AssociatedDeclaration; } }; // List of components of an expression. This first one is the whole // expression and the last one is the base expression. using MappableExprComponentList = SmallVector<MappableComponent, 8>; using MappableExprComponentListRef = ArrayRef<MappableComponent>; // List of all component lists associated to the same base declaration. // E.g. if both 'S.a' and 'S.b' are a mappable expressions, each will have // their component list but the same base declaration 'S'. using MappableExprComponentLists = SmallVector<MappableExprComponentList, 8>; using MappableExprComponentListsRef = ArrayRef<MappableExprComponentList>; protected: // Return the total number of elements in a list of component lists. static unsigned getComponentsTotalNumber(MappableExprComponentListsRef ComponentLists); // Return the total number of elements in a list of declarations. All // declarations are expected to be canonical. static unsigned getUniqueDeclarationsTotalNumber(ArrayRef<const ValueDecl *> Declarations); }; /// This structure contains all sizes needed for by an /// OMPMappableExprListClause. struct OMPMappableExprListSizeTy { /// Number of expressions listed. unsigned NumVars; /// Number of unique base declarations. unsigned NumUniqueDeclarations; /// Number of component lists. unsigned NumComponentLists; /// Total number of expression components. unsigned NumComponents; OMPMappableExprListSizeTy() = default; OMPMappableExprListSizeTy(unsigned NumVars, unsigned NumUniqueDeclarations, unsigned NumComponentLists, unsigned NumComponents) : NumVars(NumVars), NumUniqueDeclarations(NumUniqueDeclarations), NumComponentLists(NumComponentLists), NumComponents(NumComponents) {} }; /// This represents clauses with a list of expressions that are mappable. /// Examples of these clauses are 'map' in /// '#pragma omp target [enter|exit] [data]...' directives, and 'to' and 'from /// in '#pragma omp target update...' directives. template <class T> class OMPMappableExprListClause : public OMPVarListClause<T>, public OMPClauseMappableExprCommon { friend class OMPClauseReader; /// Number of unique declarations in this clause. unsigned NumUniqueDeclarations; /// Number of component lists in this clause. unsigned NumComponentLists; /// Total number of components in this clause. unsigned NumComponents; /// C++ nested name specifier for the associated user-defined mapper. NestedNameSpecifierLoc MapperQualifierLoc; /// The associated user-defined mapper identifier information. DeclarationNameInfo MapperIdInfo; protected: /// Build a clause for \a NumUniqueDeclarations declarations, \a /// NumComponentLists total component lists, and \a NumComponents total /// components. /// /// \param K Kind of the clause. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. /// \param MapperQualifierLocPtr C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfoPtr The identifier of associated user-defined mapper. OMPMappableExprListClause( OpenMPClauseKind K, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes, NestedNameSpecifierLoc *MapperQualifierLocPtr = nullptr, DeclarationNameInfo *MapperIdInfoPtr = nullptr) : OMPVarListClause<T>(K, Locs.StartLoc, Locs.LParenLoc, Locs.EndLoc, Sizes.NumVars), NumUniqueDeclarations(Sizes.NumUniqueDeclarations), NumComponentLists(Sizes.NumComponentLists), NumComponents(Sizes.NumComponents) { if (MapperQualifierLocPtr) MapperQualifierLoc = *MapperQualifierLocPtr; if (MapperIdInfoPtr) MapperIdInfo = *MapperIdInfoPtr; } /// Get the unique declarations that are in the trailing objects of the /// class. MutableArrayRef<ValueDecl *> getUniqueDeclsRef() { return MutableArrayRef<ValueDecl *>( static_cast<T *>(this)->template getTrailingObjects<ValueDecl *>(), NumUniqueDeclarations); } /// Get the unique declarations that are in the trailing objects of the /// class. ArrayRef<ValueDecl *> getUniqueDeclsRef() const { return ArrayRef<ValueDecl *>( static_cast<const T *>(this) ->template getTrailingObjects<ValueDecl *>(), NumUniqueDeclarations); } /// Set the unique declarations that are in the trailing objects of the /// class. void setUniqueDecls(ArrayRef<ValueDecl *> UDs) { assert(UDs.size() == NumUniqueDeclarations && "Unexpected amount of unique declarations."); std::copy(UDs.begin(), UDs.end(), getUniqueDeclsRef().begin()); } /// Get the number of lists per declaration that are in the trailing /// objects of the class. MutableArrayRef<unsigned> getDeclNumListsRef() { return MutableArrayRef<unsigned>( static_cast<T *>(this)->template getTrailingObjects<unsigned>(), NumUniqueDeclarations); } /// Get the number of lists per declaration that are in the trailing /// objects of the class. ArrayRef<unsigned> getDeclNumListsRef() const { return ArrayRef<unsigned>( static_cast<const T *>(this)->template getTrailingObjects<unsigned>(), NumUniqueDeclarations); } /// Set the number of lists per declaration that are in the trailing /// objects of the class. void setDeclNumLists(ArrayRef<unsigned> DNLs) { assert(DNLs.size() == NumUniqueDeclarations && "Unexpected amount of list numbers."); std::copy(DNLs.begin(), DNLs.end(), getDeclNumListsRef().begin()); } /// Get the cumulative component lists sizes that are in the trailing /// objects of the class. They are appended after the number of lists. MutableArrayRef<unsigned> getComponentListSizesRef() { return MutableArrayRef<unsigned>( static_cast<T *>(this)->template getTrailingObjects<unsigned>() + NumUniqueDeclarations, NumComponentLists); } /// Get the cumulative component lists sizes that are in the trailing /// objects of the class. They are appended after the number of lists. ArrayRef<unsigned> getComponentListSizesRef() const { return ArrayRef<unsigned>( static_cast<const T *>(this)->template getTrailingObjects<unsigned>() + NumUniqueDeclarations, NumComponentLists); } /// Set the cumulative component lists sizes that are in the trailing /// objects of the class. void setComponentListSizes(ArrayRef<unsigned> CLSs) { assert(CLSs.size() == NumComponentLists && "Unexpected amount of component lists."); std::copy(CLSs.begin(), CLSs.end(), getComponentListSizesRef().begin()); } /// Get the components that are in the trailing objects of the class. MutableArrayRef<MappableComponent> getComponentsRef() { return MutableArrayRef<MappableComponent>( static_cast<T *>(this) ->template getTrailingObjects<MappableComponent>(), NumComponents); } /// Get the components that are in the trailing objects of the class. ArrayRef<MappableComponent> getComponentsRef() const { return ArrayRef<MappableComponent>( static_cast<const T *>(this) ->template getTrailingObjects<MappableComponent>(), NumComponents); } /// Set the components that are in the trailing objects of the class. /// This requires the list sizes so that it can also fill the original /// expressions, which are the first component of each list. void setComponents(ArrayRef<MappableComponent> Components, ArrayRef<unsigned> CLSs) { assert(Components.size() == NumComponents && "Unexpected amount of component lists."); assert(CLSs.size() == NumComponentLists && "Unexpected amount of list sizes."); std::copy(Components.begin(), Components.end(), getComponentsRef().begin()); } /// Fill the clause information from the list of declarations and /// associated component lists. void setClauseInfo(ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists) { // Perform some checks to make sure the data sizes are consistent with the // information available when the clause was created. assert(getUniqueDeclarationsTotalNumber(Declarations) == NumUniqueDeclarations && "Unexpected number of mappable expression info entries!"); assert(getComponentsTotalNumber(ComponentLists) == NumComponents && "Unexpected total number of components!"); assert(Declarations.size() == ComponentLists.size() && "Declaration and component lists size is not consistent!"); assert(Declarations.size() == NumComponentLists && "Unexpected declaration and component lists size!"); // Organize the components by declaration and retrieve the original // expression. Original expressions are always the first component of the // mappable component list. llvm::MapVector<ValueDecl *, SmallVector<MappableExprComponentListRef, 8>> ComponentListMap; { auto CI = ComponentLists.begin(); for (auto DI = Declarations.begin(), DE = Declarations.end(); DI != DE; ++DI, ++CI) { assert(!CI->empty() && "Invalid component list!"); ComponentListMap[*DI].push_back(*CI); } } // Iterators of the target storage. auto UniqueDeclarations = getUniqueDeclsRef(); auto UDI = UniqueDeclarations.begin(); auto DeclNumLists = getDeclNumListsRef(); auto DNLI = DeclNumLists.begin(); auto ComponentListSizes = getComponentListSizesRef(); auto CLSI = ComponentListSizes.begin(); auto Components = getComponentsRef(); auto CI = Components.begin(); // Variable to compute the accumulation of the number of components. unsigned PrevSize = 0u; // Scan all the declarations and associated component lists. for (auto &M : ComponentListMap) { // The declaration. auto *D = M.first; // The component lists. auto CL = M.second; // Initialize the entry. *UDI = D; ++UDI; *DNLI = CL.size(); ++DNLI; // Obtain the cumulative sizes and concatenate all the components in the // reserved storage. for (auto C : CL) { // Accumulate with the previous size. PrevSize += C.size(); // Save the size. *CLSI = PrevSize; ++CLSI; // Append components after the current components iterator. CI = std::copy(C.begin(), C.end(), CI); } } } /// Set the nested name specifier of associated user-defined mapper. void setMapperQualifierLoc(NestedNameSpecifierLoc NNSL) { MapperQualifierLoc = NNSL; } /// Set the name of associated user-defined mapper. void setMapperIdInfo(DeclarationNameInfo MapperId) { MapperIdInfo = MapperId; } /// Get the user-defined mapper references that are in the trailing objects of /// the class. MutableArrayRef<Expr *> getUDMapperRefs() { return llvm::makeMutableArrayRef<Expr *>( static_cast<T *>(this)->template getTrailingObjects<Expr *>() + OMPVarListClause<T>::varlist_size(), OMPVarListClause<T>::varlist_size()); } /// Get the user-defined mappers references that are in the trailing objects /// of the class. ArrayRef<Expr *> getUDMapperRefs() const { return llvm::makeArrayRef<Expr *>( static_cast<T *>(this)->template getTrailingObjects<Expr *>() + OMPVarListClause<T>::varlist_size(), OMPVarListClause<T>::varlist_size()); } /// Set the user-defined mappers that are in the trailing objects of the /// class. void setUDMapperRefs(ArrayRef<Expr *> DMDs) { assert(DMDs.size() == OMPVarListClause<T>::varlist_size() && "Unexpected number of user-defined mappers."); std::copy(DMDs.begin(), DMDs.end(), getUDMapperRefs().begin()); } public: /// Return the number of unique base declarations in this clause. unsigned getUniqueDeclarationsNum() const { return NumUniqueDeclarations; } /// Return the number of lists derived from the clause expressions. unsigned getTotalComponentListNum() const { return NumComponentLists; } /// Return the total number of components in all lists derived from the /// clause. unsigned getTotalComponentsNum() const { return NumComponents; } /// Gets the nested name specifier for associated user-defined mapper. NestedNameSpecifierLoc getMapperQualifierLoc() const { return MapperQualifierLoc; } /// Gets the name info for associated user-defined mapper. const DeclarationNameInfo &getMapperIdInfo() const { return MapperIdInfo; } /// Iterator that browse the components by lists. It also allows /// browsing components of a single declaration. class const_component_lists_iterator : public llvm::iterator_adaptor_base< const_component_lists_iterator, MappableExprComponentListRef::const_iterator, std::forward_iterator_tag, MappableComponent, ptrdiff_t, MappableComponent, MappableComponent> { // The declaration the iterator currently refers to. ArrayRef<ValueDecl *>::iterator DeclCur; // The list number associated with the current declaration. ArrayRef<unsigned>::iterator NumListsCur; // Remaining lists for the current declaration. unsigned RemainingLists = 0; // The cumulative size of the previous list, or zero if there is no previous // list. unsigned PrevListSize = 0; // The cumulative sizes of the current list - it will delimit the remaining // range of interest. ArrayRef<unsigned>::const_iterator ListSizeCur; ArrayRef<unsigned>::const_iterator ListSizeEnd; // Iterator to the end of the components storage. MappableExprComponentListRef::const_iterator End; public: /// Construct an iterator that scans all lists. explicit const_component_lists_iterator( ArrayRef<ValueDecl *> UniqueDecls, ArrayRef<unsigned> DeclsListNum, ArrayRef<unsigned> CumulativeListSizes, MappableExprComponentListRef Components) : const_component_lists_iterator::iterator_adaptor_base( Components.begin()), DeclCur(UniqueDecls.begin()), NumListsCur(DeclsListNum.begin()), ListSizeCur(CumulativeListSizes.begin()), ListSizeEnd(CumulativeListSizes.end()), End(Components.end()) { assert(UniqueDecls.size() == DeclsListNum.size() && "Inconsistent number of declarations and list sizes!"); if (!DeclsListNum.empty()) RemainingLists = *NumListsCur; } /// Construct an iterator that scan lists for a given declaration \a /// Declaration. explicit const_component_lists_iterator( const ValueDecl *Declaration, ArrayRef<ValueDecl *> UniqueDecls, ArrayRef<unsigned> DeclsListNum, ArrayRef<unsigned> CumulativeListSizes, MappableExprComponentListRef Components) : const_component_lists_iterator(UniqueDecls, DeclsListNum, CumulativeListSizes, Components) { // Look for the desired declaration. While we are looking for it, we // update the state so that we know the component where a given list // starts. for (; DeclCur != UniqueDecls.end(); ++DeclCur, ++NumListsCur) { if (*DeclCur == Declaration) break; assert(*NumListsCur > 0 && "No lists associated with declaration??"); // Skip the lists associated with the current declaration, but save the // last list size that was skipped. std::advance(ListSizeCur, *NumListsCur - 1); PrevListSize = *ListSizeCur; ++ListSizeCur; } // If we didn't find any declaration, advance the iterator to after the // last component and set remaining lists to zero. if (ListSizeCur == CumulativeListSizes.end()) { this->I = End; RemainingLists = 0u; return; } // Set the remaining lists with the total number of lists of the current // declaration. RemainingLists = *NumListsCur; // Adjust the list size end iterator to the end of the relevant range. ListSizeEnd = ListSizeCur; std::advance(ListSizeEnd, RemainingLists); // Given that the list sizes are cumulative, the index of the component // that start the list is the size of the previous list. std::advance(this->I, PrevListSize); } // Return the array with the current list. The sizes are cumulative, so the // array size is the difference between the current size and previous one. std::pair<const ValueDecl *, MappableExprComponentListRef> operator*() const { assert(ListSizeCur != ListSizeEnd && "Invalid iterator!"); return std::make_pair( *DeclCur, MappableExprComponentListRef(&*this->I, *ListSizeCur - PrevListSize)); } std::pair<const ValueDecl *, MappableExprComponentListRef> operator->() const { return **this; } // Skip the components of the current list. const_component_lists_iterator &operator++() { assert(ListSizeCur != ListSizeEnd && RemainingLists && "Invalid iterator!"); // If we don't have more lists just skip all the components. Otherwise, // advance the iterator by the number of components in the current list. if (std::next(ListSizeCur) == ListSizeEnd) { this->I = End; RemainingLists = 0; } else { std::advance(this->I, *ListSizeCur - PrevListSize); PrevListSize = *ListSizeCur; // We are done with a declaration, move to the next one. if (!(--RemainingLists)) { ++DeclCur; ++NumListsCur; RemainingLists = *NumListsCur; assert(RemainingLists && "No lists in the following declaration??"); } } ++ListSizeCur; return *this; } }; using const_component_lists_range = llvm::iterator_range<const_component_lists_iterator>; /// Iterators for all component lists. const_component_lists_iterator component_lists_begin() const { return const_component_lists_iterator( getUniqueDeclsRef(), getDeclNumListsRef(), getComponentListSizesRef(), getComponentsRef()); } const_component_lists_iterator component_lists_end() const { return const_component_lists_iterator( ArrayRef<ValueDecl *>(), ArrayRef<unsigned>(), ArrayRef<unsigned>(), MappableExprComponentListRef(getComponentsRef().end(), getComponentsRef().end())); } const_component_lists_range component_lists() const { return {component_lists_begin(), component_lists_end()}; } /// Iterators for component lists associated with the provided /// declaration. const_component_lists_iterator decl_component_lists_begin(const ValueDecl *VD) const { return const_component_lists_iterator( VD, getUniqueDeclsRef(), getDeclNumListsRef(), getComponentListSizesRef(), getComponentsRef()); } const_component_lists_iterator decl_component_lists_end() const { return component_lists_end(); } const_component_lists_range decl_component_lists(const ValueDecl *VD) const { return {decl_component_lists_begin(VD), decl_component_lists_end()}; } /// Iterators to access all the declarations, number of lists, list sizes, and /// components. using const_all_decls_iterator = ArrayRef<ValueDecl *>::iterator; using const_all_decls_range = llvm::iterator_range<const_all_decls_iterator>; const_all_decls_range all_decls() const { auto A = getUniqueDeclsRef(); return const_all_decls_range(A.begin(), A.end()); } using const_all_num_lists_iterator = ArrayRef<unsigned>::iterator; using const_all_num_lists_range = llvm::iterator_range<const_all_num_lists_iterator>; const_all_num_lists_range all_num_lists() const { auto A = getDeclNumListsRef(); return const_all_num_lists_range(A.begin(), A.end()); } using const_all_lists_sizes_iterator = ArrayRef<unsigned>::iterator; using const_all_lists_sizes_range = llvm::iterator_range<const_all_lists_sizes_iterator>; const_all_lists_sizes_range all_lists_sizes() const { auto A = getComponentListSizesRef(); return const_all_lists_sizes_range(A.begin(), A.end()); } using const_all_components_iterator = ArrayRef<MappableComponent>::iterator; using const_all_components_range = llvm::iterator_range<const_all_components_iterator>; const_all_components_range all_components() const { auto A = getComponentsRef(); return const_all_components_range(A.begin(), A.end()); } using mapperlist_iterator = MutableArrayRef<Expr *>::iterator; using mapperlist_const_iterator = ArrayRef<const Expr *>::iterator; using mapperlist_range = llvm::iterator_range<mapperlist_iterator>; using mapperlist_const_range = llvm::iterator_range<mapperlist_const_iterator>; mapperlist_iterator mapperlist_begin() { return getUDMapperRefs().begin(); } mapperlist_iterator mapperlist_end() { return getUDMapperRefs().end(); } mapperlist_const_iterator mapperlist_begin() const { return getUDMapperRefs().begin(); } mapperlist_const_iterator mapperlist_end() const { return getUDMapperRefs().end(); } mapperlist_range mapperlists() { return mapperlist_range(mapperlist_begin(), mapperlist_end()); } mapperlist_const_range mapperlists() const { return mapperlist_const_range(mapperlist_begin(), mapperlist_end()); } }; /// This represents clause 'map' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target map(a,b) /// \endcode /// In this example directive '#pragma omp target' has clause 'map' /// with the variables 'a' and 'b'. class OMPMapClause final : public OMPMappableExprListClause<OMPMapClause>, private llvm::TrailingObjects< OMPMapClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { // There are varlist_size() of expressions, and varlist_size() of // user-defined mappers. return 2 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } private: /// Map-type-modifiers for the 'map' clause. OpenMPMapModifierKind MapTypeModifiers[NumberOfOMPMapClauseModifiers] = { OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown}; /// Location of map-type-modifiers for the 'map' clause. SourceLocation MapTypeModifiersLoc[NumberOfOMPMapClauseModifiers]; /// Map type for the 'map' clause. OpenMPMapClauseKind MapType = OMPC_MAP_unknown; /// Is this an implicit map type or not. bool MapTypeIsImplicit = false; /// Location of the map type. SourceLocation MapLoc; /// Colon location. SourceLocation ColonLoc; /// Build a clause for \a NumVars listed expressions, \a /// NumUniqueDeclarations declarations, \a NumComponentLists total component /// lists, and \a NumComponents total expression components. /// /// \param MapModifiers Map-type-modifiers. /// \param MapModifiersLoc Locations of map-type-modifiers. /// \param MapperQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfo The identifier of associated user-defined mapper. /// \param MapType Map type. /// \param MapTypeIsImplicit Map type is inferred implicitly. /// \param MapLoc Location of the map type. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPMapClause(ArrayRef<OpenMPMapModifierKind> MapModifiers, ArrayRef<SourceLocation> MapModifiersLoc, NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, OpenMPMapClauseKind MapType, bool MapTypeIsImplicit, SourceLocation MapLoc, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_map, Locs, Sizes, &MapperQualifierLoc, &MapperIdInfo), MapType(MapType), MapTypeIsImplicit(MapTypeIsImplicit), MapLoc(MapLoc) { assert(llvm::array_lengthof(MapTypeModifiers) == MapModifiers.size() && "Unexpected number of map type modifiers."); llvm::copy(MapModifiers, std::begin(MapTypeModifiers)); assert(llvm::array_lengthof(MapTypeModifiersLoc) == MapModifiersLoc.size() && "Unexpected number of map type modifier locations."); llvm::copy(MapModifiersLoc, std::begin(MapTypeModifiersLoc)); } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPMapClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_map, OMPVarListLocTy(), Sizes) {} /// Set map-type-modifier for the clause. /// /// \param I index for map-type-modifier. /// \param T map-type-modifier for the clause. void setMapTypeModifier(unsigned I, OpenMPMapModifierKind T) { assert(I < NumberOfOMPMapClauseModifiers && "Unexpected index to store map type modifier, exceeds array size."); MapTypeModifiers[I] = T; } /// Set location for the map-type-modifier. /// /// \param I index for map-type-modifier location. /// \param TLoc map-type-modifier location. void setMapTypeModifierLoc(unsigned I, SourceLocation TLoc) { assert(I < NumberOfOMPMapClauseModifiers && "Index to store map type modifier location exceeds array size."); MapTypeModifiersLoc[I] = TLoc; } /// Set type for the clause. /// /// \param T Type for the clause. void setMapType(OpenMPMapClauseKind T) { MapType = T; } /// Set type location. /// /// \param TLoc Type location. void setMapLoc(SourceLocation TLoc) { MapLoc = TLoc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. /// \param UDMapperRefs References to user-defined mappers associated with /// expressions used in the clause. /// \param MapModifiers Map-type-modifiers. /// \param MapModifiersLoc Location of map-type-modifiers. /// \param UDMQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperId The identifier of associated user-defined mapper. /// \param Type Map type. /// \param TypeIsImplicit Map type is inferred implicitly. /// \param TypeLoc Location of the map type. static OMPMapClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists, ArrayRef<Expr *> UDMapperRefs, ArrayRef<OpenMPMapModifierKind> MapModifiers, ArrayRef<SourceLocation> MapModifiersLoc, NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId, OpenMPMapClauseKind Type, bool TypeIsImplicit, SourceLocation TypeLoc); /// Creates an empty clause with the place for \a NumVars original /// expressions, \a NumUniqueDeclarations declarations, \NumComponentLists /// lists, and \a NumComponents expression components. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPMapClause *CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); /// Fetches mapping kind for the clause. OpenMPMapClauseKind getMapType() const LLVM_READONLY { return MapType; } /// Is this an implicit map type? /// We have to capture 'IsMapTypeImplicit' from the parser for more /// informative error messages. It helps distinguish map(r) from /// map(tofrom: r), which is important to print more helpful error /// messages for some target directives. bool isImplicitMapType() const LLVM_READONLY { return MapTypeIsImplicit; } /// Fetches the map-type-modifier at 'Cnt' index of array of modifiers. /// /// \param Cnt index for map-type-modifier. OpenMPMapModifierKind getMapTypeModifier(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMapClauseModifiers && "Requested modifier exceeds the total number of modifiers."); return MapTypeModifiers[Cnt]; } /// Fetches the map-type-modifier location at 'Cnt' index of array of /// modifiers' locations. /// /// \param Cnt index for map-type-modifier location. SourceLocation getMapTypeModifierLoc(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMapClauseModifiers && "Requested modifier location exceeds total number of modifiers."); return MapTypeModifiersLoc[Cnt]; } /// Fetches ArrayRef of map-type-modifiers. ArrayRef<OpenMPMapModifierKind> getMapTypeModifiers() const LLVM_READONLY { return llvm::makeArrayRef(MapTypeModifiers); } /// Fetches ArrayRef of location of map-type-modifiers. ArrayRef<SourceLocation> getMapTypeModifiersLoc() const LLVM_READONLY { return llvm::makeArrayRef(MapTypeModifiersLoc); } /// Fetches location of clause mapping kind. SourceLocation getMapLoc() const LLVM_READONLY { return MapLoc; } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } child_range children() { return child_range( reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPMapClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { if (MapType == OMPC_MAP_to || MapType == OMPC_MAP_tofrom) return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { auto Children = const_cast<OMPMapClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_map; } }; /// This represents 'num_teams' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp teams num_teams(n) /// \endcode /// In this example directive '#pragma omp teams' has clause 'num_teams' /// with single expression 'n'. class OMPNumTeamsClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// NumTeams number. Stmt *NumTeams = nullptr; /// Set the NumTeams number. /// /// \param E NumTeams number. void setNumTeams(Expr *E) { NumTeams = E; } public: /// Build 'num_teams' clause. /// /// \param E Expression associated with this clause. /// \param HelperE Helper Expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPNumTeamsClause(Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_num_teams, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTeams(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPNumTeamsClause() : OMPClause(llvm::omp::OMPC_num_teams, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return NumTeams number. Expr *getNumTeams() { return cast<Expr>(NumTeams); } /// Return NumTeams number. Expr *getNumTeams() const { return cast<Expr>(NumTeams); } child_range children() { return child_range(&NumTeams, &NumTeams + 1); } const_child_range children() const { return const_child_range(&NumTeams, &NumTeams + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_num_teams; } }; /// This represents 'thread_limit' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp teams thread_limit(n) /// \endcode /// In this example directive '#pragma omp teams' has clause 'thread_limit' /// with single expression 'n'. class OMPThreadLimitClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// ThreadLimit number. Stmt *ThreadLimit = nullptr; /// Set the ThreadLimit number. /// /// \param E ThreadLimit number. void setThreadLimit(Expr *E) { ThreadLimit = E; } public: /// Build 'thread_limit' clause. /// /// \param E Expression associated with this clause. /// \param HelperE Helper Expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPThreadLimitClause(Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_thread_limit, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), ThreadLimit(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPThreadLimitClause() : OMPClause(llvm::omp::OMPC_thread_limit, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return ThreadLimit number. Expr *getThreadLimit() { return cast<Expr>(ThreadLimit); } /// Return ThreadLimit number. Expr *getThreadLimit() const { return cast<Expr>(ThreadLimit); } child_range children() { return child_range(&ThreadLimit, &ThreadLimit + 1); } const_child_range children() const { return const_child_range(&ThreadLimit, &ThreadLimit + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_thread_limit; } }; /// This represents 'priority' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp task priority(n) /// \endcode /// In this example directive '#pragma omp teams' has clause 'priority' with /// single expression 'n'. class OMPPriorityClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Priority number. Stmt *Priority = nullptr; /// Set the Priority number. /// /// \param E Priority number. void setPriority(Expr *E) { Priority = E; } public: /// Build 'priority' clause. /// /// \param Priority Expression associated with this clause. /// \param HelperPriority Helper priority for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPPriorityClause(Expr *Priority, Stmt *HelperPriority, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_priority, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Priority(Priority) { setPreInitStmt(HelperPriority, CaptureRegion); } /// Build an empty clause. OMPPriorityClause() : OMPClause(llvm::omp::OMPC_priority, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return Priority number. Expr *getPriority() { return cast<Expr>(Priority); } /// Return Priority number. Expr *getPriority() const { return cast<Expr>(Priority); } child_range children() { return child_range(&Priority, &Priority + 1); } const_child_range children() const { return const_child_range(&Priority, &Priority + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPPriorityClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_priority; } }; /// This represents 'grainsize' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp taskloop grainsize(4) /// \endcode /// In this example directive '#pragma omp taskloop' has clause 'grainsize' /// with single expression '4'. class OMPGrainsizeClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *Grainsize = nullptr; /// Set safelen. void setGrainsize(Expr *Size) { Grainsize = Size; } public: /// Build 'grainsize' clause. /// /// \param Size Expression associated with this clause. /// \param HelperSize Helper grainsize for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPGrainsizeClause(Expr *Size, Stmt *HelperSize, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_grainsize, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Grainsize(Size) { setPreInitStmt(HelperSize, CaptureRegion); } /// Build an empty clause. explicit OMPGrainsizeClause() : OMPClause(llvm::omp::OMPC_grainsize, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getGrainsize() const { return cast_or_null<Expr>(Grainsize); } child_range children() { return child_range(&Grainsize, &Grainsize + 1); } const_child_range children() const { return const_child_range(&Grainsize, &Grainsize + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPGrainsizeClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_grainsize; } }; /// This represents 'nogroup' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp taskloop nogroup /// \endcode /// In this example directive '#pragma omp taskloop' has 'nogroup' clause. class OMPNogroupClause : public OMPClause { public: /// Build 'nogroup' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_nogroup, StartLoc, EndLoc) {} /// Build an empty clause. OMPNogroupClause() : OMPClause(llvm::omp::OMPC_nogroup, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nogroup; } }; /// This represents 'num_tasks' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp taskloop num_tasks(4) /// \endcode /// In this example directive '#pragma omp taskloop' has clause 'num_tasks' /// with single expression '4'. class OMPNumTasksClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *NumTasks = nullptr; /// Set safelen. void setNumTasks(Expr *Size) { NumTasks = Size; } public: /// Build 'num_tasks' clause. /// /// \param Size Expression associated with this clause. /// \param HelperSize Helper grainsize for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPNumTasksClause(Expr *Size, Stmt *HelperSize, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_num_tasks, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTasks(Size) { setPreInitStmt(HelperSize, CaptureRegion); } /// Build an empty clause. explicit OMPNumTasksClause() : OMPClause(llvm::omp::OMPC_num_tasks, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getNumTasks() const { return cast_or_null<Expr>(NumTasks); } child_range children() { return child_range(&NumTasks, &NumTasks + 1); } const_child_range children() const { return const_child_range(&NumTasks, &NumTasks + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPNumTasksClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_num_tasks; } }; /// This represents 'hint' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp critical (name) hint(6) /// \endcode /// In this example directive '#pragma omp critical' has name 'name' and clause /// 'hint' with argument '6'. class OMPHintClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Hint expression of the 'hint' clause. Stmt *Hint = nullptr; /// Set hint expression. void setHint(Expr *H) { Hint = H; } public: /// Build 'hint' clause with expression \a Hint. /// /// \param Hint Hint expression. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_hint, StartLoc, EndLoc), LParenLoc(LParenLoc), Hint(Hint) {} /// Build an empty clause. OMPHintClause() : OMPClause(llvm::omp::OMPC_hint, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns number of threads. Expr *getHint() const { return cast_or_null<Expr>(Hint); } child_range children() { return child_range(&Hint, &Hint + 1); } const_child_range children() const { return const_child_range(&Hint, &Hint + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_hint; } }; /// This represents 'dist_schedule' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp distribute dist_schedule(static, 3) /// \endcode /// In this example directive '#pragma omp distribute' has 'dist_schedule' /// clause with arguments 'static' and '3'. class OMPDistScheduleClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'schedule' clause. OpenMPDistScheduleClauseKind Kind = OMPC_DIST_SCHEDULE_unknown; /// Start location of the schedule kind in source code. SourceLocation KindLoc; /// Location of ',' (if any). SourceLocation CommaLoc; /// Chunk size. Expr *ChunkSize = nullptr; /// Set schedule kind. /// /// \param K Schedule kind. void setDistScheduleKind(OpenMPDistScheduleClauseKind K) { Kind = K; } /// Sets the location of '('. /// /// \param Loc Location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set schedule kind start location. /// /// \param KLoc Schedule kind location. void setDistScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } /// Set location of ','. /// /// \param Loc Location of ','. void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; } /// Set chunk size. /// /// \param E Chunk size. void setChunkSize(Expr *E) { ChunkSize = E; } public: /// Build 'dist_schedule' clause with schedule kind \a Kind and chunk /// size expression \a ChunkSize. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param CommaLoc Location of ','. /// \param EndLoc Ending location of the clause. /// \param Kind DistSchedule kind. /// \param ChunkSize Chunk size. /// \param HelperChunkSize Helper chunk size for combined directives. OMPDistScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KLoc, SourceLocation CommaLoc, SourceLocation EndLoc, OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, Stmt *HelperChunkSize) : OMPClause(llvm::omp::OMPC_dist_schedule, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Kind(Kind), KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) { setPreInitStmt(HelperChunkSize); } /// Build an empty clause. explicit OMPDistScheduleClause() : OMPClause(llvm::omp::OMPC_dist_schedule, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Get kind of the clause. OpenMPDistScheduleClauseKind getDistScheduleKind() const { return Kind; } /// Get location of '('. SourceLocation getLParenLoc() { return LParenLoc; } /// Get kind location. SourceLocation getDistScheduleKindLoc() { return KindLoc; } /// Get location of ','. SourceLocation getCommaLoc() { return CommaLoc; } /// Get chunk size. Expr *getChunkSize() { return ChunkSize; } /// Get chunk size. const Expr *getChunkSize() const { return ChunkSize; } child_range children() { return child_range(reinterpret_cast<Stmt **>(&ChunkSize), reinterpret_cast<Stmt **>(&ChunkSize) + 1); } const_child_range children() const { auto Children = const_cast<OMPDistScheduleClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_dist_schedule; } }; /// This represents 'defaultmap' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp target defaultmap(tofrom: scalar) /// \endcode /// In this example directive '#pragma omp target' has 'defaultmap' clause of kind /// 'scalar' with modifier 'tofrom'. class OMPDefaultmapClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Modifiers for 'defaultmap' clause. OpenMPDefaultmapClauseModifier Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown; /// Locations of modifiers. SourceLocation ModifierLoc; /// A kind of the 'defaultmap' clause. OpenMPDefaultmapClauseKind Kind = OMPC_DEFAULTMAP_unknown; /// Start location of the defaultmap kind in source code. SourceLocation KindLoc; /// Set defaultmap kind. /// /// \param K Defaultmap kind. void setDefaultmapKind(OpenMPDefaultmapClauseKind K) { Kind = K; } /// Set the defaultmap modifier. /// /// \param M Defaultmap modifier. void setDefaultmapModifier(OpenMPDefaultmapClauseModifier M) { Modifier = M; } /// Set location of the defaultmap modifier. void setDefaultmapModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } /// Sets the location of '('. /// /// \param Loc Location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set defaultmap kind start location. /// /// \param KLoc Defaultmap kind location. void setDefaultmapKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } public: /// Build 'defaultmap' clause with defaultmap kind \a Kind /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param EndLoc Ending location of the clause. /// \param Kind Defaultmap kind. /// \param M The modifier applied to 'defaultmap' clause. /// \param MLoc Location of the modifier OMPDefaultmapClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KLoc, SourceLocation EndLoc, OpenMPDefaultmapClauseKind Kind, OpenMPDefaultmapClauseModifier M) : OMPClause(llvm::omp::OMPC_defaultmap, StartLoc, EndLoc), LParenLoc(LParenLoc), Modifier(M), ModifierLoc(MLoc), Kind(Kind), KindLoc(KLoc) {} /// Build an empty clause. explicit OMPDefaultmapClause() : OMPClause(llvm::omp::OMPC_defaultmap, SourceLocation(), SourceLocation()) {} /// Get kind of the clause. OpenMPDefaultmapClauseKind getDefaultmapKind() const { return Kind; } /// Get the modifier of the clause. OpenMPDefaultmapClauseModifier getDefaultmapModifier() const { return Modifier; } /// Get location of '('. SourceLocation getLParenLoc() { return LParenLoc; } /// Get kind location. SourceLocation getDefaultmapKindLoc() { return KindLoc; } /// Get the modifier location. SourceLocation getDefaultmapModifierLoc() const { return ModifierLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_defaultmap; } }; /// This represents clause 'to' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target update to(a,b) /// \endcode /// In this example directive '#pragma omp target update' has clause 'to' /// with the variables 'a' and 'b'. class OMPToClause final : public OMPMappableExprListClause<OMPToClause>, private llvm::TrailingObjects< OMPToClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param MapperQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfo The identifier of associated user-defined mapper. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPToClause(NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_to, Locs, Sizes, &MapperQualifierLoc, &MapperIdInfo) {} /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPToClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_to, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { // There are varlist_size() of expressions, and varlist_size() of // user-defined mappers. return 2 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. /// \param UDMapperRefs References to user-defined mappers associated with /// expressions used in the clause. /// \param UDMQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperId The identifier of associated user-defined mapper. static OMPToClause *Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists, ArrayRef<Expr *> UDMapperRefs, NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPToClause *CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPToClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_to; } }; /// This represents clause 'from' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target update from(a,b) /// \endcode /// In this example directive '#pragma omp target update' has clause 'from' /// with the variables 'a' and 'b'. class OMPFromClause final : public OMPMappableExprListClause<OMPFromClause>, private llvm::TrailingObjects< OMPFromClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param MapperQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfo The identifier of associated user-defined mapper. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPFromClause(NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_from, Locs, Sizes, &MapperQualifierLoc, &MapperIdInfo) {} /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPFromClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_from, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { // There are varlist_size() of expressions, and varlist_size() of // user-defined mappers. return 2 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. /// \param UDMapperRefs References to user-defined mappers associated with /// expressions used in the clause. /// \param UDMQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperId The identifier of associated user-defined mapper. static OMPFromClause *Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists, ArrayRef<Expr *> UDMapperRefs, NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPFromClause *CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPFromClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_from; } }; /// This represents clause 'use_device_ptr' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target data use_device_ptr(a,b) /// \endcode /// In this example directive '#pragma omp target data' has clause /// 'use_device_ptr' with the variables 'a' and 'b'. class OMPUseDevicePtrClause final : public OMPMappableExprListClause<OMPUseDevicePtrClause>, private llvm::TrailingObjects< OMPUseDevicePtrClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDevicePtrClause(const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_ptr, Locs, Sizes) { } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDevicePtrClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_ptr, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { return 3 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } /// Sets the list of references to private copies with initializers for new /// private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// Gets the list of references to private copies with initializers for new /// private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Sets the list of references to initializer variables for new private /// variables. /// \param VL List of references. void setInits(ArrayRef<Expr *> VL); /// Gets the list of references to initializer variables for new private /// variables. MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param PrivateVars Expressions referring to private copies. /// \param Inits Expressions referring to private copy initializers. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. static OMPUseDevicePtrClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<Expr *> PrivateVars, ArrayRef<Expr *> Inits, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); using private_copies_iterator = MutableArrayRef<Expr *>::iterator; using private_copies_const_iterator = ArrayRef<const Expr *>::iterator; using private_copies_range = llvm::iterator_range<private_copies_iterator>; using private_copies_const_range = llvm::iterator_range<private_copies_const_iterator>; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } using inits_iterator = MutableArrayRef<Expr *>::iterator; using inits_const_iterator = ArrayRef<const Expr *>::iterator; using inits_range = llvm::iterator_range<inits_iterator>; using inits_const_range = llvm::iterator_range<inits_const_iterator>; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPUseDevicePtrClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_use_device_ptr; } }; /// This represents clause 'is_device_ptr' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target is_device_ptr(a,b) /// \endcode /// In this example directive '#pragma omp target' has clause /// 'is_device_ptr' with the variables 'a' and 'b'. class OMPIsDevicePtrClause final : public OMPMappableExprListClause<OMPIsDevicePtrClause>, private llvm::TrailingObjects< OMPIsDevicePtrClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPIsDevicePtrClause(const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_is_device_ptr, Locs, Sizes) {} /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPIsDevicePtrClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_is_device_ptr, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { return varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. static OMPIsDevicePtrClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPIsDevicePtrClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_is_device_ptr; } }; /// This represents clause 'nontemporal' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp simd nontemporal(a) /// \endcode /// In this example directive '#pragma omp simd' has clause 'nontemporal' for /// the variable 'a'. class OMPNontemporalClause final : public OMPVarListClause<OMPNontemporalClause>, private llvm::TrailingObjects<OMPNontemporalClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPNontemporalClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPNontemporalClause>(llvm::omp::OMPC_nontemporal, StartLoc, LParenLoc, EndLoc, N) { } /// Build an empty clause. /// /// \param N Number of variables. explicit OMPNontemporalClause(unsigned N) : OMPVarListClause<OMPNontemporalClause>( llvm::omp::OMPC_nontemporal, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Get the list of privatied copies if the member expression was captured by /// one of the privatization clauses. MutableArrayRef<Expr *> getPrivateRefs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateRefs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPNontemporalClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPNontemporalClause *CreateEmpty(const ASTContext &C, unsigned N); /// Sets the list of references to private copies created in private clauses. /// \param VL List of references. void setPrivateRefs(ArrayRef<Expr *> VL); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPNontemporalClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range private_refs() { return child_range(reinterpret_cast<Stmt **>(getPrivateRefs().begin()), reinterpret_cast<Stmt **>(getPrivateRefs().end())); } const_child_range private_refs() const { auto Children = const_cast<OMPNontemporalClause *>(this)->private_refs(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nontemporal; } }; /// This represents 'order' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp simd order(concurrent) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'order' /// clause with kind 'concurrent'. class OMPOrderClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'default' clause. OpenMPOrderClauseKind Kind = OMPC_ORDER_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clause. /// /// \param K Argument of clause. void setKind(OpenMPOrderClauseKind K) { Kind = K; } /// Set argument location. /// /// \param KLoc Argument location. void setKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'order' clause with argument \p A ('concurrent'). /// /// \param A Argument of the clause ('concurrent'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPOrderClause(OpenMPOrderClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_order, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPOrderClause() : OMPClause(llvm::omp::OMPC_order, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. OpenMPOrderClauseKind getKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_order; } }; /// This represents 'destroy' clause in the '#pragma omp depobj' /// directive. /// /// \code /// #pragma omp depobj(a) destroy /// \endcode /// In this example directive '#pragma omp depobj' has 'destroy' clause. class OMPDestroyClause final : public OMPClause { public: /// Build 'destroy' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPDestroyClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_destroy, StartLoc, EndLoc) {} /// Build an empty clause. OMPDestroyClause() : OMPClause(llvm::omp::OMPC_destroy, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_destroy; } }; /// This represents 'detach' clause in the '#pragma omp task' directive. /// /// \code /// #pragma omp task detach(evt) /// \endcode /// In this example directive '#pragma omp detach' has simple 'detach' clause /// with the variable 'evt'. class OMPDetachClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Expression of the 'detach' clause. Stmt *Evt = nullptr; /// Set condition. void setEventHandler(Expr *E) { Evt = E; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Build 'detach' clause with event-handler \a Evt. /// /// \param Evt Event handler expression. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_detach, StartLoc, EndLoc), LParenLoc(LParenLoc), Evt(Evt) {} /// Build an empty clause. OMPDetachClause() : OMPClause(llvm::omp::OMPC_detach, SourceLocation(), SourceLocation()) {} /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns event-handler expression. Expr *getEventHandler() const { return cast_or_null<Expr>(Evt); } child_range children() { return child_range(&Evt, &Evt + 1); } const_child_range children() const { return const_child_range(&Evt, &Evt + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_detach; } }; /// This represents clause 'inclusive' in the '#pragma omp scan' directive. /// /// \code /// #pragma omp scan inclusive(a,b) /// \endcode /// In this example directive '#pragma omp scan' has clause 'inclusive' /// with the variables 'a' and 'b'. class OMPInclusiveClause final : public OMPVarListClause<OMPInclusiveClause>, private llvm::TrailingObjects<OMPInclusiveClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPInclusiveClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPInclusiveClause>(llvm::omp::OMPC_inclusive, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPInclusiveClause(unsigned N) : OMPVarListClause<OMPInclusiveClause>(llvm::omp::OMPC_inclusive, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. static OMPInclusiveClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPInclusiveClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPInclusiveClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_inclusive; } }; /// This represents clause 'exclusive' in the '#pragma omp scan' directive. /// /// \code /// #pragma omp scan exclusive(a,b) /// \endcode /// In this example directive '#pragma omp scan' has clause 'exclusive' /// with the variables 'a' and 'b'. class OMPExclusiveClause final : public OMPVarListClause<OMPExclusiveClause>, private llvm::TrailingObjects<OMPExclusiveClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPExclusiveClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPExclusiveClause>(llvm::omp::OMPC_exclusive, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPExclusiveClause(unsigned N) : OMPVarListClause<OMPExclusiveClause>(llvm::omp::OMPC_exclusive, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. static OMPExclusiveClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPExclusiveClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPExclusiveClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_exclusive; } }; /// This represents clause 'uses_allocators' in the '#pragma omp target'-based /// directives. /// /// \code /// #pragma omp target uses_allocators(default_allocator, my_allocator(traits)) /// \endcode /// In this example directive '#pragma omp target' has clause 'uses_allocators' /// with the allocators 'default_allocator' and user-defined 'my_allocator'. class OMPUsesAllocatorsClause final : public OMPClause, private llvm::TrailingObjects<OMPUsesAllocatorsClause, Expr *, SourceLocation> { public: /// Data for list of allocators. struct Data { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; private: friend class OMPClauseReader; friend TrailingObjects; enum class ExprOffsets { Allocator, AllocatorTraits, Total, }; enum class ParenLocsOffsets { LParen, RParen, Total, }; /// Location of '('. SourceLocation LParenLoc; /// Total number of allocators in the clause. unsigned NumOfAllocators = 0; /// Build clause. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of allocators asssociated with the clause. OMPUsesAllocatorsClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPClause(llvm::omp::OMPC_uses_allocators, StartLoc, EndLoc), LParenLoc(LParenLoc), NumOfAllocators(N) {} /// Build an empty clause. /// \param N Number of allocators asssociated with the clause. /// explicit OMPUsesAllocatorsClause(unsigned N) : OMPClause(llvm::omp::OMPC_uses_allocators, SourceLocation(), SourceLocation()), NumOfAllocators(N) {} unsigned numTrailingObjects(OverloadToken<Expr *>) const { return NumOfAllocators * static_cast<int>(ExprOffsets::Total); } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Sets the allocators data for the clause. void setAllocatorsData(ArrayRef<OMPUsesAllocatorsClause::Data> Data); public: /// Creates clause with a list of allocators \p Data. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param Data List of allocators. static OMPUsesAllocatorsClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<OMPUsesAllocatorsClause::Data> Data); /// Creates an empty clause with the place for \p N allocators. /// /// \param C AST context. /// \param N The number of allocators. static OMPUsesAllocatorsClause *CreateEmpty(const ASTContext &C, unsigned N); /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns number of allocators associated with the clause. unsigned getNumberOfAllocators() const { return NumOfAllocators; } /// Returns data for the specified allocator. OMPUsesAllocatorsClause::Data getAllocatorData(unsigned I) const; // Iterators child_range children() { Stmt **Begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); return child_range(Begin, Begin + NumOfAllocators * static_cast<int>(ExprOffsets::Total)); } const_child_range children() const { Stmt *const *Begin = reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>()); return const_child_range( Begin, Begin + NumOfAllocators * static_cast<int>(ExprOffsets::Total)); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_uses_allocators; } }; /// This class implements a simple visitor for OMPClause /// subclasses. template<class ImplClass, template <typename> class Ptr, typename RetTy> class OMPClauseVisitorBase { public: #define PTR(CLASS) Ptr<CLASS> #define DISPATCH(CLASS) \ return static_cast<ImplClass*>(this)->Visit##CLASS(static_cast<PTR(CLASS)>(S)) #define OMP_CLAUSE_CLASS(Enum, Str, Class) \ RetTy Visit ## Class (PTR(Class) S) { DISPATCH(Class); } #include "llvm/Frontend/OpenMP/OMPKinds.def" RetTy Visit(PTR(OMPClause) S) { // Top switch clause: visit each OMPClause. switch (S->getClauseKind()) { #define OMP_CLAUSE_CLASS(Enum, Str, Class) \ case llvm::omp::Clause::Enum: \ return Visit##Class(static_cast<PTR(Class)>(S)); #define OMP_CLAUSE_NO_CLASS(Enum, Str) \ case llvm::omp::Clause::Enum: \ break; #include "llvm/Frontend/OpenMP/OMPKinds.def" } } // Base case, ignore it. :) RetTy VisitOMPClause(PTR(OMPClause) Node) { return RetTy(); } #undef PTR #undef DISPATCH }; template <typename T> using const_ptr = std::add_pointer_t<std::add_const_t<T>>; template <class ImplClass, typename RetTy = void> class OMPClauseVisitor : public OMPClauseVisitorBase<ImplClass, std::add_pointer_t, RetTy> {}; template<class ImplClass, typename RetTy = void> class ConstOMPClauseVisitor : public OMPClauseVisitorBase <ImplClass, const_ptr, RetTy> {}; class OMPClausePrinter final : public OMPClauseVisitor<OMPClausePrinter> { raw_ostream &OS; const PrintingPolicy &Policy; /// Process clauses with list of variables. template <typename T> void VisitOMPClauseList(T *Node, char StartSym); public: OMPClausePrinter(raw_ostream &OS, const PrintingPolicy &Policy) : OS(OS), Policy(Policy) {} #define OMP_CLAUSE_CLASS(Enum, Str, Class) \ void Visit##Class(Class *S); #include "llvm/Frontend/OpenMP/OMPKinds.def" }; struct OMPTraitProperty { llvm::omp::TraitProperty Kind = llvm::omp::TraitProperty::invalid; }; struct OMPTraitSelector { Expr *ScoreOrCondition = nullptr; llvm::omp::TraitSelector Kind = llvm::omp::TraitSelector::invalid; llvm::SmallVector<OMPTraitProperty, 1> Properties; }; struct OMPTraitSet { llvm::omp::TraitSet Kind = llvm::omp::TraitSet::invalid; llvm::SmallVector<OMPTraitSelector, 2> Selectors; }; /// Helper data structure representing the traits in a match clause of an /// `declare variant` or `metadirective`. The outer level is an ordered /// collection of selector sets, each with an associated kind and an ordered /// collection of selectors. A selector has a kind, an optional score/condition, /// and an ordered collection of properties. class OMPTraitInfo { /// Private constructor accesible only by ASTContext. OMPTraitInfo() {} friend class ASTContext; public: /// Reconstruct a (partial) OMPTraitInfo object from a mangled name. OMPTraitInfo(StringRef MangledName); /// The outermost level of selector sets. llvm::SmallVector<OMPTraitSet, 2> Sets; bool anyScoreOrCondition( llvm::function_ref<bool(Expr *&, bool /* IsScore */)> Cond) { return llvm::any_of(Sets, [&](OMPTraitSet &Set) { return llvm::any_of( Set.Selectors, [&](OMPTraitSelector &Selector) { return Cond(Selector.ScoreOrCondition, /* IsScore */ Selector.Kind != llvm::omp::TraitSelector::user_condition); }); }); } /// Create a variant match info object from this trait info object. While the /// former is a flat representation the actual main difference is that the /// latter uses clang::Expr to store the score/condition while the former is /// independent of clang. Thus, expressions and conditions are evaluated in /// this method. void getAsVariantMatchInfo(ASTContext &ASTCtx, llvm::omp::VariantMatchInfo &VMI) const; /// Return a string representation identifying this context selector. std::string getMangledName() const; /// Print a human readable representation into \p OS. void print(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const; }; llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo &TI); llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo *TI); } // namespace clang #endif // LLVM_CLANG_AST_OPENMPCLAUSE_H
keepass_fmt_plug.c
/* KeePass cracker patch for JtR. Hacked together during May of * 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>. * * Support for cracking KeePass databases, which use key file(s), was added by * m3g9tr0n (Spiros Fraganastasis) and Dhiru Kholia in September of 2014. * * Support for all types of keyfile within Keepass 1.x ans Keepass 2.x was * added by Fist0urs <eddy.maaalou at gmail.com> * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>, * 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. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_KeePass; #elif FMT_REGISTERS_H john_register_one(&fmt_KeePass); #else #include "sha2.h" #include <string.h> #include "stdint.h" #include <assert.h> #include <errno.h> #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "aes.h" #include "twofish.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 1 #endif #endif #include "memdbg.h" #define FORMAT_LABEL "KeePass" #define FORMAT_NAME "" #define ALGORITHM_NAME "SHA256 AES 32/" ARCH_BITS_STR " " SHA2_LIB #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 0 #define BINARY_ALIGN MEM_ALIGN_NONE #define SALT_SIZE sizeof(struct custom_salt) #if ARCH_ALLOWS_UNALIGNED // Avoid a compiler bug, see #1284 #define SALT_ALIGN 1 #else // salt align of 4 was crashing on sparc due to the long long value. #define SALT_ALIGN sizeof(long long) #endif #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests KeePass_tests[] = { {"$keepass$*1*50000*124*60eed105dac456cfc37d89d950ca846e*72ffef7c0bc3698b8eca65184774f6cd91a9356d338e5140e47e319a87f5e46a*8725bdfd3580cf054a1564dc724aaffe*8e58cc08af2462ddffe2ee39735ad14b15e8cb96dc05ef70d8e64d475eca7bf5*1*752*71d7e65fb3e20b288da8cd582b5c2bc3b63162eef6894e5e92eea73f711fe86e7a7285d5ac9d5ffd07798b83673b06f34180b7f5f3d05222ebf909c67e6580c646bcb64ad039fcdc6f33178fe475739a562dc78012f6be3104da9af69e0e12c2c9c5cd7134bb99d5278f2738a40155acbe941ff2f88db18daf772c7b5fc1855ff9e93ceb35a1db2c30cabe97a96c58b07c16912b2e095e530cc8c24041e7d4876b842f2e7c6df41d08da8c5c4f2402dd3241c3367b6e6e06cd0fa369934e78a6aab1479756a15264af09e3c8e1037f07a58f70f4bf634737ff58725414db10d7b2f61a7ed69878bc0de8bb99f3795bf9980d87992848cd9b9abe0fa6205a117ab1dd5165cf11ffa10b765e8723251ea0907bbc5f3eef8cf1f08bb89e193842b40c95922f38c44d0c3197033a5c7c926a33687aa71c482c48381baa4a34a46b8a4f78715f42eccbc8df80ee3b43335d92bdeb3bb0667cf6da83a018e4c0cd5803004bf6c300b9bee029246d16bd817ff235fcc22bb8c729929499afbf90bf787e98479db5ff571d3d727059d34c1f14454ff5f0a1d2d025437c2d8db4a7be7b901c067b929a0028fe8bb74fa96cb84831ccd89138329708d12c76bd4f5f371e43d0a2d234e5db2b3d6d5164e773594ab201dc9498078b48d4303dd8a89bf81c76d1424084ebf8d96107cb2623fb1cb67617257a5c7c6e56a8614271256b9dd80c76b6d668de4ebe17574ad617f5b1133f45a6d8621e127fcc99d8e788c535da9f557d91903b4e388108f02e9539a681d42e61f8e2f8b06654d4dec308690902a5c76f55b3d79b7c9a0ce994494bc60eff79ff41debc3f2684f40fc912f09035aae022148238ba6f5cfb92f54a5fb28cbb417ff01f39cc464e95929fba5e19be0251bef59879303063e6392c3a49032af3d03d5c9027868d5d6a187698dd75dfc295d2789a0e6cf391a380cc625b0a49f3084f45558ac273b0bbe62a8614db194983b2e207cef7deb1fa6a0bd39b0215d72bf646b599f187ee0009b7b458bb4930a1aea55222099446a0250a975447ff52", "openwall"}, {"$keepass$*2*6000*222*e54497d3d9be3e310a817a13515225a87773ba71557a88673c34db824550be7b*d405c4f7e3c7b2b142fda44c3d55d3afab1c91a6aca7c81c1ff7e61b3f03be85*7eb45af0af777ecb57f0159b9ffa528b*0af7d9facefb20378e8666389de7586ea72e9527dc78bf5dfe5f1b455060a3e6*9b0d1893678dea77f88bf66e6986adbc5a8095e4a09c7e9744bad42ac49133a7", "password"}, {"$keepass$*1*50000*124*f7465d646bab0a86197fcf2b778ea9c1*ec24a474b0745f9ff1de44ac3e0a274dda83375ecec45eb9ddc40b524fb51df2*f7f17dd2a15c4cf13fb4c8a504298fb3*e7765dba9ed64686a2c0b712de95bd0051a20b331ea0f77133e6afbb9faa1479*1*608*e5802225bf18755620355ad67efa87335532197ce45ee8374a5d23478557414b110426904671c49b266672c02e334c4261d52a9a0723d050329319f8d3b06a6d9507e5b30c78823beea101f52bde5ecdb6b6d0d2627fc254678416b39d2ba43ebce229c0b25f8c530975bc617be602d36e95a6e83c99c7264d5cc994af762460942830ac06b03d30c84c000d01061a938c274d78d383040c8cf5e69e7fbbaf6b46a7061399087f1db2747cd83afdb2b36e6077cecdc3b5c3b3f29f3a1ef537e8c798f8d614f9866a19a53b463aa81632e9aca43ebff9c787ca20a416a4051f16e4ececb84ea853fcc48a988e2d77cb385a2add3b858a18ee73783695a093628a0082d928ffeea39db585a478647e29395fdf2e3e8f54dc5b8277712d8cf5e8a266780944889fb46408b8afb614c3b8e7152b8cc865368d0ae000404234c11c8a77ebc521326683c00967a474cf82336afd1cb8f867db5f6cc7f5c9ae755c0fd0b4c9554ad26bef0b10f0c70978746090034e16922ee9cf38eb251515117cc62da3a62a6fd8a5dab0c10e857b2e2489d2521e1903d6b107c16fd1bf6565fc2953ea3206481ab6c466dba43777076c58ada7cb1883043f4747b2b80731476057598054ea9ec9de1645b4034f6569f579e70a021cc0a490dfa703def725846d0693d7cb02dea430905470db56663953b81b72f7543d6db7713afbcc91919b23cff80290a1053f34516c0b2c7a1f4bec1718994563ae188c2f65e20378537f88be2ebc6c47fbadabbd33414ffa30f115be0abdc89182e0a77d8d5c258d9ec5005415890218eb456fdcb79f1b15031289a0909fc6d8ae48ca6d2d699b6e0cd2e76462", "crackthis"}, {"$keepass$*1*50000*124*e144905f9aa746e1b2c382c807125d02*dd08f46898a3e75c458a44f34ec5391d3f3eb62b24dbda3d5e486e36312168cc*376ae8d5e8430d0a18e7bb4a0baddf75*5fa8dfc2f440ad296f1562683d06bf2717ae7e8ed343a279f54292f9fc8229ab*1*608*3ce1e03a1452e44b609ebe7326db4ef133ca25c325cc7cc5795ef92358011e2d32a1cb7cadc6f412b1d0a09f67f1444dfec73ed770507683360962d26b0c2b0384bcf9aba2cf1b3e4b5d7083ceaf5f941a2b99ec68d574eb58fe79e94d90b81c8f1f0ccfd35b16d415e8e203c06138eb6a1144520ef98bcdb33d669d2ab4aef2ab739e6dbc3f2ea5c6eef8410ca1555262181d8379b516551eb9d6a23eeb515bd8ef12735a635b25743c1188642486dd1fa4544138a361bcfc108f689bfb90f81d9808adcbd509f057cdbfd1cd31ee8b542956292f9bcca21fabeacc9ba96b335223103a72f94d9b04bcba9d74fada62e0d5bf2da142e413a373ea3c97ff1d50109532f5d041c5f77bea28cdea00388ab9dd3afc72bc266ff44c34221d751738545056e83d7558cf02ffc6f5a57163526ffff9a7de1c6276d4815a812c165ef0293bb951bcbc2cf389d20e188a6c24d1bc5322ee0bc6972b765fb199b28d6e14c3b795bd5d7d4f0672352dfed4870cf59480bab0f39f2a20ac162e8365b6e3dcb4a7fec1baafcb8c806726a777c7a5832a0d1c12568c2d9cad8dc04b1ce3506dbc1bf9663d625cfccb2d3c1cb6b96eee0f34e019b0145e903feed4683abe2568f2c0007c02c57b43f4ee585f9760d5b04c8581e25421b6b5bb370a5b48965b64584b1ed444ea52101af2b818b71eb0f9ae7942117273a3aff127641e17779580b48168c5575a8d843a87dee1088e0fde62bb2100e5b2e178daa463aeaeb1d4ff0544445aab09a7bdc684bd948f21112004dcc678e9c5f8cf8ba6113244b7c72d544f37cbc6baed6ddc76b9ccba6480abfb79a80dda4cdf7e218f396a749b4e5f", "password"}, /* CMIYC 2013 "pro" hard hash */ {"$keepass$*2*6000*222*a279e37c38b0124559a83fa452a0269d56dc4119a5866d18e76f1f3fd536d64d*7ec7a06bc975ea2ae7c8dcb99e826a308564849b6b25d858cbbc78475af3733f*d477c849bf2278b7a1f626c81e343553*e61db922e9b77a161e9b674ddadfb8c660d61b5f68d97a3b1596ae94cfa9d169*7c80c7db9de77f176e86ba11697152c4c8f182bdb8133ad1bca22e9ec5bc275b", "Sh4RK%nAD0*"}, /* twofish version 1 hash from http://openwall.info/wiki/john/sample-non-hashes#KeePass */ {"$keepass$*1*50000*1*1ff21bd79aa8e9c3f439281a4ce6a97b*cfbdb00057ee0c9e889ca9d93b069ab5ae19f78852bc21aae4f60d0d325e0034*c1a7e6138a49a2dcfb3a84afbc1d918b*a704f9d060f0de5a070155d1d5a8727da92f404242cb3aa2b9aa53a145f87474*1*608*c2d3d18e416af56788d1c3e4257da9ce6e5dcad4db012d7422d17b4527bbb2bb994d9db03907ae01cc1565f5fd0729b930c9ee352426c57de5dee7e941e1d6aedeaf2b0e6509819385de9b4dd6a09979b3edfa0959a7186c422031e426f18d295c55ac616aabeec99f89e696be1d585950ef16a94ae610f2449cc3964bb63ec6043ef36c89117bc78e99e5fbf083b48cb84f85a964e8a037018b3afc2cc55fbe7d74cbdb53d5a54bcd202a1d0a342dbf48a8f7a24264cde8d800a506bf134008b1d8d9b8dd80c19511d9f43b3c23b19eb4a7dcf584f80c49961f73dcba3d2d0390a39a683ddcc8771b49cc3c673ea0aa902d075e25bc814608e2e6d1d6218a6379fd677bc5daaa18b6f5a021d2f661338ca8cc3645dc6cddb860af222a5cdb59a5e2a2c1921203344ced4e2154446239f6c1af8c1bace8207e0f519ea9c08db2f5d0bde0416b09ef6c530213e648641ae56c9af9fbdcb0a286cc4de121655697b9eb00c0fd89ed7269c3859eca20e0c7b60be8d2a1323eb915139cf90c55f9cff01a5bdf757e09ee6d64c2de9aec8d3ea42feeb67caf51b9ba1a80b435e271fdb7f9144ca31e41671768b2c5e8adf70245fdf52005de418efbe2a156d19eeb2ed9e97a0ddb133d11bd8655356d9d3edbbdbf9d0db345b2eb2c1f550ce070f5b0f8f8e58a6ffd52ae8089627dc4a0dac4b4846349066bfa0d2f395d2cb3871e57e353d622e0904a9f54a3e4706797d95b34619f792c15ab8efb3ac523becc3023f01aaad169bc08db8d01e2dd22eff8f6b4f7b741d196bc3de466590011e6d5c9703a19c07d96d26fe1ad93d0931454730ee1f3146428a126d1ed02763f827ff4", "twofish"}, /* keyfile test cases*/ {"$keepass$*1*6000*0*1a1d38235ccbeae4ca2a9edfbd3b290c*8e1e81b37a6161b6033fbd6dd350aaeaa0712cf2649fe40e3fbbaa4b61684f54*d9517d352aea00c2b7f57f1154b9c0a0*0a8ae9b13347402c242d7cde4d58d01f1e129287eaf62df768856bbb9d0633a1*1*1360*6555a7e9eca9d5a2c9504a5c888846f0a8902fa31e3dc90f8fcc118856d5daabcaaf4316c4d589e11cce5b9a209e9a7ec1db5b848a706c78f7c7dfac4fd9ea86ac15af500518766dbf4525ee7c1b477a8fec4abdd6f4ad36894ec5aee0c9a5662c5091ceb61b3aa99ff3eacd687ed797b0a1e8ceecd5c51456cb1f70dadf0fda190752e4efe4fb101d5fc5d7745ff01d68cb4c0cc32c6003f85c310e43d7d659748bfc260cbb329c4076c2c9948386c74bb967362a98d6490dbe340f5d440b557b105edd5561836fbb6894f4a1d9a5cd0182536a28f60ca268d682065f8f5226e24a07d635a3c4f04760094cee033fb2f7c3a0cbdf7f174d31c827f6911a75ca95b21332bb47ea6359aa2d70ff4b16e8481cd536e0ec4ba90963edda754b6e0e694855e4f266899b3dd2b0f74c3e688caa376b22810945249ac4e1c38e8d1093ce272ed45d26037a1fd6e0cfcdbdf096c8b2795ba736641bafe9938b6eb2b40ea347f9c49952c118d86ec671c065e3c94f0de2409fec2fde318ad7e6dd0189baf4fa0044fc1d2974b9dafb1608f4bca525706e44ca6af09e305ad29f5e4ba0831145713d5d8b6d6d955c4b5ca031e34b4292aee5383179e1e0afe92ee6565e69825c90bb5e79612a4ad4a3babbd4a75b5481ea710c93595781b71532c17730409482e6b59bb9831be4efadadf36eda5bc5fcf0f3541aaba6662807e531a3e28078f5960e50f80e624c5434b545c1232fdd64359f53b90d6635107f4f005ac02110eebdbdda4f2c92addd686059e9d799a55902526f87f78b8844e2000f82e7b5c8ba3a19fe26117c43f69ba26eee75cc385737791ca4554ce935af26c50331963e500605e87ac3602a76669bf6318e797ef01fe1c25e567cc864de11bd00f555fdf188648bf4179658e325be39a4050b7b01553422e5cd1bbaf5e8f75ce34f0e92f1253c880d4e77f484f14817e288f01efbfe1a8f8b90e9d18b86898856bdf3ee6b5754853cb99a746fa0b753f1a49f529a89d9a0c2fbd5365477be829190dbf491bc886f66ae1bfe014a7e23a420f76a4a0d0d5ebcea51dc0021651a6cdbe5c89a7ae8bfdae2e30d404c31790c0aba8791793ce3072adf21e5a3c5b5e4f9cea82ebff5070e13f94300d5688523ba2a142ae8f82f6ef940e69beba1d665ab17a2ae471500fc48ded336b27450f08dfe07fa5e556963f035a01950f43b2f649bf7f552e9ee7154f5ffdec109fd5bdf0e879d044ef4b78e590ac769efcdd7dad74228872af966d2e8d976336de1ee4289e933288b5b0b43195df1c248176ac944f5e99918dbc067f93d15e95602c9cb8246f378377785b7ebfee44f81b385a3e1c9c5276e4b477c4841af871e6b0e3f4387c58cea01fe2aff04df0f51ac93757172d7537ee0df51ec931564ed2c8a11a45da8c03644d0bc93a14d9f79555250b9c8245690bc1c72ea7e9104a9f570680f704c1f8759a65e210e1b9a855b46ed6801354175b27fc288a7bc39a2003f4400c124ec41d7f54f67be99f778895d9c3e33623a346021215a369487457e78322dbd71a3d969b3e22dfea987ac93d5c4f8252142824f5a67e54a2b1b78ea928fbb63653e122555f6c76150f2541bdad6524f69964c91e9175406d0b824e175e63c7677d990341ee69c4ca9612a05e3bd2ed304c45cd97051aaf0b63c0d917af8d01723e215bb93f816b51d79e29e4e885b98f8ca8320443503c07e67b4d546f544ffced62ef7298a8ac6175f77c180900f638466cd15d6511d7b16992a8e0674563c02fe7776079ee92739bc142a1e601b3aaee284f6f828656e43e58b93bcfd5f69b6aa8c003788d1ae88f569f64402d64e18cb8ffc2268013fe4da9ba7da557da3e259623168b7fd57cf0e4c8327bae66e02bc12978725022ef4cc03b4021d3a*1*64*3a96fb77fbbbca7336ee699f17be31fde552191128553c6d89bfce4035dc0af0", "choupinette"}, {"$keepass$*2*6000*222*aa511591cb50394d044f31abb2febdb2788c9ee41d78a53f3efe0f83fdd64e81*7ceab79302a794cef818d9426e53a78458f82e72575967c4fb3788d4bc685874*1c5c1c0c475ee2f22bd56e9c75cfd67c*e7bf79115c83a0236260c71c17a816f9bd9288a683eb4b5e0d48666c66e97774*53f26838a293b392bfde1ad21b444b834cf5c02155a1378ac496653b2f3779ec*1*64*98df4f35fe74c031992d81a639305c4520f303fd1ca4bb09b53e33032b44c46a", "kukudanlaplace"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int any_cracked, *cracked; static size_t cracked_size; static struct custom_salt { long long offset; int version; int isinline; int keyfilesize; int have_keyfile; int contentsize; // unsigned char contents[LINE_BUFFER_SIZE]; unsigned char contents[0x30000]; // We need to fix this in some other way, now that LINE_BUFFER_SIZE has been dropped so heavily! unsigned char final_randomseed[32]; unsigned char enc_iv[16]; unsigned char keyfile[32]; unsigned char contents_hash[32]; unsigned char transf_randomseed[32]; unsigned char expected_bytes[32]; uint32_t key_transf_rounds; int algorithm; // 1 for Twofish } *cur_salt; static void transform_key(char *masterkey, struct custom_salt *csp, unsigned char *final_key) { // First, hash the masterkey SHA256_CTX ctx; unsigned char hash[32]; unsigned char temphash[32]; int i; AES_KEY akey; SHA256_Init(&ctx); SHA256_Update(&ctx, masterkey, strlen(masterkey)); SHA256_Final(hash, &ctx); if(csp->version == 2 && cur_salt->have_keyfile == 0) { SHA256_Init(&ctx); SHA256_Update(&ctx, hash, 32); SHA256_Final(hash, &ctx); } memset(&akey, 0, sizeof(AES_KEY)); if(AES_set_encrypt_key(csp->transf_randomseed, 256, &akey) < 0) { fprintf(stderr, "AES_set_encrypt_key failed!\n"); } if (cur_salt->have_keyfile) { SHA256_CTX composite_ctx; SHA256_Init(&composite_ctx); SHA256_Update(&composite_ctx, hash, 32); memcpy(temphash, cur_salt->keyfile, 32); SHA256_Update(&composite_ctx, temphash, 32); SHA256_Final(hash, &composite_ctx); } // Next, encrypt the created hash i = csp->key_transf_rounds >> 2; while (i--) { AES_encrypt(hash, hash, &akey); AES_encrypt(hash, hash, &akey); AES_encrypt(hash, hash, &akey); AES_encrypt(hash, hash, &akey); AES_encrypt(hash+16, hash+16, &akey); AES_encrypt(hash+16, hash+16, &akey); AES_encrypt(hash+16, hash+16, &akey); AES_encrypt(hash+16, hash+16, &akey); } i = csp->key_transf_rounds & 3; while (i--) { AES_encrypt(hash, hash, &akey); AES_encrypt(hash+16, hash+16, &akey); } // Finally, hash it again... SHA256_Init(&ctx); SHA256_Update(&ctx, hash, 32); SHA256_Final(hash, &ctx); // ...and hash the result together with the randomseed SHA256_Init(&ctx); if(csp->version == 1) { SHA256_Update(&ctx, csp->final_randomseed, 16); } else { SHA256_Update(&ctx, csp->final_randomseed, 32); } SHA256_Update(&ctx, hash, 32); SHA256_Final(final_key, &ctx); } static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = 1; 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(self->params.max_keys_per_crypt, sizeof(*saved_key)); any_cracked = 0; cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt; cracked = mem_calloc(cracked_size, 1); Twofish_initialise(); } static void done(void) { MEM_FREE(cracked); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy; char *keeptr; char *p; int version, res, contentsize; if (strncmp(ciphertext, "$keepass$*", 10)) return 0; /* handle 'chopped' .pot lines */ if (ldr_isa_pot_source(ciphertext)) return 1; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += 10; if ((p = strtokm(ctcopy, "*")) == NULL) /* version */ goto err; if (!isdec(p)) goto err; version = atoi(p); if (version != 1 && version != 2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* rounds */ goto err; if (!isdec(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* offset */ goto err; if (!isdec(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* final random seed */ goto err; res = hexlenl(p); if (res != 32 && res != 64) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* transf random seed */ goto err; if (hexlenl(p) != 64) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* env_iv */ goto err; if (hexlenl(p) != 32) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* hash or expected bytes*/ goto err; if (hexlenl(p) != 64) goto err; if (version == 1) { if ((p = strtokm(NULL, "*")) == NULL) /* inline flag */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res != 1 && res != 2) { fprintf(stderr, "[!] Support for non-inlined data is currently missing from the " \ FORMAT_LABEL " format.\n"); fprintf(stderr, "See https://github.com/magnumripper/JohnTheRipper/issues/1026\n"); error(); } if (res == 1) { if ((p = strtokm(NULL, "*")) == NULL) /* content size */ goto err; if (!isdec(p)) goto err; contentsize = atoi(p); if ((p = strtokm(NULL, "*")) == NULL) /* content */ goto err; if (hexlenl(p) / 2 != contentsize) goto err; } p = strtokm(NULL, "*"); // keyfile handling if (p) { res = atoi(p); if (res == 1) { if ((p = strtokm(NULL, "*")) == NULL) goto err; res = atoi(p); if ((p = strtokm(NULL, "*")) == NULL) goto err; if (res != 64 && strlen(p) != 64) goto err; } } } else { if ((p = strtokm(NULL, "*")) == NULL) /* content */ goto err; if (hexlenl(p) != 64) goto err; p = strtokm(NULL, "*"); // keyfile handling if (p) { res = atoi(p); if (res == 1) { if ((p = strtokm(NULL, "*")) == NULL) goto err; res = atoi(p); if ((p = strtokm(NULL, "*")) == NULL) goto err; if (res != 64 && strlen(p) != 64) 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; char *p; int i; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += 10; /* skip over "$keepass$*" */ p = strtokm(ctcopy, "*"); cs.version = atoi(p); if(cs.version == 1) { p = strtokm(NULL, "*"); cs.key_transf_rounds = atoi(p); p = strtokm(NULL, "*"); // cs.offset = atoll(p); // Twofish handling hack! cs.algorithm = atoll(p); p = strtokm(NULL, "*"); for (i = 0; i < 16; i++) cs.final_randomseed[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); for (i = 0; i < 32; i++) cs.transf_randomseed[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); for (i = 0; i < 16; i++) cs.enc_iv[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); for (i = 0; i < 32; i++) cs.contents_hash[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.isinline = atoi(p); if(cs.isinline == 1) { p = strtokm(NULL, "*"); cs.contentsize = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.contentsize; i++) cs.contents[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; } p = strtokm(NULL, "*"); if (p) { /* keyfile handling */ p = strtokm(NULL, "*"); cs.keyfilesize = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < 32; i++) cs.keyfile[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; cs.have_keyfile = 1; } } else { p = strtokm(NULL, "*"); cs.key_transf_rounds = atoi(p); p = strtokm(NULL, "*"); // cs.offset = atoll(p); // Twofish handling hack cs.algorithm = atoll(p); p = strtokm(NULL, "*"); for (i = 0; i < 32; i++) cs.final_randomseed[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); for (i = 0; i < 32; i++) cs.transf_randomseed[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); for (i = 0; i < 16; i++) cs.enc_iv[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); for (i = 0; i < 32; i++) cs.expected_bytes[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); for (i = 0; i < 32; i++) cs.contents[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); if (p) { /* keyfile handling */ p = strtokm(NULL, "*"); cs.keyfilesize = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < 32; i++) cs.keyfile[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; cs.have_keyfile = 1; } } MEM_FREE(keeptr); if (cs.algorithm != 0 && cs.algorithm != 1) // offset hijacking! cs.algorithm = 0; // AES return (void *)&cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } 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 { unsigned char final_key[32]; //unsigned char decrypted_content[LINE_BUFFER_SIZE]; unsigned char decrypted_content[0x30000]; SHA256_CTX ctx; unsigned char iv[16]; unsigned char out[32]; int pad_byte; int datasize; AES_KEY akey; Twofish_key tkey; // derive and set decryption key transform_key(saved_key[index], cur_salt, final_key); if (cur_salt->algorithm == 0) { /* AES decrypt cur_salt->contents with final_key */ memcpy(iv, cur_salt->enc_iv, 16); memset(&akey, 0, sizeof(AES_KEY)); if(AES_set_decrypt_key(final_key, 256, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n"); } } else if (cur_salt->algorithm == 1) { memcpy(iv, cur_salt->enc_iv, 16); memset(&tkey, 0, sizeof(Twofish_key)); Twofish_prepare_key(final_key, 32, &tkey); } if (cur_salt->version == 1 && cur_salt->algorithm == 0) { AES_cbc_encrypt(cur_salt->contents, decrypted_content, cur_salt->contentsize, &akey, iv, AES_DECRYPT); pad_byte = decrypted_content[cur_salt->contentsize-1]; datasize = cur_salt->contentsize - pad_byte; SHA256_Init(&ctx); SHA256_Update(&ctx, decrypted_content, datasize); SHA256_Final(out, &ctx); if(!memcmp(out, cur_salt->contents_hash, 32)) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } else if (cur_salt->version == 2 && cur_salt->algorithm == 0) { AES_cbc_encrypt(cur_salt->contents, decrypted_content, 32, &akey, iv, AES_DECRYPT); if(!memcmp(decrypted_content, cur_salt->expected_bytes, 32)) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } else if (cur_salt->version == 1 && cur_salt->algorithm == 1) { /* KeePass 1.x with Twofish */ int crypto_size; crypto_size = Twofish_Decrypt(&tkey, cur_salt->contents, decrypted_content, cur_salt->contentsize, iv); datasize = crypto_size; // awesome, right? if (datasize <= cur_salt->contentsize && datasize > 0) { SHA256_Init(&ctx); SHA256_Update(&ctx, decrypted_content, datasize); SHA256_Final(out, &ctx); if(!memcmp(out, cur_salt->contents_hash, 32)) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } } else { // KeePass version 2 with Twofish is TODO. Twofish support under KeePass version 2 // requires a third-party plugin. See http://keepass.info/plugins.html for details. abort(); } } 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]; } static void KeePass_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 unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->key_transf_rounds; } /* * The version shouldn't have a significant impact * on performance. Nevertless, report it as the 2nd * "tunable cost". */ static unsigned int keepass_version(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->version; } struct fmt_main fmt_KeePass = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { "iteration count", "version", }, KeePass_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { iteration_count, keepass_version, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, KeePass_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
DRB037-truedepseconddimension-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. */ /* Only the outmost loop can be parallelized in this program. The inner loop has true dependence. Data race pair: b[i][j]@63:7 vs. b[i][j-1]@63:15 */ #include <stdlib.h> #include <stdio.h> double b[1000][1000]; int main(int argc, char* argv[]) { int i,j; int n=1000, m=1000; #pragma omp parallel for private(j) for (i=0;i<n;i++) #pragma omp parallel for simd for (j=1;j<m;j++) b[i][j]= i * m + j; #pragma omp parallel for simd private(j) for (i=0;i<n;i++) for (j=1;j<m;j++) b[i][j]=b[i][j-1]; #pragma omp parallel for private(j) ordered for (i=0;i<n;i++) #pragma omp parallel for simd ordered for (j=1;j<m;j++) #pragma omp ordered simd printf("%lf\n",b[i][j]); return 0; }
surface.h
#ifndef batoid_surface_h #define batoid_surface_h #include "rayVector.h" namespace batoid { #if defined(BATOID_GPU) #pragma omp declare target #endif class Surface { public: virtual ~Surface(); virtual const Surface* getDevPtr() const = 0; virtual double sag(double x, double y) const = 0; virtual void normal( double x, double y, double& nx, double& ny, double& nz ) const = 0; virtual bool timeToIntersect( const double x, const double y, const double z, const double vx, const double vy, const double vz, double& dt ) const; virtual void grad( double x, double y, double& dzdx, double& dzdy ) const; protected: Surface(); mutable Surface* _devPtr; private: #if defined(BATOID_GPU) void freeDevPtr() const; #endif }; #if defined(BATOID_GPU) #pragma omp end declare target #endif } #endif
stream-optimized.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 <stdlib.h> #include <stddef.h> #include <math.h> #include <float.h> #include <limits.h> #ifndef WIN32 #include <unistd.h> #include <sys/time.h> #else #include <Windows.h> #endif /*----------------------------------------------------------------------- * 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 // it turns out that massive static arrays make Emscripten blow up, as it // encodes their initializers naively. A ten million entry array gets a // ten million entry initializer. //static STREAM_TYPE a[STREAM_ARRAY_SIZE+OFFSET], // b[STREAM_ARRAY_SIZE+OFFSET], // c[STREAM_ARRAY_SIZE+OFFSET]; static STREAM_TYPE* 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(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; intptr_t j; STREAM_TYPE scalar; double t, times[4][NTIMES]; a = calloc(STREAM_ARRAY_SIZE + OFFSET, sizeof(STREAM_TYPE)); b = calloc(STREAM_ARRAY_SIZE + OFFSET, sizeof(STREAM_TYPE)); c = calloc(STREAM_ARRAY_SIZE + OFFSET, sizeof(STREAM_TYPE)); if(!a || !b || !c) { printf("Memory allocation failed.\n"); return -1; } /* --- 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); free(a); free(b); free(c); 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. */ #ifndef WIN32 #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 ); } #else #include <Windows.h> double mysecond() { static LARGE_INTEGER freq = {0}; LARGE_INTEGER count = {0}; if(freq.QuadPart == 0LL) { QueryPerformanceFrequency(&freq); } QueryPerformanceCounter(&count); return (double)count.QuadPart / (double)freq.QuadPart; } #endif #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; size_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
ispc_tasking.c
// Copyright 2020 Intel Corporation // SPDX-License-Identifier: BSD-3-Clause #include <stdint.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #endif // Signature of ispc-generated 'task' functions typedef void (*TaskFuncType)(void *data, int threadIndex, int threadCount, int taskIndex, int taskCount, int taskIndex0, int taskIndex1, int taskIndex2, int taskCount0, int taskCount1, int taskCount2); void ISPCLaunch(void **taskGroupPtr, void *_func, void *data, int count0, int count1, int count2) { const int count = count0 * count1 * count2; TaskFuncType func = (TaskFuncType)_func; #pragma omp parallel { #ifdef _OPENMP const int threadIndex = omp_get_thread_num(); const int threadCount = omp_get_num_threads(); #else const int threadIndex = 0; const int threadCount = 1; #endif #pragma omp for schedule(runtime) for (int i = 0; i < count; i++) { int taskIndex0 = i % count0; int taskIndex1 = (i / count0) % count1; int taskIndex2 = i / (count0 * count1); func(data, threadIndex, threadCount, i, count, taskIndex0, taskIndex1, taskIndex2, count0, count1, count2); } } } void ISPCSync(void *h) { free(h); } void *ISPCAlloc(void **taskGroupPtr, int64_t size, int32_t alignment) { *taskGroupPtr = aligned_alloc(alignment, size); return *taskGroupPtr; }
convert_hyb_x_coo.c
#include "alphasparse/format.h" #include <stdlib.h> #include <alphasparse/opt.h> #include <alphasparse/util.h> #include <memory.h> #include <stdio.h> static void print_coo_s(const spmat_coo_s_t *mat) { printf("nnz:%d, cols:%d, rows:%d\n", mat->nnz, mat->cols, mat->rows); for (ALPHA_INT i = 0; i < mat->nnz; i++) { printf("#%d, val:%f, row:%d, col:%d\n", i, mat->values[i], mat->row_indx[i], mat->col_indx[i]); } printf("=====================================\n\n"); } static void print_ell_s(const spmat_ell_s_t *mat) { printf("ld:%d, cols:%d, rows:%d\n", mat->ld, mat->cols, mat->rows); for(ALPHA_INT i = 0; i < mat->ld; i++) { for(ALPHA_INT j = 0; j < mat->rows; j++) { printf("%f ", mat->values[i*mat->rows + j]); } printf("\n"); } printf("=====================================\n\n"); } alphasparse_status_t ONAME(const ALPHA_SPMAT_COO *source, ALPHA_SPMAT_HYB **dest) { ALPHA_SPMAT_HYB *mat = alpha_malloc(sizeof(ALPHA_SPMAT_HYB)); *dest = mat; ALPHA_SPMAT_CSR *csr; convert_csr_coo(source, &csr); ALPHA_INT m = csr->rows; ALPHA_INT n = csr->cols; ALPHA_INT csr_nnz = source->nnz; ALPHA_INT ell_width = (csr_nnz - 1) / m + 1; ALPHA_INT coo_nnz = 0; for (ALPHA_INT i = 0; i < m; i++) { ALPHA_INT row_nnz = csr->rows_end[i] - csr->rows_start[i]; ALPHA_INT deta = row_nnz - ell_width; coo_nnz += deta > 0 ? deta : 0; } const ALPHA_INT thread_num = alpha_get_thread_num(); ALPHA_Number *ell_values = alpha_memalign((uint64_t)ell_width * m * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT); ALPHA_INT *ell_col_ind = alpha_memalign((uint64_t)ell_width * m * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT); ALPHA_Number *coo_values = alpha_memalign((uint64_t)coo_nnz * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT); ALPHA_INT *coo_row_val = alpha_memalign((uint64_t)coo_nnz * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT); ALPHA_INT *coo_col_val = alpha_memalign((uint64_t)coo_nnz * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT); memset(ell_values, 0, (uint64_t)ell_width * m * sizeof(ALPHA_Number)); memset(ell_col_ind, 0, (uint64_t)ell_width * m * sizeof(ALPHA_INT)); memset(coo_values, 0, (uint64_t)coo_nnz * sizeof(ALPHA_Number)); memset(coo_row_val, 0, (uint64_t)coo_nnz * sizeof(ALPHA_INT)); memset(coo_col_val, 0, (uint64_t)coo_nnz * sizeof(ALPHA_INT)); // i列j行, 列优先 #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < ell_width; i++) { for (ALPHA_INT j = 0; j < m; j++) { ALPHA_INT csr_rs = csr->rows_start[j]; ALPHA_INT csr_re = csr->rows_end[j]; if (csr_rs + i < csr_re) { ell_values [i * m + j] = csr->values[csr_rs + i]; ell_col_ind[i * m + j] = csr->col_indx[csr_rs + i]; } } } ALPHA_INT idx = 0; for (ALPHA_INT i = ell_width; i < n; i++) { for (ALPHA_INT j = 0; j < m; j++) { ALPHA_INT csr_rs = csr->rows_start[j]; ALPHA_INT csr_re = csr->rows_end[j]; if (csr_rs + i < csr_re) { coo_values [idx] = csr->values[csr_rs + i]; coo_row_val[idx] = j; coo_col_val[idx] = csr->col_indx[csr_rs +i]; idx++; } } } // coo part sort ALPHA_SPMAT_COO *coo = alpha_malloc(sizeof(ALPHA_SPMAT_COO)); coo->col_indx = coo_col_val; coo->row_indx = coo_row_val; coo->values = coo_values; coo->cols = n; coo->rows = m; coo->nnz = coo_nnz; // coo->ordered = false; // coo_order(coo); mat->ell_val = ell_values; mat->ell_col_ind = ell_col_ind; mat->coo_val = coo->values; mat->coo_col_val = coo->col_indx; mat->coo_row_val = coo->row_indx; mat->nnz = coo_nnz; mat->rows = m; mat->cols = n; mat->ell_width = ell_width; //#define CHECK #ifdef CHECK #ifdef S print_coo_s(source); print_coo_s(coo); ALPHA_SPMAT_ELL *ell = alpha_malloc(sizeof(ALPHA_SPMAT_ELL)); ell->values = ell_values; ell->indices = ell_col_ind; ell->ld = ell_width; ell->rows = m; ell->cols = n; print_ell_s(ell); #endif #undef CHECK #endif return ALPHA_SPARSE_STATUS_SUCCESS; }
GB_binop__ne_fp32.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__ne_fp32) // A.*B function (eWiseMult): GB (_AemultB_08__ne_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__ne_fp32) // A.*B function (eWiseMult): GB (_AemultB_04__ne_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ne_fp32) // A*D function (colscale): GB (_AxD__ne_fp32) // D*A function (rowscale): GB (_DxB__ne_fp32) // C+=B function (dense accum): GB (_Cdense_accumB__ne_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__ne_fp32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ne_fp32) // C=scalar+B GB (_bind1st__ne_fp32) // C=scalar+B' GB (_bind1st_tran__ne_fp32) // C=A+scalar GB (_bind2nd__ne_fp32) // C=A'+scalar GB (_bind2nd_tran__ne_fp32) // C type: bool // A type: float // A pattern? 0 // B type: float // B pattern? 0 // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #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) \ float 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) \ float 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_NE || GxB_NO_FP32 || GxB_NO_NE_FP32) //------------------------------------------------------------------------------ // 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__ne_fp32) ( 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__ne_fp32) ( 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__ne_fp32) ( 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 float float bwork = (*((float *) 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__ne_fp32) ( 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__ne_fp32) ( 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__ne_fp32) ( 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) ; float alpha_scalar ; float beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((float *) alpha_scalar_in)) ; beta_scalar = (*((float *) 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__ne_fp32) ( 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__ne_fp32) ( 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__ne_fp32) ( 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__ne_fp32) ( 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__ne_fp32) ( 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 ; float x = (*((float *) x_input)) ; float *Bx = (float *) 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 ; float 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__ne_fp32) ( 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 ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float 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) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__ne_fp32) ( 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 \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // 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) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__ne_fp32) ( 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 float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_fp64_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_fp64_fp32 // op(A') function: GB_unop_tran__identity_fp64_fp32 // C type: double // A type: float // cast: double cij = (double) aij // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ double z = (double) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = (double) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP64 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_fp64_fp32 ( double *Cx, // Cx and Ax may be aliased const float *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; double z = (double) aij ; Cx [p] = z ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_fp64_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
DataGen.h
// Copyright (C) 2019-2020 Zilliz. 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. 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 #pragma once #include <boost/algorithm/string/predicate.hpp> #include <cstring> #include <memory> #include <random> #include <google/protobuf/text_format.h> #include "Constants.h" #include "common/Schema.h" #include "index/ScalarIndexSort.h" #include "index/StringIndexSort.h" #include "knowhere/index/VecIndex.h" #include "knowhere/index/VecIndexFactory.h" #include "knowhere/index/vector_index/IndexIVF.h" #include "knowhere/index/vector_index/adapter/VectorAdapter.h" #include "query/SearchOnIndex.h" #include "segcore/SegmentGrowingImpl.h" #include "segcore/SegmentSealedImpl.h" #include "segcore/Utils.h" using boost::algorithm::starts_with; namespace milvus::segcore { struct GeneratedData { std::vector<idx_t> row_ids_; std::vector<Timestamp> timestamps_; InsertData* raw_; std::vector<FieldId> field_ids; SchemaPtr schema_; template <typename T> std::vector<T> get_col(FieldId field_id) const { std::vector<T> ret(raw_->num_rows()); for (auto target_field_data : raw_->fields_data()) { if (field_id.get() != target_field_data.field_id()) { continue; } auto& field_meta = schema_->operator[](field_id); if (field_meta.is_vector()) { if (field_meta.get_data_type() == DataType::VECTOR_FLOAT) { int len = raw_->num_rows() * field_meta.get_dim(); ret.resize(len); auto src_data = reinterpret_cast<const T*>(target_field_data.vectors().float_vector().data().data()); std::copy_n(src_data, len, ret.data()); } else if (field_meta.get_data_type() == DataType::VECTOR_BINARY) { int len = raw_->num_rows() * (field_meta.get_dim() / 8); ret.resize(len); auto src_data = reinterpret_cast<const T*>(target_field_data.vectors().binary_vector().data()); std::copy_n(src_data, len, ret.data()); } else { PanicInfo("unsupported"); } return std::move(ret); } switch (field_meta.get_data_type()) { case DataType::BOOL: { auto src_data = reinterpret_cast<const T*>(target_field_data.scalars().bool_data().data().data()); std::copy_n(src_data, raw_->num_rows(), ret.data()); break; } case DataType::INT8: case DataType::INT16: case DataType::INT32: { auto src_data = reinterpret_cast<const int32_t*>(target_field_data.scalars().int_data().data().data()); std::copy_n(src_data, raw_->num_rows(), ret.data()); break; } case DataType::INT64: { auto src_data = reinterpret_cast<const T*>(target_field_data.scalars().long_data().data().data()); std::copy_n(src_data, raw_->num_rows(), ret.data()); break; } case DataType::FLOAT: { auto src_data = reinterpret_cast<const T*>(target_field_data.scalars().float_data().data().data()); std::copy_n(src_data, raw_->num_rows(), ret.data()); break; } case DataType::DOUBLE: { auto src_data = reinterpret_cast<const T*>(target_field_data.scalars().double_data().data().data()); std::copy_n(src_data, raw_->num_rows(), ret.data()); break; } case DataType::VARCHAR: { auto ret_data = reinterpret_cast<std::string*>(ret.data()); auto src_data = target_field_data.scalars().string_data().data(); std::copy(src_data.begin(), src_data.end(), ret_data); break; } default: { PanicInfo("unsupported"); } } } return std::move(ret); } std::unique_ptr<DataArray> get_col(FieldId field_id) const { for (auto target_field_data : raw_->fields_data()) { if (field_id.get() == target_field_data.field_id()) { return std::make_unique<DataArray>(target_field_data); } } PanicInfo("field id not find"); } private: GeneratedData() = default; friend GeneratedData DataGen(SchemaPtr schema, int64_t N, uint64_t seed, uint64_t ts_offset, int repeat_count); }; inline GeneratedData DataGen(SchemaPtr schema, int64_t N, uint64_t seed = 42, uint64_t ts_offset = 0, int repeat_count = 1) { using std::vector; std::default_random_engine er(seed); std::normal_distribution<> distr(0, 1); int offset = 0; auto insert_data = std::make_unique<InsertData>(); auto insert_cols = [&insert_data](auto& data, int64_t count, auto& field_meta) { auto array = milvus::segcore::CreateDataArrayFrom(data.data(), count, field_meta); insert_data->mutable_fields_data()->AddAllocated(array.release()); }; for (auto field_id : schema->get_field_ids()) { auto field_meta = schema->operator[](field_id); switch (field_meta.get_data_type()) { case DataType::VECTOR_FLOAT: { auto dim = field_meta.get_dim(); vector<float> final(dim * N); bool is_ip = starts_with(field_meta.get_name().get(), "normalized"); #pragma omp parallel for for (int n = 0; n < N; ++n) { vector<float> data(dim); float sum = 0; std::default_random_engine er2(seed + n); std::normal_distribution<> distr2(0, 1); for (auto& x : data) { x = distr2(er2) + offset; sum += x * x; } if (is_ip) { sum = sqrt(sum); for (auto& x : data) { x /= sum; } } std::copy(data.begin(), data.end(), final.begin() + dim * n); } insert_cols(final, N, field_meta); break; } case DataType::VECTOR_BINARY: { auto dim = field_meta.get_dim(); Assert(dim % 8 == 0); vector<uint8_t> data(dim / 8 * N); for (auto& x : data) { x = er(); } insert_cols(data, N, field_meta); break; } case DataType::INT64: { vector<int64_t> data(N); for (int i = 0; i < N; i++) { data[i] = i / repeat_count; } insert_cols(data, N, field_meta); break; } case DataType::INT32: { vector<int> data(N); for (auto& x : data) { x = er() % (2 * N); } insert_cols(data, N, field_meta); break; } case DataType::INT16: { vector<int16_t> data(N); for (auto& x : data) { x = er() % (2 * N); } insert_cols(data, N, field_meta); break; } case DataType::INT8: { vector<int8_t> data(N); for (auto& x : data) { x = er() % (2 * N); } insert_cols(data, N, field_meta); break; } case DataType::FLOAT: { vector<float> data(N); for (auto& x : data) { x = distr(er); } insert_cols(data, N, field_meta); break; } case DataType::DOUBLE: { vector<double> data(N); for (auto& x : data) { x = distr(er); } insert_cols(data, N, field_meta); break; } case DataType::VARCHAR: { vector<std::string> data(N); for (int i = 0; i < N / repeat_count; i++) { auto str = std::to_string(er()); for (int j = 0; j < repeat_count; j++) { data[i * repeat_count + j] = str; } } insert_cols(data, N, field_meta); break; } default: { throw std::runtime_error("unimplemented"); } } ++offset; } GeneratedData res; res.schema_ = schema; res.raw_ = insert_data.release(); res.raw_->set_num_rows(N); for (int i = 0; i < N; ++i) { res.row_ids_.push_back(i); res.timestamps_.push_back(i + ts_offset); } return res; } inline auto CreatePlaceholderGroup(int64_t num_queries, int dim, int64_t seed = 42) { namespace ser = milvus::proto::common; ser::PlaceholderGroup raw_group; auto value = raw_group.add_placeholders(); value->set_tag("$0"); value->set_type(ser::PlaceholderType::FloatVector); std::normal_distribution<double> dis(0, 1); std::default_random_engine e(seed); for (int i = 0; i < num_queries; ++i) { std::vector<float> vec; for (int d = 0; d < dim; ++d) { vec.push_back(dis(e)); } // std::string line((char*)vec.data(), (char*)vec.data() + vec.size() * sizeof(float)); value->add_values(vec.data(), vec.size() * sizeof(float)); } return raw_group; } inline auto CreatePlaceholderGroupFromBlob(int64_t num_queries, int dim, const float* src) { namespace ser = milvus::proto::common; ser::PlaceholderGroup raw_group; auto value = raw_group.add_placeholders(); value->set_tag("$0"); value->set_type(ser::PlaceholderType::FloatVector); int64_t src_index = 0; for (int i = 0; i < num_queries; ++i) { std::vector<float> vec; for (int d = 0; d < dim; ++d) { vec.push_back(src[src_index++]); } // std::string line((char*)vec.data(), (char*)vec.data() + vec.size() * sizeof(float)); value->add_values(vec.data(), vec.size() * sizeof(float)); } return raw_group; } inline auto CreateBinaryPlaceholderGroup(int64_t num_queries, int64_t dim, int64_t seed = 42) { assert(dim % 8 == 0); namespace ser = milvus::proto::common; ser::PlaceholderGroup raw_group; auto value = raw_group.add_placeholders(); value->set_tag("$0"); value->set_type(ser::PlaceholderType::BinaryVector); std::default_random_engine e(seed); for (int i = 0; i < num_queries; ++i) { std::vector<uint8_t> vec; for (int d = 0; d < dim / 8; ++d) { vec.push_back(e()); } // std::string line((char*)vec.data(), (char*)vec.data() + vec.size() * sizeof(float)); value->add_values(vec.data(), vec.size()); } return raw_group; } inline auto CreateBinaryPlaceholderGroupFromBlob(int64_t num_queries, int64_t dim, const uint8_t* ptr) { assert(dim % 8 == 0); namespace ser = milvus::proto::common; ser::PlaceholderGroup raw_group; auto value = raw_group.add_placeholders(); value->set_tag("$0"); value->set_type(ser::PlaceholderType::BinaryVector); for (int i = 0; i < num_queries; ++i) { std::vector<uint8_t> vec; for (int d = 0; d < dim / 8; ++d) { vec.push_back(*ptr); ++ptr; } // std::string line((char*)vec.data(), (char*)vec.data() + vec.size() * sizeof(float)); value->add_values(vec.data(), vec.size()); } return raw_group; } inline json SearchResultToJson(const SearchResult& sr) { int64_t num_queries = sr.total_nq_; int64_t topk = sr.unity_topK_; std::vector<std::vector<std::string>> results; for (int q = 0; q < num_queries; ++q) { std::vector<std::string> result; for (int k = 0; k < topk; ++k) { int index = q * topk + k; result.emplace_back(std::to_string(sr.seg_offsets_[index]) + "->" + std::to_string(sr.distances_[index])); } results.emplace_back(std::move(result)); } return json{results}; }; inline void SealedLoadFieldData(const GeneratedData& dataset, SegmentSealed& seg) { auto row_count = dataset.row_ids_.size(); { LoadFieldDataInfo info; FieldMeta field_meta(FieldName("RowID"), RowFieldID, DataType::INT64); auto array = CreateScalarDataArrayFrom(dataset.row_ids_.data(), row_count, field_meta); info.field_data = array.release(); info.row_count = dataset.row_ids_.size(); info.field_id = RowFieldID.get(); // field id for RowId seg.LoadFieldData(info); } { LoadFieldDataInfo info; FieldMeta field_meta(FieldName("Timestamp"), TimestampFieldID, DataType::INT64); auto array = CreateScalarDataArrayFrom(dataset.timestamps_.data(), row_count, field_meta); info.field_data = array.release(); info.row_count = dataset.timestamps_.size(); info.field_id = TimestampFieldID.get(); seg.LoadFieldData(info); } for (auto field_data : dataset.raw_->fields_data()) { LoadFieldDataInfo info; info.field_id = field_data.field_id(); info.row_count = row_count; info.field_data = &field_data; seg.LoadFieldData(info); } } inline std::unique_ptr<SegmentSealed> SealedCreator(SchemaPtr schema, const GeneratedData& dataset) { auto segment = CreateSealedSegment(schema); SealedLoadFieldData(dataset, *segment); return segment; } inline knowhere::VecIndexPtr GenVecIndexing(int64_t N, int64_t dim, const float* vec) { // {knowhere::IndexParams::nprobe, 10}, auto conf = knowhere::Config{ {knowhere::meta::METRIC_TYPE, knowhere::metric::L2}, {knowhere::meta::DIM, dim}, {knowhere::indexparam::NLIST, 1024}, {knowhere::meta::DEVICE_ID, 0} }; auto database = knowhere::GenDataset(N, dim, vec); auto indexing = std::make_shared<knowhere::IVF>(); indexing->Train(database, conf); indexing->AddWithoutIds(database, conf); return indexing; } template <typename T> inline scalar::IndexBasePtr GenScalarIndexing(int64_t N, const T* data) { if constexpr (std::is_same_v<T, std::string>) { auto indexing = scalar::CreateStringIndexSort(); indexing->Build(N, data); return indexing; } else { auto indexing = scalar::CreateScalarIndexSort<T>(); indexing->Build(N, data); return indexing; } } inline std::vector<char> translate_text_plan_to_binary_plan(const char* text_plan) { proto::plan::PlanNode plan_node; auto ok = google::protobuf::TextFormat::ParseFromString(text_plan, &plan_node); AssertInfo(ok, "Failed to parse"); std::string binary_plan; plan_node.SerializeToString(&binary_plan); std::vector<char> ret; ret.resize(binary_plan.size()); std::memcpy(ret.data(), binary_plan.c_str(), binary_plan.size()); return ret; } } // namespace milvus::segcore
valid.mob3.src.h
#pragma once #include "ukr.h" #include "omp.h" #include "transpose.h" #include "gen_ukr_A6B2gemm_1_128_56_56_128_3_3.h" #include "gen_ukr_A4B2gemm_1_128_56_56_128_3_3.h" void testrun(float* A ,float*B, float*C, float*oriB ){ int tid = omp_get_thread_num(); int Nx = 56; int Ny = 56; int Nh = 3; long long Astrides[6] = {0,1,2,3,4,5}; int b1 = 0; for (int fpck = (tid%1)*16; fpck < uNf; fpck+=1*16){ for(int cwh = (tid/1)*8; cwh < uNc*uNw*uNh/8*8; cwh+=8*1){ transpose8x8_avx(oriB+ (fpck+0)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 0, uNc*uNw*uNh, 16); transpose8x8_avx(oriB+ (fpck+8)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 8, uNc*uNw*uNh, 16); } } #pragma omp barrier// begin push button generated block for(int c5=0;c5<128+0;c5+=128) { for(int xy5=0;xy5<3136+0;xy5+=3136) { for(int f5=0;f5<128+0;f5+=128) { for(int c4=c5;c4<min(128, 128+c5);c4+=128) { for(int f4=f5;f4<min(128, 128+f5);f4+=Tf2) { for(int xy4=xy5;xy4<min(3136, 3136+xy5);xy4+=3136) { for(int c3=c4;c3<min(128, 128+c4);c3+=Tc1) { for(int f3=f4;f3<min(128, Tf2+f4);f3+=Tf2) { for(int xy3=xy4;xy3<min(3136, 3136+xy4);xy3+=Txy3) { for(int xy2=xy3;xy2<min(3136, Txy3+xy3);xy2+=6) { for(int f2=f3;f2<min(128, Tf2+f3);f2+=16) { for(int c2=c3;c2<min(128, Tc1+c3);c2+=Tc1) { for(int c1=c2;c1<min(128, Tc1+c2);c1+=Tc1) { for(int xy1=xy2;xy1<min(3136, 6+xy2);xy1+=6) { for(int f1=f2;f1<min(128, 16+f2);f1+=16) { int ctile=min(Tc1, 128-c1); int x1=xy1/56; int y1=xy1%56/1; int c1_1=c1/1; int c1_2=c1%1/1; int kf1_1=f1/16; int kf1_2=f1%16/1; int of1_1=f1/1; int of1_2=f1%1/1; int offsetA=0+b1*430592+c1_1*3364+1*x1*58+1*y1*1+c1_2*1; int offsetB=0+kf1_1*18432+c1*144+0*48+0*16+kf1_2*1; int offsetC=0+b1*401408+of1_1*3136+x1*56+y1*1+of1_2*1; if(56-y1>=6){ cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); } else if(56*56-xy1>=6){ for(int sti=56-y1;sti<6;sti+=1) { Astrides[sti]+=2; } cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); for(int sti=56-y1;sti<6;sti+=1) { Astrides[sti]-=2; } } else{ cnn_ukr_float_scatter_4x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); } } } } } } } } } } } } } } } } // end push button generated block }
pzgstrf.c
/*! \file Copyright (c) 2003, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from U.S. Dept. of Energy) All rights reserved. The source code is distributed under BSD license, see the file License.txt at the top-level directory. */ #include <stdlib.h> /* for getenv and atoi */ #include "slu_mt_zdefs.h" void pzgstrf(superlumt_options_t *superlumt_options, SuperMatrix *A, int_t *perm_r, SuperMatrix *L, SuperMatrix *U, Gstat_t *Gstat, int_t *info) { /* * -- SuperLU MT routine (version 2.0) -- * Lawrence Berkeley National Lab, Univ. of California Berkeley, * and Xerox Palo Alto Research Center. * September 10, 2007 * * Purpose * ======= * * PZGSTRF computes an LU factorization of a general sparse nrow-by-ncol * matrix A using partial pivoting with row interchanges. The factorization * has the form * Pr * A = L * U * where Pr is a row permutation matrix, L is lower triangular with unit * diagonal elements (lower trapezoidal if A->nrow > A->ncol), and U is * upper triangular (upper trapezoidal if A->nrow < A->ncol). * * Arguments * ========= * * superlumt_options (input) superlumt_options_t* * The structure defines the parameters to control how the sparse * LU factorization is performed. The following fields must be set * by the user: * * o nprocs (int_t) * Number of processes to be spawned and used for factorization. * * o refact (yes_no_t) * Specifies whether this is first time or subsequent factorization. * = NO: this factorization is treated as the first one; * = YES: it means that a factorization was performed prior to this * one. Therefore, this factorization will re-use some * existing data structures, such as L and U storage, column * elimination tree, and the symbolic information of the * Householder matrix. * * o panel_size (int_t) * A panel consists of at most panel_size consecutive columns. * * o relax (int_t) * Degree of relaxing supernodes. If the number of nodes (columns) * in a subtree of the elimination tree is less than relax, this * subtree is considered as one supernode, regardless of the row * structures of those columns. * * o diag_pivot_thresh (double) * Diagonal pivoting threshold. At step j of Gaussian elimination, * if abs(A_jj) >= diag_pivot_thresh * (max_(i>=j) abs(A_ij)), * use A_jj as pivot. 0 <= diag_pivot_thresh <= 1. The default * value is 1.0, corresponding to partial pivoting. * * o usepr (yes_no_t) * Whether the pivoting will use perm_r specified by the user. * = YES: use perm_r; perm_r is input, unchanged on exit. * = NO: perm_r is determined by partial pivoting, and is output. * * o drop_tol (double) (NOT IMPLEMENTED) * Drop tolerance parameter. At step j of the Gaussian elimination, * if abs(A_ij)/(max_i abs(A_ij)) < drop_tol, drop entry A_ij. * 0 <= drop_tol <= 1. The default value of drop_tol is 0, * corresponding to not dropping any entry. * * o perm_c (int_t*) * Column permutation vector of size A->ncol, which defines the * permutation matrix Pc; perm_c[i] = j means column i of A is * in position j in A*Pc. * * o perm_r (int_t*) * Column permutation vector of size A->nrow. * If superlumt_options->usepr = NO, this is an output argument. * * o work (void*) of size lwork * User-supplied work space and space for the output data structures. * Not referenced if lwork = 0; * * o lwork (int_t) * Specifies the length of work array. * = 0: allocate space internally by system malloc; * > 0: use user-supplied work array of length lwork in bytes, * returns error if space runs out. * = -1: the routine guesses the amount of space needed without * performing the factorization, and returns it in * superlu_memusage->total_needed; no other side effects. * * A (input) SuperMatrix* * Original matrix A, permuted by columns, of dimension * (A->nrow, A->ncol). The type of A can be: * Stype = NCP; Dtype = _D; Mtype = GE. * * perm_r (input/output) int_t*, dimension A->nrow * Row permutation vector which defines the permutation matrix Pr, * perm_r[i] = j means row i of A is in position j in Pr*A. * If superlumt_options->usepr = NO, perm_r is output argument; * If superlumt_options->usepr = YES, the pivoting routine will try * to use the input perm_r, unless a certain threshold criterion * is violated. In that case, perm_r is overwritten by a new * permutation determined by partial pivoting or diagonal * threshold pivoting. * * L (output) SuperMatrix* * The factor L from the factorization Pr*A=L*U; use compressed row * subscripts storage for supernodes, i.e., L has type: * Stype = SCP, Dtype = _D, Mtype = TRLU. * * U (output) SuperMatrix* * The factor U from the factorization Pr*A*Pc=L*U. Use column-wise * storage scheme, i.e., U has types: Stype = NCP, Dtype = _D, * Mtype = TRU. * * Gstat (output) Gstat_t* * Record all the statistics about the factorization; * See Gstat_t structure defined in slu_mt_util.h. * * info (output) int_t* * = 0: successful exit * < 0: if info = -i, the i-th argument had an illegal value * > 0: if info = i, and i is * <= A->ncol: U(i,i) is exactly zero. The factorization has * been completed, but the factor U is exactly singular, * and division by zero will occur if it is used to solve a * system of equations. * > A->ncol: number of bytes allocated when memory allocation * failure occurred, plus A->ncol. * */ pzgstrf_threadarg_t *pzgstrf_threadarg; pxgstrf_shared_t pxgstrf_shared; register int_t nprocs = superlumt_options->nprocs; register int_t i, iinfo; double *utime = Gstat->utime; double usrtime, wtime; double usertimer_(); #if ( MACH==SUN ) thread_t *thread_id; #elif ( MACH==DEC || MACH==PTHREAD ) pthread_t *thread_id; void *status; #endif void *pzgstrf_thread(void *); /* -------------------------------------------------------------- Initializes the parallel data structures for pzgstrf_thread(). --------------------------------------------------------------*/ pzgstrf_threadarg = pzgstrf_thread_init(A, L, U, superlumt_options, &pxgstrf_shared, Gstat, info); if ( *info ) return; /* Start timing factorization. */ usrtime = usertimer_(); wtime = SuperLU_timer_(); /* ------------------------------------------------------------ On a SUN multiprocessor system, use Solaris thread. ------------------------------------------------------------*/ #if ( MACH==SUN ) /* Create nproc threads for concurrent factorization. */ thread_id = (thread_t *) SUPERLU_MALLOC(nprocs * sizeof(thread_t)); for (i = 1; i < nprocs; ++i) { #if ( PRNTlevel==1 ) printf(".. Create unbound threads: i " IFMT ", nprocs " IFMT "\n", i, nprocs); #endif if ( (iinfo = thr_create(NULL, 0, pzgstrf_thread, &(pzgstrf_threadarg[i]), 0, &thread_id[i])) ) { fprintf(stderr, "thr_create: %d\n", iinfo); SUPERLU_ABORT("thr_creat()"); } } pzgstrf_thread( &(pzgstrf_threadarg[0]) ); /* Wait for all threads to terminate. */ for (i = 1; i < nprocs; i++) thr_join(thread_id[i], 0, 0); SUPERLU_FREE (thread_id); /* _SOLARIS_2 */ /* ------------------------------------------------------------ On a DEC multiprocessor system, use pthread. ------------------------------------------------------------*/ #elif ( MACH==DEC ) /* Use DECthreads ... */ /* Create nproc threads for concurrent factorization. */ thread_id = (pthread_t *) SUPERLU_MALLOC(nprocs * sizeof(pthread_t)); for (i = 0; i < nprocs; ++i) { if ( iinfo = pthread_create(&thread_id[i], NULL, pzgstrf_thread, &(pzgstrf_threadarg[i])) ) { fprintf(stderr, "pthread_create: %d\n", iinfo); SUPERLU_ABORT("pthread_create()"); } /* pthread_bind_to_cpu_np(thread_id[i], i);*/ } /* Wait for all threads to terminate. */ for (i = 0; i < nprocs; i++) pthread_join(thread_id[i], &status); SUPERLU_FREE (thread_id); /* _DEC */ /* ------------------------------------------------------------ On a SGI Power Challenge or Origin multiprocessor system, use parallel C. ------------------------------------------------------------*/ #elif ( MACH==SGI || MACH==ORIGIN ) /* Use parallel C ... */ if ( getenv("MP_SET_NUMTHREADS") ) { i = atoi(getenv("MP_SET_NUMTHREADS")); if ( nprocs > i ) { printf("nprocs=" IFMT "> environment allowed: MP_SET_NUMTHREADS=" IFMT "\n", nprocs, i); exit(-1); } } #pragma parallel #pragma shared (pzgstrf_threadarg) /*#pragma numthreads (max = nprocs)*/ #pragma numthreads (nprocs) { pzgstrf_thread( pzgstrf_threadarg ); } /* _SGI or _ORIGIN */ /* ------------------------------------------------------------ On a Cray PVP multiprocessor system, use microtasking. ------------------------------------------------------------*/ #elif ( MACH==CRAY_PVP ) /* Use C microtasking. */ if ( getenv("NCPUS") ) { i = atoi(getenv("NCPUS")); if ( nprocs > i ) { printf("nprocs=" IFMT "> environment allowed: NCPUS=" IFMT "\n", nprocs, i); exit(-1); } } #pragma _CRI taskloop private (i,nprocs) shared (pzgstrf_threadarg) /* Stand-alone task loop */ for (i = 0; i < nprocs; ++i) { pzgstrf_thread( &(pzgstrf_threadarg[i]) ); } /* _CRAY_PVP */ /* ------------------------------------------------------------ Use POSIX threads. ------------------------------------------------------------*/ #elif ( MACH==PTHREAD ) /* Use pthread ... */ /* Create nproc threads for concurrent factorization. */ thread_id = (pthread_t *) SUPERLU_MALLOC(nprocs * sizeof(pthread_t)); for (i = 0; i < nprocs; ++i) { if ( iinfo = pthread_create(&thread_id[i], NULL, pzgstrf_thread, &(pzgstrf_threadarg[i])) ) { fprintf(stderr, "pthread_create: " IFMT "\n", iinfo); SUPERLU_ABORT("pthread_create()"); } } /* Wait for all threads to terminate. */ for (i = 0; i < nprocs; i++) pthread_join(thread_id[i], &status); SUPERLU_FREE (thread_id); /* _PTHREAD */ /* ------------------------------------------------------------ Use openMP. ------------------------------------------------------------*/ #elif ( MACH==OPENMP ) /* Use openMP ... */ #pragma omp parallel for shared (pzgstrf_threadarg) private (i) /* Stand-alone task loop */ for (i = 0; i < nprocs; ++i) { pzgstrf_thread( &(pzgstrf_threadarg[i]) ); } /* _OPENMP */ /* ------------------------------------------------------------ On all other systems, use single processor. ------------------------------------------------------------*/ #else printf("pzgstrf() is not parallelized on this machine.\n"); printf("pzgstrf() will be run on single processor.\n"); pzgstrf_thread( &(pzgstrf_threadarg[0]) ); #endif wtime = SuperLU_timer_() - wtime; usrtime = usertimer_() - usrtime; utime[FACT] = wtime; #if ( PRNTlevel==1 ) printf(".. pzgstrf_thread() returns info " IFMT ", usrtime %.2f, wtime %.2f\n", *info, usrtime, wtime); #endif /* check_mem_leak("after pzgstrf_thread()"); */ /* ------------------------------------------------------------ Clean up and free storage after multithreaded factorization. ------------------------------------------------------------*/ pzgstrf_thread_finalize(pzgstrf_threadarg, &pxgstrf_shared, A, perm_r, L, U); }
3d25pt_var.c
/* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 32; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[(t)%2][i ][j ][k ] + coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) + coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) + coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) + coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) + coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) + coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) + coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) + coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) + coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) + coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) + coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) + coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_binop__islt_fp32.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__islt_fp32 // A.*B function (eWiseMult): GB_AemultB__islt_fp32 // A*D function (colscale): GB_AxD__islt_fp32 // D*A function (rowscale): GB_DxB__islt_fp32 // C+=B function (dense accum): GB_Cdense_accumB__islt_fp32 // C+=b function (dense accum): GB_Cdense_accumb__islt_fp32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__islt_fp32 // C=scalar+B GB_bind1st__islt_fp32 // C=scalar+B' GB_bind1st_tran__islt_fp32 // C=A+scalar GB_bind2nd__islt_fp32 // C=A'+scalar GB_bind2nd_tran__islt_fp32 // C type: float // A type: float // B,b type: float // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // 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) \ float aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ float bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float 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_ISLT || GxB_NO_FP32 || GxB_NO_ISLT_FP32) //------------------------------------------------------------------------------ // 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__islt_fp32 ( 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__islt_fp32 ( 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__islt_fp32 ( 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 float float bwork = (*((float *) 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__islt_fp32 ( 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 float *GB_RESTRICT Cx = (float *) 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__islt_fp32 ( 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 float *GB_RESTRICT Cx = (float *) 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__islt_fp32 ( 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__islt_fp32 ( 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__islt_fp32 ( 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 float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) 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 ; float 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__islt_fp32 ( 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 ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float 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) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB_bind1st_tran__islt_fp32 ( 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 \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // 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) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB_bind2nd_tran__islt_fp32 ( 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 float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
map-2.c
/* { dg-do compile } */ /* { dg-options "-fopenmp" } */ void foo (int *p, int (*q)[10], int r[10], int s[10][10]) { int a[10], b[10][10]; #pragma omp target map (tofrom: p[-1:2]) ; #pragma omp target map (tofrom: q[-1:2][0:10]) ; #pragma omp target map (tofrom: q[-1:2][-2:10]) /* { dg-error "negative low bound in array section in" } */ ; #pragma omp target map (tofrom: r[-1:2]) ; #pragma omp target map (tofrom: s[-1:2][:]) ; #pragma omp target map (tofrom: s[-1:2][-2:10]) /* { dg-error "negative low bound in array section in" } */ ; #pragma omp target map (tofrom: a[-1:2]) /* { dg-error "negative low bound in array section in" } */ ; #pragma omp target map (tofrom: b[-1:2][0:]) /* { dg-error "negative low bound in array section in" } */ ; #pragma omp target map (tofrom: b[1:2][-2:10]) /* { dg-error "negative low bound in array section in" } */ ; #pragma omp target map (tofrom: p[2:-3]) /* { dg-error "negative length in array section in" } */ ; #pragma omp target map (tofrom: q[2:-3][:]) /* { dg-error "negative length in array section in" } */ ; #pragma omp target map (tofrom: q[2:3][0:-1]) /* { dg-error "negative length in array section in" } */ ; #pragma omp target map (tofrom: r[2:-5]) /* { dg-error "negative length in array section in" } */ ; #pragma omp target map (tofrom: s[2:-5][:]) /* { dg-error "negative length in array section in" } */ ; #pragma omp target map (tofrom: s[2:5][0:-4]) /* { dg-error "negative length in array section in" } */ ; #pragma omp target map (tofrom: a[2:-5]) /* { dg-error "negative length in array section in" } */ ; #pragma omp target map (tofrom: b[2:-5][0:10]) /* { dg-error "negative length in array section in" } */ ; #pragma omp target map (tofrom: b[2:5][0:-4]) /* { dg-error "negative length in array section in" } */ ; }
GB_binop__rminus_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__rminus_fp32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__rminus_fp32) // A.*B function (eWiseMult): GB (_AemultB_03__rminus_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_fp32) // A*D function (colscale): GB (_AxD__rminus_fp32) // D*A function (rowscale): GB (_DxB__rminus_fp32) // C+=B function (dense accum): GB (_Cdense_accumB__rminus_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__rminus_fp32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_fp32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_fp32) // C=scalar+B GB (_bind1st__rminus_fp32) // C=scalar+B' GB (_bind1st_tran__rminus_fp32) // C=A+scalar GB (_bind2nd__rminus_fp32) // C=A'+scalar GB (_bind2nd_tran__rminus_fp32) // C type: float // A type: float // B,b type: float // BinaryOp: cij = (bij - aij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // 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) \ float aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ float bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float 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 = (y - x) ; // 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_RMINUS || GxB_NO_FP32 || GxB_NO_RMINUS_FP32) //------------------------------------------------------------------------------ // 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__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( 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 float float bwork = (*((float *) 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__rminus_fp32) ( 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 float *restrict Cx = (float *) 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__rminus_fp32) ( 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 float *restrict Cx = (float *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( 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__rminus_fp32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) 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 ; float bij = Bx [p] ; Cx [p] = (bij - x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rminus_fp32) ( 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 ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = Ax [p] ; Cx [p] = (y - aij) ; } 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) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB (_bind1st_tran__rminus_fp32) ( 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 \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // 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) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (y - aij) ; \ } GrB_Info GB (_bind2nd_tran__rminus_fp32) ( 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 float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
kgraph-data.h
#ifndef WDONG_KGRAPH_DATA #define WDONG_KGRAPH_DATA #include <cmath> #include <cstring> #include <malloc.h> #include <vector> #include <fstream> #include <stdexcept> #include <boost/assert.hpp> #ifdef __GNUC__ #ifdef __AVX__ #define KGRAPH_MATRIX_ALIGN 32 #else #ifdef __SSE2__ #define KGRAPH_MATRIX_ALIGN 16 #else #define KGRAPH_MATRIX_ALIGN 4 #endif #endif #endif namespace kgraph { /// L2 square distance with AVX instructions. /** AVX instructions have strong alignment requirement for t1 and t2. */ extern float float_l2sqr_avx (float const *t1, float const *t2, unsigned dim); /// L2 square distance with SSE2 instructions. extern float float_l2sqr_sse2 (float const *t1, float const *t2, unsigned dim); extern float float_l2sqr_sse2 (float const *, unsigned dim); extern float float_dot_sse2 (float const *, float const *, unsigned dim); /// L2 square distance for uint8_t with SSE2 instructions (for SIFT). extern float uint8_l2sqr_sse2 (uint8_t const *t1, uint8_t const *t2, unsigned dim); extern float float_l2sqr (float const *, float const *, unsigned dim); extern float float_l2sqr (float const *, unsigned dim); extern float float_dot (float const *, float const *, unsigned dim); using std::vector; /// namespace for various distance metrics. namespace metric { /// L2 square distance. struct l2sqr { template <typename T> /// L2 square distance. static float apply (T const *t1, T const *t2, unsigned dim) { float r = 0; for (unsigned i = 0; i < dim; ++i) { float v = float(t1[i]) - float(t2[i]); v *= v; r += v; } return r; } /// inner product. template <typename T> static float dot (T const *t1, T const *t2, unsigned dim) { float r = 0; for (unsigned i = 0; i < dim; ++i) { r += float(t1[i]) *float(t2[i]); } return r; } /// L2 norm. template <typename T> static float norm2 (T const *t1, unsigned dim) { float r = 0; for (unsigned i = 0; i < dim; ++i) { float v = float(t1[i]); v *= v; r += v; } return r; } }; struct l2 { template <typename T> static float apply (T const *t1, T const *t2, unsigned dim) { return sqrt(l2sqr::apply<T>(t1, t2, dim)); } }; } /// Matrix data. template <typename T, unsigned A = KGRAPH_MATRIX_ALIGN> class Matrix { unsigned col; unsigned row; size_t stride; char *data; void reset (unsigned r, unsigned c) { row = r; col = c; stride = (sizeof(T) * c + A - 1) / A * A; /* data.resize(row * stride); */ if (data) free(data); data = (char *)memalign(A, row * stride); // SSE instruction needs data to be aligned if (!data) throw runtime_error("memalign"); } public: Matrix (): col(0), row(0), stride(0), data(0) {} Matrix (unsigned r, unsigned c): data(0) { reset(r, c); } ~Matrix () { if (data) free(data); } unsigned size () const { return row; } unsigned dim () const { return col; } size_t step () const { return stride; } void resize (unsigned r, unsigned c) { reset(r, c); } T const *operator [] (unsigned i) const { return reinterpret_cast<T const *>(&data[stride * i]); } T *operator [] (unsigned i) { return reinterpret_cast<T *>(&data[stride * i]); } void zero () { memset(data, 0, row * stride); } void normalize2 () { #pragma omp parallel for for (unsigned i = 0; i < row; ++i) { T *p = operator[](i); double sum = metric::l2sqr::norm2(p, col); sum = std::sqrt(sum); for (unsigned j = 0; j < col; ++j) { p[j] /= sum; } } } void load (const std::string &path, unsigned dim, unsigned skip = 0, unsigned gap = 0) { std::ifstream is(path.c_str(), std::ios::binary); if (!is) throw io_error(path); is.seekg(0, std::ios::end); size_t size = is.tellg(); size -= skip; unsigned line = sizeof(T) * dim + gap; unsigned N = size / line; reset(N, dim); zero(); is.seekg(skip, std::ios::beg); for (unsigned i = 0; i < N; ++i) { is.read(&data[stride * i], sizeof(T) * dim); is.seekg(gap, std::ios::cur); } if (!is) throw io_error(path); } void load_lshkit (std::string const &path) { static const unsigned LSHKIT_HEADER = 3; std::ifstream is(path.c_str(), std::ios::binary); unsigned header[LSHKIT_HEADER]; /* entry size, row, col */ is.read((char *)header, sizeof header); if (!is) throw io_error(path); if (header[0] != sizeof(T)) throw io_error(path); is.close(); unsigned D = header[2]; unsigned skip = LSHKIT_HEADER * sizeof(unsigned); unsigned gap = 0; load(path, D, skip, gap); } void save_lshkit (std::string const &path) { std::ofstream os(path.c_str(), std::ios::binary); unsigned header[3]; assert(sizeof header == 3*4); header[0] = sizeof(T); header[1] = row; header[2] = col; os.write((const char *)header, sizeof(header)); for (unsigned i = 0; i < row; ++i) { os.write(&data[stride * i], sizeof(T) * col); } } }; /// Matrix proxy to interface with 3rd party libraries (FLANN, OpenCV, NumPy). template <typename DATA_TYPE, unsigned A = KGRAPH_MATRIX_ALIGN> class MatrixProxy { unsigned rows; unsigned cols; // # elements, not bytes, in a row, size_t stride; // # bytes in a row, >= cols * sizeof(element) uint8_t const *data; public: MatrixProxy (Matrix<DATA_TYPE> const &m) : rows(m.size()), cols(m.dim()), stride(m.step()), data(reinterpret_cast<uint8_t const *>(m[0])) { } #ifndef __AVX__ #ifdef FLANN_DATASET_H_ /// Construct from FLANN matrix. MatrixProxy (flann::Matrix<DATA_TYPE> const &m) : rows(m.rows), cols(m.cols), stride(m.stride), data(m.data) { if (stride % A) throw invalid_argument("bad alignment"); } #endif #ifdef __OPENCV_CORE_HPP__ /// Construct from OpenCV matrix. MatrixProxy (cv::Mat const &m) : rows(m.rows), cols(m.cols), stride(m.step), data(m.data) { if (stride % A) throw invalid_argument("bad alignment"); } #endif #ifdef NPY_NDARRAYOBJECT_H /// Construct from NumPy matrix. MatrixProxy (PyArrayObject *obj) { if (!obj || (obj->nd != 2)) throw invalid_argument("bad array shape"); rows = obj->dimensions[0]; cols = obj->dimensions[1]; stride = obj->strides[0]; data = reinterpret_cast<uint8_t const *>(obj->data); if (obj->descr->elsize != sizeof(DATA_TYPE)) throw invalid_argument("bad data type size"); if (stride % A) throw invalid_argument("bad alignment"); if (!(stride >= cols * sizeof(DATA_TYPE))) throw invalid_argument("bad stride"); } #endif #endif unsigned size () const { return rows; } unsigned dim () const { return cols; } DATA_TYPE const *operator [] (unsigned i) const { return reinterpret_cast<DATA_TYPE const *>(data + stride * i); } DATA_TYPE *operator [] (unsigned i) { return const_cast<DATA_TYPE *>(reinterpret_cast<DATA_TYPE const *>(data + stride * i)); } }; /// Oracle for Matrix or MatrixProxy. /** DATA_TYPE can be Matrix or MatrixProxy, * DIST_TYPE should be one class within the namespace kgraph.metric. */ template <typename DATA_TYPE, typename DIST_TYPE> class MatrixOracle: public kgraph::IndexOracle { MatrixProxy<DATA_TYPE> proxy; public: class SearchOracle: public kgraph::SearchOracle { MatrixProxy<DATA_TYPE> proxy; DATA_TYPE const *query; public: SearchOracle (MatrixProxy<DATA_TYPE> const &p, DATA_TYPE const *q): proxy(p), query(q) { } virtual unsigned size () const { return proxy.size(); } virtual float operator () (unsigned i) const { return DIST_TYPE::apply(proxy[i], query, proxy.dim()); } }; template <typename MATRIX_TYPE> MatrixOracle (MATRIX_TYPE const &m): proxy(m) { } virtual unsigned size () const { return proxy.size(); } virtual float operator () (unsigned i, unsigned j) const { return DIST_TYPE::apply(proxy[i], proxy[j], proxy.dim()); } SearchOracle query (DATA_TYPE const *query) const { return SearchOracle(proxy, query); } }; inline float AverageRecall (Matrix<float> const &gs, Matrix<float> const &result, unsigned K = 0) { if (K == 0) { K = result.dim(); } if (!(gs.dim() >= K)) throw invalid_argument("gs.dim() >= K"); if (!(result.dim() >= K)) throw invalid_argument("result.dim() >= K"); if (!(gs.size() >= result.size())) throw invalid_argument("gs.size() > result.size()"); float sum = 0; for (unsigned i = 0; i < result.size(); ++i) { float const *gs_row = gs[i]; float const *re_row = result[i]; // compare unsigned found = 0; unsigned gs_n = 0; unsigned re_n = 0; while ((gs_n < K) && (re_n < K)) { if (gs_row[gs_n] < re_row[re_n]) { ++gs_n; } else if (gs_row[gs_n] == re_row[re_n]) { ++found; ++gs_n; ++re_n; } else { throw runtime_error("distance is unstable"); } } sum += float(found) / K; } return sum / result.size(); } } #ifndef KGRAPH_NO_VECTORIZE #ifdef __GNUC__ #ifdef __AVX__ #if 0 namespace kgraph { namespace metric { template <> inline float l2sqr::apply<float> (float const *t1, float const *t2, unsigned dim) { return float_l2sqr_avx(t1, t2, dim); } }} #endif #else #ifdef __SSE2__ namespace kgraph { namespace metric { template <> inline float l2sqr::apply<float> (float const *t1, float const *t2, unsigned dim) { return float_l2sqr_sse2(t1, t2, dim); } template <> inline float l2sqr::dot<float> (float const *t1, float const *t2, unsigned dim) { return float_dot_sse2(t1, t2, dim); } template <> inline float l2sqr::norm2<float> (float const *t1, unsigned dim) { return float_l2sqr_sse2(t1, dim); } template <> inline float l2sqr::apply<uint8_t> (uint8_t const *t1, uint8_t const *t2, unsigned dim) { return uint8_l2sqr_sse2(t1, t2, dim); } }} #endif #endif #endif #endif #endif
pmv-OpenMP-a.c
#include <stdlib.h> #include <stdio.h> #include <time.h> //#define PRINT_ALL #define VECTOR_GLOBAL //#define VECTOR_DYNAMIC #ifdef VECTOR_GLOBAL #define MAX 1073741824 //=2^10 double v[MAX], m[MAX][MAX], r[MAX]; #endif int main(int argc,char** argv){ if (argc<2){ printf("Faltan nº componentes del vector \n"); exit(-1); } struct timespec cgt1,cgt2; double ncgt; //para tiempo de ejecución int i, j; unsigned int N = atoi(argv[1]); // Máximo N =2^32 -1=4294967295 (sizeof(unsigned int) = 4 B) #ifdef VECTOR_GLOBAL if (N>MAX) N=MAX; #endif #ifdef VECTOR_DYNAMIC double *v, **m, *r; v = (double*) malloc(N*sizeof(double)); // malloc necesita el tamaño en bytes m = (double**) malloc(N*sizeof(double*)); //si no hay espacio suficiente malloc devuelve NULL for (i=0; i<N; i++) m[i] = (double*) malloc(N*sizeof(double)); r = (double*) malloc(N*sizeof(double)); if ((v==NULL) || (m==NULL) || (r==NULL)) { printf("Error en la reserva de espacio para los vectores\n"); exit(-2); } #endif //Inicializar vector y matriz #pragma omp parallel for for (i=0; i<N; i++) { v[i] = N*0.1+ i*0.1; for (j=0; j<N; j++) m[i][j] = v[i]*0.1+j*0.1; } //Comprobamos la incialización #ifdef PRINT_ALL printf(" Vector:\n"); for (i=0; i<N; i++) { printf("\t%f", v[i]); } printf("\n\n Matriz: \n"); for (i=0; i<N; i++) { for (j=0; j<N; j++) printf("\t%f", m[i][j]); printf("\n\n"); } #endif clock_gettime(CLOCK_REALTIME,&cgt1); //Calcular el producto int sum; #pragma omp parallel for private(j, sum) for (i=0; i<N; i++) { sum = 0; for (j=0; j<N; j++) sum += m[i][j]*v[j]; r[i] = sum; } clock_gettime(CLOCK_REALTIME,&cgt2); ncgt = (double) (cgt2.tv_sec - cgt1.tv_sec) + (double) ((cgt2.tv_nsec - cgt1.tv_nsec)/(1.e+9)); //Imprimir resultado del producto printf("\n Resultado:\n"); #ifdef PRINT_ALL for (i=0; i<N; i++) { printf("\t%f", r[i]); } printf("\n"); #else printf("Primer valor: %f \t Último valor: %f \n", r[0], r[N-1]); #endif printf("\n Tiempo de ejecución(s): %11.9f\n", ncgt); #ifdef VECTOR_DYNAMIC free(v); // libera el espacio reservado para v free(m); // libera el espacio reservado para m free(r); #endif return 0; }
GB_binop__bshift_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__bshift_uint64) // A.*B function (eWiseMult): GB (_AemultB_01__bshift_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__bshift_uint64) // A.*B function (eWiseMult): GB (_AemultB_03__bshift_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bshift_uint64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bshift_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__bshift_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bshift_uint64) // C=scalar+B GB (_bind1st__bshift_uint64) // C=scalar+B' GB (_bind1st_tran__bshift_uint64) // C=A+scalar GB (_bind2nd__bshift_uint64) // C=A'+scalar GB (_bind2nd_tran__bshift_uint64) // C type: uint64_t // A type: uint64_t // B,b type: int8_t // BinaryOp: cij = GB_bitshift_uint64 (aij, bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 0 // 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 \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_bitshift_uint64 (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // 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_BSHIFT || GxB_NO_UINT64 || GxB_NO_BSHIFT_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__bshift_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bshift_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bshift_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type 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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bshift_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *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__bshift_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__bshift_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__bshift_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__bshift_uint64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bshift_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_bitshift_uint64 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bshift_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; 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 ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = GB_bitshift_uint64 (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_bitshift_uint64 (x, aij) ; \ } GrB_Info GB (_bind1st_tran__bshift_uint64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_bitshift_uint64 (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__bshift_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
threshold.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2018 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://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/property.h" #include "MagickCore/blob.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/configure.h" #include "MagickCore/constitute.h" #include "MagickCore/decorate.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/effect.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/montage.h" #include "MagickCore/option.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/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/shear.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ static const char *MinimalThresholdMap = "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; /* Forward declarations. */ static ThresholdMap *GetThresholdMapFile(const char *,const char *,const char *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image,const size_t width, % const size_t height,const double bias,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o bias: the mean bias. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (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); threshold_image=CloneImage(image,0,0,MagickTrue, exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveThresholdImage) #endif proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoThresholdImage() automatically selects a threshold and replaces each % pixel in the image with a black pixel if the image intentsity is less than % the selected threshold otherwise white. % % The format of the AutoThresholdImage method is: % % MagickBooleanType AutoThresholdImage(Image *image, % const AutoThresholdMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-threshold. % % o method: choose from Kapur, OTSU, or Triangle. % % o exception: return any errors or warnings in this structure. % */ static double KapurThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { #define MaxIntensity 255 double *black_entropy, *cumulative_histogram, entropy, epsilon, maximum_entropy, *white_entropy; register ssize_t i, j; size_t threshold; /* Compute optimal threshold from the entopy of the histogram. */ cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*cumulative_histogram)); black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*black_entropy)); white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*white_entropy)); if ((cumulative_histogram == (double *) NULL) || (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL)) { if (white_entropy != (double *) NULL) white_entropy=(double *) RelinquishMagickMemory(white_entropy); if (black_entropy != (double *) NULL) black_entropy=(double *) RelinquishMagickMemory(black_entropy); if (cumulative_histogram != (double *) NULL) cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Entropy for black and white parts of the histogram. */ cumulative_histogram[0]=histogram[0]; for (i=1; i <= MaxIntensity; i++) cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i]; epsilon=MagickMinimumValue; for (j=0; j <= MaxIntensity; j++) { /* Black entropy. */ black_entropy[j]=0.0; if (cumulative_histogram[j] > epsilon) { entropy=0.0; for (i=0; i <= j; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/cumulative_histogram[j]* log(histogram[i]/cumulative_histogram[j]); black_entropy[j]=entropy; } /* White entropy. */ white_entropy[j]=0.0; if ((1.0-cumulative_histogram[j]) > epsilon) { entropy=0.0; for (i=j+1; i <= MaxIntensity; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/(1.0-cumulative_histogram[j])* log(histogram[i]/(1.0-cumulative_histogram[j])); white_entropy[j]=entropy; } } /* Find histogram bin with maximum entropy. */ maximum_entropy=black_entropy[0]+white_entropy[0]; threshold=0; for (j=1; j <= MaxIntensity; j++) if ((black_entropy[j]+white_entropy[j]) > maximum_entropy) { maximum_entropy=black_entropy[j]+white_entropy[j]; threshold=(size_t) j; } /* Free resources. */ white_entropy=(double *) RelinquishMagickMemory(white_entropy); black_entropy=(double *) RelinquishMagickMemory(black_entropy); cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); return(100.0*threshold/MaxIntensity); } static double OTSUThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double max_sigma, *myu, *omega, *probability, *sigma, threshold; register ssize_t i; /* Compute optimal threshold from maximization of inter-class variance. */ myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu)); omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega)); probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*probability)); sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma)); if ((myu == (double *) NULL) || (omega == (double *) NULL) || (probability == (double *) NULL) || (sigma == (double *) NULL)) { if (sigma != (double *) NULL) sigma=(double *) RelinquishMagickMemory(sigma); if (probability != (double *) NULL) probability=(double *) RelinquishMagickMemory(probability); if (omega != (double *) NULL) omega=(double *) RelinquishMagickMemory(omega); if (myu != (double *) NULL) myu=(double *) RelinquishMagickMemory(myu); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Calculate probability density. */ for (i=0; i <= (ssize_t) MaxIntensity; i++) probability[i]=histogram[i]; /* Generate probability of graylevels and mean value for separation. */ omega[0]=probability[0]; myu[0]=0.0; for (i=1; i <= (ssize_t) MaxIntensity; i++) { omega[i]=omega[i-1]+probability[i]; myu[i]=myu[i-1]+i*probability[i]; } /* Sigma maximization: inter-class variance and compute optimal threshold. */ threshold=0; max_sigma=0.0; for (i=0; i < (ssize_t) MaxIntensity; i++) { sigma[i]=0.0; if ((omega[i] != 0.0) && (omega[i] != 1.0)) sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0- omega[i])); if (sigma[i] > max_sigma) { max_sigma=sigma[i]; threshold=(double) i; } } /* Free resources. */ myu=(double *) RelinquishMagickMemory(myu); omega=(double *) RelinquishMagickMemory(omega); probability=(double *) RelinquishMagickMemory(probability); sigma=(double *) RelinquishMagickMemory(sigma); return(100.0*threshold/MaxIntensity); } static double TriangleThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double a, b, c, count, distance, inverse_ratio, max_distance, segment, x1, x2, y1, y2; register ssize_t i; ssize_t end, max, start, threshold; /* Compute optimal threshold with triangle algorithm. */ (void) exception; start=0; /* find start bin, first bin not zero count */ for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > 0.0) { start=i; break; } end=0; /* find end bin, last bin not zero count */ for (i=(ssize_t) MaxIntensity; i >= 0; i--) if (histogram[i] > 0.0) { end=i; break; } max=0; /* find max bin, bin with largest count */ count=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > count) { max=i; count=histogram[i]; } /* Compute threshold at split point. */ x1=(double) max; y1=histogram[max]; x2=(double) end; if ((max-start) >= (end-max)) x2=(double) start; y2=0.0; a=y1-y2; b=x2-x1; c=(-1.0)*(a*x1+b*y1); inverse_ratio=1.0/sqrt(a*a+b*b+c*c); threshold=0; max_distance=0.0; if (x2 == (double) start) for (i=start; i < max; i++) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment > 0.0)) { threshold=i; max_distance=distance; } } else for (i=end; i > max; i--) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment < 0.0)) { threshold=i; max_distance=distance; } } return(100.0*threshold/MaxIntensity); } MagickExport MagickBooleanType AutoThresholdImage(Image *image, const AutoThresholdMethod method,ExceptionInfo *exception) { CacheView *image_view; char property[MagickPathExtent]; double gamma, *histogram, sum, threshold; MagickBooleanType status; register ssize_t i; ssize_t y; /* Form histogram. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; (void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { double intensity = GetPixelIntensity(image,p); histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Normalize histogram. */ sum=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) sum+=histogram[i]; gamma=PerceptibleReciprocal(sum); for (i=0; i <= (ssize_t) MaxIntensity; i++) histogram[i]=gamma*histogram[i]; /* Discover threshold from histogram. */ switch (method) { case KapurThresholdMethod: { threshold=KapurThreshold(image,histogram,exception); break; } case OTSUThresholdMethod: default: { threshold=OTSUThreshold(image,histogram,exception); break; } case TriangleThresholdMethod: { threshold=TriangleThreshold(image,histogram,exception); break; } } histogram=(double *) RelinquishMagickMemory(histogram); if (threshold < 0.0) status=MagickFalse; if (status == MagickFalse) return(MagickFalse); /* Threshold image. */ (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold); (void) SetImageProperty(image,"auto-threshold:threshold",property,exception); return(BilevelImage(image,QuantumRange*threshold/100.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImage method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold values. % % o exception: return any errors or warnings in this structure. % % Aside: You can get the same results as operator using LevelImages() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); /* Bilevel threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register 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++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); 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 (image->channel_mask != DefaultChannels) pixel=(double) q[i]; q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange); } 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 critical (MagickCore_BilevelImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register 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++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); 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 (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel < GetPixelInfoChannel(&threshold,channel)) q[i]=(Quantum) 0; } 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 critical (MagickCore_BlackThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImage method is: % % MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception) { #define ClampImageTag "Clamp/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelInfo *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) ClampPixel(q->red); q->green=(double) ClampPixel(q->green); q->blue=(double) ClampPixel(q->blue); q->alpha=(double) ClampPixel(q->alpha); q++; } return(SyncImage(image,exception)); } /* Clamp image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register 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++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampPixel((MagickRealType) q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ClampImage) #endif proceed=SetImageProgress(image,ClampImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() loads and searches one or more threshold map files for the % map matching the given name or alias. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { ThresholdMap *map; map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) { const StringInfo *option; LinkedListInfo *options; options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); } #endif return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename, const char *map_id,ExceptionInfo *exception) { char *p; const char *attribute, *content; double value; register ssize_t i; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); map=(ThresholdMap *) NULL; thresholds=NewXMLTree(xml,exception); if (thresholds == (XMLTreeInfo *) NULL) return(map); for (threshold=GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { attribute=GetXMLTreeAttribute(threshold,"map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold,"alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } map=(ThresholdMap *) AcquireCriticalMemory(sizeof(*map)); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); for (i=0; i < (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { const char *alias, *content, *map; XMLTreeInfo *description, *threshold, *thresholds; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); threshold=GetXMLTreeChild(thresholds,"threshold"); for ( ; threshold != (XMLTreeInfo *) NULL; threshold=GetNextXMLTreeTag(threshold)) { map=GetXMLTreeAttribute(threshold,"map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias=GetXMLTreeAttribute(threshold,"alias"); description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"",map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; char token[MagickPathExtent]; const char *p; double levels[CompositePixelChannel]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; ThresholdMap *map; assert(image != (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); if (threshold_map == (const char *) NULL) return(MagickTrue); p=(char *) threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MagickPathExtent-1)) break; token[p-threshold_map]=(*p); p++; } token[p-threshold_map]='\0'; map=GetThresholdMap(token,exception); if (map == (ThresholdMap *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } for (i=0; i < MaxPixelChannels; i++) levels[i]=2.0; p=strchr((char *) threshold_map,','); if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0)) { GetNextToken(p,&p,MagickPathExtent,token); for (i=0; (i < MaxPixelChannels); i++) levels[i]=StringToDouble(token,(char **) NULL); for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); levels[i]=StringToDouble(token,(char **) NULL); } } for (i=0; i < MaxPixelChannels; i++) if (fabs(levels[i]) >= 1) levels[i]-=1.0; if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register 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++) { register ssize_t i; ssize_t n; n=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ssize_t level, threshold; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (fabs(levels[n]) < MagickEpsilon) { n++; continue; } threshold=(ssize_t) (QuantumScale*q[i]*(levels[n]*(map->divisor-1)+1)); level=threshold/(map->divisor-1); threshold-=level*(map->divisor-1); q[i]=ClampToQuantum((double) (level+(threshold >= map->levels[(x % map->width)+map->width*(y % map->height)]))* QuantumRange/levels[n]); n++; } 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 critical (MagickCore_OrderedDitherImage) #endif proceed=SetImageProgress(image,DitherImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImage method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon,ExceptionInfo *exception) { #define PerceptibleImageTag "Perceptible/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelInfo *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red), epsilon); q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green), epsilon); q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue), epsilon); q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha), epsilon); q++; } return(SyncImage(image,exception)); } /* Perceptible image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register 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++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PerceptibleThreshold(q[i],epsilon); } 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 critical (MagickCore_PerceptibleImage) #endif proceed=SetImageProgress(image,PerceptibleImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImage(Image *image, % const char *thresholds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low,high: Specify the high and low thresholds. These values range from % 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const double min_threshold, const double max_threshold,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (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); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); GetPixelInfo(image,&threshold); /* Random threshold image. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double threshold; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((double) q[i] < min_threshold) threshold=min_threshold; else if ((double) q[i] > max_threshold) threshold=max_threshold; else threshold=(double) (QuantumRange* GetPseudoRandomValue(random_info[id])); q[i]=(double) q[i] <= threshold ? 0 : QuantumRange; } 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 critical (MagickCore_RandomThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image, % const char *threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; PixelInfo threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); GetPixelInfo(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.rho; threshold.blue=geometry_info.rho; threshold.black=geometry_info.rho; threshold.alpha=100.0; if ((flags & SigmaValue) != 0) threshold.green=geometry_info.sigma; if ((flags & XiValue) != 0) threshold.blue=geometry_info.xi; if ((flags & PsiValue) != 0) threshold.alpha=geometry_info.psi; if (threshold.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) threshold.black=geometry_info.psi; if ((flags & ChiValue) != 0) threshold.alpha=geometry_info.chi; } if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.black*=(MagickRealType) (QuantumRange/100.0); threshold.alpha*=(MagickRealType) (QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register 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++) { double pixel; register ssize_t i; pixel=GetPixelIntensity(image,q); 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 (image->channel_mask != DefaultChannels) pixel=(double) q[i]; if (pixel > GetPixelInfoChannel(&threshold,channel)) q[i]=QuantumRange; } 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 critical (MagickCore_WhiteThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
H2ERI_partition.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include "CMS.h" #include "H2ERI_typedef.h" #include "H2Pack_partition.h" #include "H2Pack_utils.h" #include "H2ERI_build_exchange.h" // Partition screened shell pair centers (as points) for H2 tree // Input parameters: // h2eri->num_sp : Number of screened shell pairs (SSP) // h2eri->sp : Array, size 2 * num_sp, SSP // h2eri->sp_center : Array, size 3 * num_sp, centers of SSP // h2eri->sp_extent : Array, size num_sp, extents of SSP // max_leaf_points : Maximum number of point in a leaf node's box. If <= 0, // will use 300. // max_leaf_size : Maximum size of a leaf node's box. // Output parameter: // h2eri->h2pack : H2Pack structure with point partitioning info // h2eri->sp : Array, size 2 * num_sp, sorted SSP // h2eri->sp_center : Array, size 3 * num_sp, sorted centers of SSP // h2eri->sp_extent : Array, size num_sp, sorted extents of SSP void H2ERI_partition_sp_centers(H2ERI_p h2eri, int max_leaf_points, double max_leaf_size) { // 1. Partition screened shell pair centers int num_sp = h2eri->num_sp; double *sp_center = h2eri->sp_center; if (max_leaf_points <= 0) max_leaf_points = 300; if (max_leaf_size <= 0.0) max_leaf_size = 1.0; // Manually set the kernel matrix size for h2eri->h2pack->tb allocation. shell_t *sp_shells = h2eri->sp_shells; int num_sp_bfp = 0; for (int i = 0; i < num_sp; i++) { int am0 = sp_shells[i].am; int am1 = sp_shells[i + num_sp].am; num_sp_bfp += NCART(am0) * NCART(am1); } h2eri->h2pack->krnl_mat_size = num_sp_bfp; h2eri->h2pack->is_H2ERI = 1; // Tell H2Pack not to set krnl_mat_size and mat_cluster H2P_partition_points( h2eri->h2pack, num_sp, sp_center, max_leaf_points, max_leaf_size ); memcpy(sp_center, h2eri->h2pack->coord, sizeof(double) * 3 * num_sp); // 2. Permute the screened shell pairs and their extents according to // the permutation of their center coordinate int *coord_idx = h2eri->h2pack->coord_idx; double *sp_extent = h2eri->sp_extent; int *sp_shell_idx = h2eri->sp_shell_idx; shell_t *sp_shells_new = (shell_t *) malloc(sizeof(shell_t) * num_sp * 2); double *sp_extent_new = (double *) malloc(sizeof(double) * num_sp); int *sp_shell_idx_new = (int *) malloc(sizeof(int) * num_sp * 2); assert(sp_shells_new != NULL && sp_extent_new != NULL); assert(sp_shell_idx_new != NULL); for (int i = 0; i < num_sp; i++) { int cidx_i = coord_idx[i]; int i20 = i, i21 = i + num_sp; int cidx_i20 = cidx_i, cidx_i21 = cidx_i + num_sp; sp_extent_new[i] = sp_extent[cidx_i]; simint_initialize_shell(&sp_shells_new[i20]); simint_initialize_shell(&sp_shells_new[i21]); simint_allocate_shell(sp_shells[cidx_i20].nprim, &sp_shells_new[i20]); simint_allocate_shell(sp_shells[cidx_i21].nprim, &sp_shells_new[i21]); simint_copy_shell(&sp_shells[cidx_i20], &sp_shells_new[i20]); simint_copy_shell(&sp_shells[cidx_i21], &sp_shells_new[i21]); sp_shell_idx_new[i20] = sp_shell_idx[cidx_i20]; sp_shell_idx_new[i21] = sp_shell_idx[cidx_i21]; } CMS_destroy_shells(num_sp * 2, h2eri->sp_shells); free(h2eri->sp_shells); free(h2eri->sp_extent); free(h2eri->sp_shell_idx); h2eri->sp_shells = sp_shells_new; h2eri->sp_extent = sp_extent_new; h2eri->sp_shell_idx = sp_shell_idx_new; // 3. Initialize shell pairs. Note that Simint MATLAB code uses (NM|QP) instead // of the normal (MN|PQ) order for ERI. We follow this for the moment. h2eri->sp = (multi_sp_t *) malloc(sizeof(multi_sp_t) * num_sp); h2eri->index_seq = (int *) malloc(sizeof(int) * num_sp); assert(h2eri->sp != NULL && h2eri->index_seq != NULL); for (int i = 0; i < num_sp; i++) { h2eri->index_seq[i] = i; simint_initialize_multi_shellpair(&h2eri->sp[i]); simint_create_multi_shellpair( 1, &h2eri->sp_shells[i + num_sp], 1, &h2eri->sp_shells[i], &h2eri->sp[i], SIMINT_SCREEN_NONE ); } } // Calculate the basis function indices information of shells and shell pairs // Input parameters: // h2eri->num_sp : Number of shell pairs // h2eri->sp : Array, size num_sp * 2, each row is a screened shell pair // Output parameters: // h2eri->shell_bf_sidx : Array, size nshell, indices of each shell's first basis function // h2eri->sp_nbfp : Array, size num_sp, number of basis function pairs of each SSP // h2eri->sp_bfp_sidx : Array, size num_sp+1, indices of each SSP first basis function pair void H2ERI_calc_bf_bfp_info(H2ERI_p h2eri) { int nshell = h2eri->nshell; int num_sp = h2eri->num_sp; shell_t *shells = h2eri->shells; shell_t *sp_shells = h2eri->sp_shells; h2eri->shell_bf_sidx = (int *) malloc(sizeof(int) * (nshell + 1)); h2eri->sp_nbfp = (int *) malloc(sizeof(int) * num_sp); h2eri->sp_bfp_sidx = (int *) malloc(sizeof(int) * (num_sp + 1)); assert(h2eri->shell_bf_sidx != NULL && h2eri->sp_nbfp != NULL); assert(h2eri->sp_bfp_sidx != NULL); h2eri->shell_bf_sidx[0] = 0; for (int i = 0; i < nshell; i++) { int am = shells[i].am; h2eri->shell_bf_sidx[i + 1] = h2eri->shell_bf_sidx[i] + NCART(am); h2eri->max_am = MAX(h2eri->max_am, am); } h2eri->num_bf = h2eri->shell_bf_sidx[nshell]; h2eri->max_shell_nbf = NCART(h2eri->max_am); h2eri->sp_bfp_sidx[0] = 0; for (int i = 0; i < num_sp; i++) { int am0 = sp_shells[i].am; int am1 = sp_shells[i + num_sp].am; int nbf0 = NCART(am0); int nbf1 = NCART(am1); int nbfp = nbf0 * nbf1; h2eri->sp_nbfp[i] = nbfp; h2eri->sp_bfp_sidx[i + 1] = h2eri->sp_bfp_sidx[i] + nbfp; } h2eri->num_sp_bfp = h2eri->sp_bfp_sidx[num_sp]; } // Calculate the max extent of shell pairs in each H2 box // Input parameters: // h2eri->h2pack : H2 tree partitioning info // h2eri->num_sp : Number of SSP // h2eri->sp_center : Array, size 3 * num_sp, centers of SSP, sorted // h2eri->sp_extent : Array, size num_sp, extents of SSP, sorted // Output parameter: // h2eri->box_extent : Array, size h2pack->n_node, extent of each H2 node box void H2ERI_calc_box_extent(H2ERI_p h2eri) { H2Pack_p h2pack = h2eri->h2pack; int n_node = h2pack->n_node; int max_level = h2pack->max_level; int max_child = h2pack->max_child; int n_leaf_node = h2pack->n_leaf_node; int *pt_cluster = h2pack->pt_cluster; int *children = h2pack->children; int *n_child = h2pack->n_child; int *level_nodes = h2pack->level_nodes; int *level_n_node = h2pack->level_n_node; double *enbox = h2pack->enbox; int num_sp = h2eri->num_sp; double *sp_center = h2eri->sp_center; double *sp_extent = h2eri->sp_extent; h2eri->box_extent = (double *) malloc(sizeof(double) * n_node); assert(h2eri->box_extent != NULL); double *box_extent = h2eri->box_extent; for (int i = max_level; i >= 1; i--) { int *level_i_nodes = level_nodes + i * n_leaf_node; int level_i_n_node = level_n_node[i]; for (int j = 0; j < level_i_n_node; j++) { int node = level_i_nodes[j]; double *node_enbox = enbox + 6 * node; double enbox_center[3]; enbox_center[0] = node_enbox[0] + 0.5 * node_enbox[3]; enbox_center[1] = node_enbox[1] + 0.5 * node_enbox[4]; enbox_center[2] = node_enbox[2] + 0.5 * node_enbox[5]; int n_child_node = n_child[node]; if (n_child_node == 0) { int pt_s = pt_cluster[2 * node]; int pt_e = pt_cluster[2 * node + 1]; double box_extent_node = 0.0; for (int d = 0; d < 3; d++) { double *center_d = sp_center + d * num_sp; double enbox_width_d = node_enbox[3 + d]; for (int k = pt_s; k <= pt_e; k++) { double tmp_extent_d_k; // Distance of shell pair center to the upper limit along each dimension tmp_extent_d_k = fabs(center_d[k] - enbox_center[d]); tmp_extent_d_k = 0.5 * enbox_width_d - tmp_extent_d_k; // Outreach of each extent box tmp_extent_d_k = sp_extent[k] - tmp_extent_d_k; // Ratio of extent box outreach over enclosing box size tmp_extent_d_k /= enbox_width_d; // Negative means this dimension of extent box is inside the // enclosing box, make it 0.1 to make sure the box_extent >= 1 tmp_extent_d_k = MAX(tmp_extent_d_k, 0.1); box_extent_node = MAX(box_extent_node, tmp_extent_d_k); } } box_extent[node] = ceil(box_extent_node); } else { // Since the out-reach width is the same, the extent of this box // (outreach / box width) is just half of the largest sub-box extent. double box_extent_node = 0.0; int *child_nodes = children + node * max_child; for (int k = 0; k < n_child_node; k++) { int child_k = child_nodes[k]; box_extent_node = MAX(box_extent_node, box_extent[child_k]); } box_extent[node] = ceil(0.5 * box_extent_node); } // End of "if (n_child_node == 0)" } // End of j loop } // End of i loop } // Calculate the matvec cluster for H2 nodes // Input parameters: // h2eri->h2pack : H2 tree partitioning info // h2eri->sp_bfp_sidx : Array, size num_sp+1, indices of each SSP first basis function pair // Output parameter: // h2eri->h2pack->mat_cluster : Array, size h2pack->n_node * 2, matvec cluster for H2 nodes void H2ERI_calc_mat_cluster(H2ERI_p h2eri) { H2Pack_p h2pack = h2eri->h2pack; int n_node = h2pack->n_node; int max_child = h2pack->max_child; int *pt_cluster = h2pack->pt_cluster; int *children = h2pack->children; int *n_child = h2pack->n_child; int *mat_cluster = h2pack->mat_cluster; int *sp_bfp_sidx = h2eri->sp_bfp_sidx; int offset = 0; for (int i = 0; i < n_node; i++) { int i20 = i * 2; int i21 = i * 2 + 1; int n_child_i = n_child[i]; if (n_child_i == 0) { int pt_s = pt_cluster[2 * i]; int pt_e = pt_cluster[2 * i + 1]; int node_nbf = sp_bfp_sidx[pt_e + 1] - sp_bfp_sidx[pt_s]; mat_cluster[i20] = offset; mat_cluster[i21] = offset + node_nbf - 1; offset += node_nbf; } else { int *i_childs = children + i * max_child; int child_0 = i_childs[0]; int child_n = i_childs[n_child_i - 1]; mat_cluster[i20] = mat_cluster[2 * child_0]; mat_cluster[i21] = mat_cluster[2 * child_n + 1]; } } } // Find each node's admissible and inadmissible pair nodes // Input parameter: // h2eri->h2pack : H2 tree partitioning info // Output parameters: // h2eri->node_adm_pairs : Array, size unknown, each node's admissible node pairs // h2eri->node_adm_pairs_sidx : Array, size h2pack->n_node+1, index of each node's first admissible node pair // h2eri->node_inadm_pairs : Array, size unknown, each node's inadmissible node pairs // h2eri->node_inadm_pairs_sidx : Array, size h2pack->n_node+1, index of each node's first inadmissible node pair void H2ERI_calc_node_adm_inadm_pairs(H2ERI_p h2eri) { H2Pack_p h2pack = h2eri->h2pack; int n_node = h2pack->n_node; int n_node1 = h2pack->n_node + 1; int n_leaf_node = h2pack->n_leaf_node; int n_r_adm_pair = h2pack->n_r_adm_pair; int n_r_inadm_pair = h2pack->n_r_inadm_pair; int n_adm_pair = 2 * n_r_adm_pair; int n_inadm_pair = 2 * n_r_inadm_pair + n_leaf_node; int *r_adm_pairs = h2pack->r_adm_pairs; int *r_inadm_pairs = h2pack->r_inadm_pairs; int *leaf_nodes = h2pack->height_nodes; int *node_adm_pairs_sidx = (int *) malloc(sizeof(int) * n_node1); int *node_inadm_pairs_sidx = (int *) malloc(sizeof(int) * n_node1); int *node_adm_pairs = (int *) malloc(sizeof(int) * n_adm_pair); int *node_inadm_pairs = (int *) malloc(sizeof(int) * n_inadm_pair); ASSERT_PRINTF(node_adm_pairs_sidx != NULL, "Failed to allocate node_adm_pairs_sidx of size %d\n", n_node1); ASSERT_PRINTF(node_inadm_pairs_sidx != NULL, "Failed to allocate node_inadm_pairs_sidx of size %d\n", n_node1); ASSERT_PRINTF(node_adm_pairs != NULL, "Failed to allocate node_adm_pairs of size %d\n", n_adm_pair); ASSERT_PRINTF(node_inadm_pairs != NULL, "Failed to allocate node_inadm_pairs of size %d\n", n_inadm_pair); memset(node_adm_pairs_sidx, 0, sizeof(int) * n_node1); for (int i = 0; i < n_r_adm_pair; i++) { int node0 = r_adm_pairs[2 * i]; int node1 = r_adm_pairs[2 * i + 1]; node_adm_pairs_sidx[node0 + 1]++; node_adm_pairs_sidx[node1 + 1]++; } for (int i = 2; i <= n_node; i++) node_adm_pairs_sidx[i] += node_adm_pairs_sidx[i - 1]; for (int i = 0; i < n_r_adm_pair; i++) { int node0 = r_adm_pairs[2 * i]; int node1 = r_adm_pairs[2 * i + 1]; int idx0 = node_adm_pairs_sidx[node0]; int idx1 = node_adm_pairs_sidx[node1]; node_adm_pairs[idx0] = node1; node_adm_pairs[idx1] = node0; node_adm_pairs_sidx[node0]++; node_adm_pairs_sidx[node1]++; } for (int i = n_node; i >= 1; i--) node_adm_pairs_sidx[i] = node_adm_pairs_sidx[i - 1]; node_adm_pairs_sidx[0] = 0; memset(node_inadm_pairs_sidx, 0, sizeof(int) * n_node1); for (int i = 0; i < n_leaf_node; i++) { int node0 = leaf_nodes[i]; node_inadm_pairs_sidx[node0 + 1]++; } for (int i = 0; i < n_r_inadm_pair; i++) { int node0 = r_inadm_pairs[2 * i]; int node1 = r_inadm_pairs[2 * i + 1]; node_inadm_pairs_sidx[node0 + 1]++; node_inadm_pairs_sidx[node1 + 1]++; } for (int i = 2; i <= n_node; i++) node_inadm_pairs_sidx[i] += node_inadm_pairs_sidx[i - 1]; for (int i = 0; i < n_leaf_node; i++) { int node0 = leaf_nodes[i]; int idx0 = node_inadm_pairs_sidx[node0]; node_inadm_pairs[idx0] = node0; node_inadm_pairs_sidx[node0]++; } for (int i = 0; i < n_r_inadm_pair; i++) { int node0 = r_inadm_pairs[2 * i]; int node1 = r_inadm_pairs[2 * i + 1]; int idx0 = node_inadm_pairs_sidx[node0]; int idx1 = node_inadm_pairs_sidx[node1]; node_inadm_pairs[idx0] = node1; node_inadm_pairs[idx1] = node0; node_inadm_pairs_sidx[node0]++; node_inadm_pairs_sidx[node1]++; } for (int i = n_node; i >= 1; i--) node_inadm_pairs_sidx[i] = node_inadm_pairs_sidx[i - 1]; node_inadm_pairs_sidx[0] = 0; h2eri->node_adm_pairs_sidx = node_adm_pairs_sidx; h2eri->node_inadm_pairs_sidx = node_inadm_pairs_sidx; h2eri->node_adm_pairs = node_adm_pairs; h2eri->node_inadm_pairs = node_inadm_pairs; } // Calculate plist, plist_idx, plist_sidx for exchange matrix construction // Input parameters: // h2eri->nshell : Number of shells // h2eri->num_sp : Number of screened shell pairs (SSP) // h2eri->sp_shell_idx : Array, size 2 * num_sp, each row is the contracted shell indices of a SSP // Output parameters: // h2eri->plist : Array, size unknown, each shell's screened pair shells // h2eri->plist_idx : Array, size unknown, corresponding indices of each shell's screened pair shells in sp_bfp_sidx // h2eri->plist_sidx : Array, size nshell+1, index of each node's first item in plist & plist_idx void H2ERI_build_plist(H2ERI_p h2eri) { int nshell = h2eri->nshell; int nshell1 = nshell + 1; int num_sp = h2eri->num_sp; int *sp_shell_idx = h2eri->sp_shell_idx; int *plist = (int *) malloc(sizeof(int) * 2 * num_sp); int *plist_idx = (int *) malloc(sizeof(int) * 2 * num_sp); int *plist_sidx = (int *) malloc(sizeof(int) * nshell1); ASSERT_PRINTF(plist != NULL, "Failed to allocate plist of size %d\n", 2 * num_sp); ASSERT_PRINTF(plist_idx != NULL, "Failed to allocate plist_idx of size %d\n", 2 * num_sp); ASSERT_PRINTF(plist_sidx != NULL, "Failed to allocate plist_sidx of size %d\n", nshell1); memset(plist_sidx, 0, sizeof(int) * nshell1); for (int i = 0; i < num_sp; i++) { int i20 = i, i21 = i + num_sp; int shell0 = sp_shell_idx[i20]; int shell1 = sp_shell_idx[i21]; plist_sidx[shell0 + 1]++; if (shell0 != shell1) plist_sidx[shell1 + 1]++; } for (int i = 2; i <= nshell; i++) plist_sidx[i] += plist_sidx[i - 1]; for (int i = 0; i < num_sp; i++) { int i20 = i, i21 = i + num_sp; int shell0 = sp_shell_idx[i20]; int shell1 = sp_shell_idx[i21]; int idx0 = plist_sidx[shell0]; plist[idx0] = shell1; plist_idx[idx0] = i; plist_sidx[shell0]++; if (shell0 != shell1) { int idx1 = plist_sidx[shell1]; plist[idx1] = shell0; plist_idx[idx1] = i; plist_sidx[shell1]++; } } for (int i = nshell; i >= 1; i--) plist_sidx[i] = plist_sidx[i - 1]; plist_sidx[0] = 0; #pragma omp parallel for schedule(dynamic) for (int i = 0; i < nshell; i++) { int sidx = plist_sidx[i]; int len = plist_sidx[i + 1] - sidx; H2P_qsort_int_key_val(plist + sidx, plist_idx + sidx, 0, len - 1); } h2eri->plist = plist; h2eri->plist_idx = plist_idx; h2eri->plist_sidx = plist_sidx; } // H2 partition of screened shell pair centers void H2ERI_partition(H2ERI_p h2eri) { H2ERI_partition_sp_centers(h2eri, 0, 0.0); H2ERI_calc_bf_bfp_info(h2eri); H2ERI_calc_box_extent (h2eri); H2ERI_calc_mat_cluster(h2eri); H2ERI_calc_node_adm_inadm_pairs(h2eri); H2ERI_build_plist(h2eri); H2ERI_exchange_workbuf_init(h2eri); // Initialize thread local Simint buffer int n_thread = h2eri->h2pack->n_thread; h2eri->simint_buffs = (simint_buff_p*) malloc(sizeof(simint_buff_p) * n_thread); h2eri->eri_batch_buffs = (eri_batch_buff_p*) malloc(sizeof(eri_batch_buff_p) * n_thread); assert(h2eri->simint_buffs != NULL); assert(h2eri->eri_batch_buffs != NULL); for (int i = 0; i < n_thread; i++) { CMS_init_Simint_buff(h2eri->max_am, &h2eri->simint_buffs[i]); CMS_init_eri_batch_buff(h2eri->max_am, 4, &h2eri->eri_batch_buffs[i]); } }
kmp_sch_simd_runtime_guided.c
// RUN: %libomp-compile // RUN: env OMP_SCHEDULE=guided %libomp-run // RUN: env OMP_SCHEDULE=guided,1 %libomp-run 1 // RUN: env OMP_SCHEDULE=guided,2 %libomp-run 2 // RUN: env OMP_SCHEDULE=dynamic %libomp-run // RUN: env OMP_SCHEDULE=dynamic,1 %libomp-run 1 // RUN: env OMP_SCHEDULE=dynamic,2 %libomp-run 2 // RUN: env OMP_SCHEDULE=auto %libomp-run // The test checks schedule(simd:runtime) // in combination with OMP_SCHEDULE=guided[,chunk] #include <stdio.h> #include <stdlib.h> #include <omp.h> #if defined(WIN32) || defined(_WIN32) #include <windows.h> #define delay() Sleep(1); #define seten(a,b,c) _putenv_s((a),(b)) #else #include <unistd.h> #define delay() usleep(10); #define seten(a,b,c) setenv((a),(b),(c)) #endif #define UBOUND 100 #define SIMD_LEN 4 int err = 0; // --------------------------------------------------------------------------- // Various definitions copied from OpenMP RTL. enum sched { kmp_sch_static_balanced_chunked = 45, kmp_sch_guided_simd = 46, kmp_sch_runtime_simd = 47, }; typedef unsigned u32; typedef long long i64; typedef unsigned long long u64; typedef struct { int reserved_1; int flags; int reserved_2; int reserved_3; char *psource; } id; #ifdef __cplusplus extern "C" { #endif int __kmpc_global_thread_num(id*); void __kmpc_barrier(id*, int gtid); void __kmpc_dispatch_init_4(id*, int, enum sched, int, int, int, int); void __kmpc_dispatch_init_8(id*, int, enum sched, i64, i64, i64, i64); int __kmpc_dispatch_next_4(id*, int, void*, void*, void*, void*); int __kmpc_dispatch_next_8(id*, int, void*, void*, void*, void*); #ifdef __cplusplus } // extern "C" #endif // End of definitions copied from OpenMP RTL. // --------------------------------------------------------------------------- static id loc = {0, 2, 0, 0, ";file;func;0;0;;"}; // --------------------------------------------------------------------------- void run_loop( int loop_lb, // Loop lower bound. int loop_ub, // Loop upper bound. int loop_st, // Loop stride. int lchunk ) { static int volatile loop_sync = 0; int lb; // Chunk lower bound. int ub; // Chunk upper bound. int st; // Chunk stride. int rc; int nthreads = omp_get_num_threads(); int tid = omp_get_thread_num(); int gtid = __kmpc_global_thread_num(&loc); int last; int tc = (loop_ub - loop_lb) / loop_st + 1; int ch; int no_chunk = 0; if (lchunk == 0) { no_chunk = 1; lchunk = 1; } ch = lchunk * SIMD_LEN; #if _DEBUG > 1 printf("run_loop gtid %d tid %d (lb=%d, ub=%d, st=%d, ch=%d)\n", gtid, tid, (int)loop_lb, (int)loop_ub, (int)loop_st, lchunk); #endif // Don't test degenerate cases that should have been discovered by codegen. if (loop_st == 0) return; if (loop_st > 0 ? loop_lb > loop_ub : loop_lb < loop_ub) return; __kmpc_dispatch_init_4(&loc, gtid, kmp_sch_runtime_simd, loop_lb, loop_ub, loop_st, SIMD_LEN); { // Let the master thread handle the chunks alone. int chunk; // No of current chunk. int last_ub; // Upper bound of the last processed chunk. u64 cur; // Number of interations in current chunk. u64 max; // Max allowed iterations for current chunk. int undersized = 0; last_ub = loop_ub; chunk = 0; max = (loop_ub - loop_lb) / loop_st + 1; // The first chunk can consume all iterations. while (__kmpc_dispatch_next_4(&loc, gtid, &last, &lb, &ub, &st)) { ++ chunk; #if _DEBUG printf("th %d: chunk=%d, lb=%d, ub=%d ch %d\n", tid, chunk, (int)lb, (int)ub, (int)(ub-lb+1)); #endif // Check if previous chunk (it is not the final chunk) is undersized. if (undersized) printf("Error with chunk %d, th %d, err %d\n", chunk, tid, ++err); if (loop_st > 0) { if (!(ub <= loop_ub)) printf("Error with ub %d, %d, ch %d, err %d\n", (int)ub, (int)loop_ub, chunk, ++err); if (!(lb <= ub)) printf("Error with bounds %d, %d, %d, err %d\n", (int)lb, (int)ub, chunk, ++err); } else { if (!(ub >= loop_ub)) printf("Error with ub %d, %d, %d, err %d\n", (int)ub, (int)loop_ub, chunk, ++err); if (!(lb >= ub)) printf("Error with bounds %d, %d, %d, err %d\n", (int)lb, (int)ub, chunk, ++err); }; // if // Stride should not change. if (!(st == loop_st)) printf("Error with st %d, %d, ch %d, err %d\n", (int)st, (int)loop_st, chunk, ++err); cur = ( ub - lb ) / loop_st + 1; // Guided scheduling uses FP computations, so current chunk may // be a bit bigger (+1) than allowed maximum. if (!( cur <= max + 1)) printf("Error with iter %llu, %llu, err %d\n", cur, max, ++err); // Update maximum for the next chunk. if (!last && cur % ch) printf("Error with chunk %d, %d, ch %d, tid %d, err %d\n", chunk, (int)cur, ch, tid, ++err); if (last && !no_chunk && cur > ch && nthreads > 1) printf("Error: too big last chunk %d (%d), tid %d, err %d\n", (int)cur, ch, tid, ++err); if (cur < max) max = cur; last_ub = ub; undersized = (cur < ch); #if _DEBUG > 1 if (last) printf("under%d cur %d, ch %d, tid %d, ub %d, lb %d, st %d =======\n", undersized,cur,ch,tid,ub,lb,loop_st); #endif } // while // Must have the right last iteration index. if (loop_st > 0) { if (!(last_ub <= loop_ub)) printf("Error with last1 %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_ub, chunk, ++err); if (last && !(last_ub + loop_st > loop_ub)) printf("Error with last2 %d, %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk, ++err); } else { if (!(last_ub >= loop_ub)) printf("Error with last1 %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_ub, chunk, ++err); if (last && !(last_ub + loop_st < loop_ub)) printf("Error with last2 %d, %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk, ++err); } // if } __kmpc_barrier(&loc, gtid); } // run_loop int main(int argc, char *argv[]) { int chunk = 0; if (argc > 1) { // expect chunk size as a parameter chunk = atoi(argv[1]); } #pragma omp parallel //num_threads(num_th) run_loop(0, UBOUND, 1, chunk); if (err) { printf("failed, err = %d\n", err); return 1; } else { printf("passed\n"); return 0; } }
GB_unop__identity_fc32_fc64.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__identity_fc32_fc64) // op(A') function: GB (_unop_tran__identity_fc32_fc64) // C type: GxB_FC32_t // A type: GxB_FC64_t // cast: GxB_FC32_t cij = GxB_CMPLXF ((float) creal (aij), (float) cimag (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_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) \ GxB_FC32_t z = GxB_CMPLXF ((float) creal (aij), (float) cimag (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = GxB_CMPLXF ((float) creal (aij), (float) cimag (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FC32 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fc32_fc64) ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC64_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_FC64_t aij = Ax [p] ; GxB_FC32_t z = GxB_CMPLXF ((float) creal (aij), (float) cimag (aij)) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC32_t z = GxB_CMPLXF ((float) creal (aij), (float) cimag (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fc32_fc64) ( 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
convolution_2x2_pack8.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 conv2x2s1_pack8_avx(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; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); __m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + p * 8) : _mm256_set1_ps(0.f); out0.fill(_bias0); 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* kptr = (const float*)kernel.channel(p).row(q); // const float* kptr = (const float*)kernel + 4 * inch * p * 64; int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 1 < outw; j += 2) { __m256 _sum0 = _mm256_loadu_ps(outptr0); __m256 _sum1 = _mm256_loadu_ps(outptr0 + 8); __m256 _r00 = _mm256_broadcast_ss(r0); __m256 _r01 = _mm256_broadcast_ss(r0 + 1); __m256 _r02 = _mm256_broadcast_ss(r0 + 2); __m256 _r03 = _mm256_broadcast_ss(r0 + 3); __m256 _r04 = _mm256_broadcast_ss(r0 + 4); __m256 _r05 = _mm256_broadcast_ss(r0 + 5); __m256 _r06 = _mm256_broadcast_ss(r0 + 6); __m256 _r07 = _mm256_broadcast_ss(r0 + 7); r0 += 8; __m256 _k00 = _mm256_loadu_ps(kptr); __m256 _k01 = _mm256_loadu_ps(kptr + 8); __m256 _k02 = _mm256_loadu_ps(kptr + 16); __m256 _k03 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k03, _r03, _sum0); __m256 _k04 = _mm256_loadu_ps(kptr); __m256 _k05 = _mm256_loadu_ps(kptr + 8); __m256 _k06 = _mm256_loadu_ps(kptr + 16); __m256 _k07 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k04, _r04, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k05, _r05, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k06, _r06, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k07, _r07, _sum0); //======================================== _r00 = _mm256_broadcast_ss(r0); _r01 = _mm256_broadcast_ss(r0 + 1); _r02 = _mm256_broadcast_ss(r0 + 2); _r03 = _mm256_broadcast_ss(r0 + 3); _r04 = _mm256_broadcast_ss(r0 + 4); _r05 = _mm256_broadcast_ss(r0 + 5); _r06 = _mm256_broadcast_ss(r0 + 6); _r07 = _mm256_broadcast_ss(r0 + 7); r0 += 8; _sum1 = _mm256_comp_fmadd_ps(_k00, _r00, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k01, _r01, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k02, _r02, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k03, _r03, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k04, _r04, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k05, _r05, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k06, _r06, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k07, _r07, _sum1); _k00 = _mm256_loadu_ps(kptr); _k01 = _mm256_loadu_ps(kptr + 8); _k02 = _mm256_loadu_ps(kptr + 16); _k03 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k03, _r03, _sum0); _k04 = _mm256_loadu_ps(kptr); _k05 = _mm256_loadu_ps(kptr + 8); _k06 = _mm256_loadu_ps(kptr + 16); _k07 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k04, _r04, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k05, _r05, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k06, _r06, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k07, _r07, _sum0); _r00 = _mm256_broadcast_ss(r0); _r01 = _mm256_broadcast_ss(r0 + 1); _r02 = _mm256_broadcast_ss(r0 + 2); _r03 = _mm256_broadcast_ss(r0 + 3); _r04 = _mm256_broadcast_ss(r0 + 4); _r05 = _mm256_broadcast_ss(r0 + 5); _r06 = _mm256_broadcast_ss(r0 + 6); _r07 = _mm256_broadcast_ss(r0 + 7); _sum1 = _mm256_comp_fmadd_ps(_k00, _r00, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k01, _r01, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k02, _r02, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k03, _r03, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k04, _r04, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k05, _r05, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k06, _r06, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k07, _r07, _sum1); //=============== __m256 _r10 = _mm256_broadcast_ss(r1); __m256 _r11 = _mm256_broadcast_ss(r1 + 1); __m256 _r12 = _mm256_broadcast_ss(r1 + 2); __m256 _r13 = _mm256_broadcast_ss(r1 + 3); __m256 _r14 = _mm256_broadcast_ss(r1 + 4); __m256 _r15 = _mm256_broadcast_ss(r1 + 5); __m256 _r16 = _mm256_broadcast_ss(r1 + 6); __m256 _r17 = _mm256_broadcast_ss(r1 + 7); __m256 _k10 = _mm256_loadu_ps(kptr); __m256 _k11 = _mm256_loadu_ps(kptr + 8); __m256 _k12 = _mm256_loadu_ps(kptr + 16); __m256 _k13 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k13, _r13, _sum0); __m256 _k14 = _mm256_loadu_ps(kptr); __m256 _k15 = _mm256_loadu_ps(kptr + 8); __m256 _k16 = _mm256_loadu_ps(kptr + 16); __m256 _k17 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k14, _r14, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k15, _r15, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k16, _r16, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k17, _r17, _sum0); //======================================= r1 += 8; _r10 = _mm256_broadcast_ss(r1); _r11 = _mm256_broadcast_ss(r1 + 1); _r12 = _mm256_broadcast_ss(r1 + 2); _r13 = _mm256_broadcast_ss(r1 + 3); _r14 = _mm256_broadcast_ss(r1 + 4); _r15 = _mm256_broadcast_ss(r1 + 5); _r16 = _mm256_broadcast_ss(r1 + 6); _r17 = _mm256_broadcast_ss(r1 + 7); _sum1 = _mm256_comp_fmadd_ps(_k10, _r10, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k11, _r11, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k12, _r12, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k13, _r13, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k14, _r14, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k15, _r15, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k16, _r16, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k17, _r17, _sum1); _k10 = _mm256_loadu_ps(kptr); _k11 = _mm256_loadu_ps(kptr + 8); _k12 = _mm256_loadu_ps(kptr + 16); _k13 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k13, _r13, _sum0); _k14 = _mm256_loadu_ps(kptr); _k15 = _mm256_loadu_ps(kptr + 8); _k16 = _mm256_loadu_ps(kptr + 16); _k17 = _mm256_loadu_ps(kptr + 24); _sum0 = _mm256_comp_fmadd_ps(_k14, _r14, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k15, _r15, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k16, _r16, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k17, _r17, _sum0); r1 += 8; _r10 = _mm256_broadcast_ss(r1); _r11 = _mm256_broadcast_ss(r1 + 1); _r12 = _mm256_broadcast_ss(r1 + 2); _r13 = _mm256_broadcast_ss(r1 + 3); _r14 = _mm256_broadcast_ss(r1 + 4); _r15 = _mm256_broadcast_ss(r1 + 5); _r16 = _mm256_broadcast_ss(r1 + 6); _r17 = _mm256_broadcast_ss(r1 + 7); _sum1 = _mm256_comp_fmadd_ps(_k10, _r10, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k11, _r11, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k12, _r12, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k13, _r13, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k14, _r14, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k15, _r15, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k16, _r16, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k17, _r17, _sum1); kptr -= 224; _mm256_storeu_ps(outptr0, _sum0); _mm256_storeu_ps(outptr0 + 8, _sum1); outptr0 += 16; } for (; j < outw; j++) { __m256 _sum = _mm256_loadu_ps(outptr0); __m256 _r00 = _mm256_broadcast_ss(r0); __m256 _r01 = _mm256_broadcast_ss(r0 + 1); __m256 _r02 = _mm256_broadcast_ss(r0 + 2); __m256 _r03 = _mm256_broadcast_ss(r0 + 3); __m256 _r04 = _mm256_broadcast_ss(r0 + 4); __m256 _r05 = _mm256_broadcast_ss(r0 + 5); __m256 _r06 = _mm256_broadcast_ss(r0 + 6); __m256 _r07 = _mm256_broadcast_ss(r0 + 7); __m256 _k00 = _mm256_loadu_ps(kptr); __m256 _k01 = _mm256_loadu_ps(kptr + 8); __m256 _k02 = _mm256_loadu_ps(kptr + 16); __m256 _k03 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k00, _r00, _sum); _sum = _mm256_comp_fmadd_ps(_k01, _r01, _sum); _sum = _mm256_comp_fmadd_ps(_k02, _r02, _sum); _sum = _mm256_comp_fmadd_ps(_k03, _r03, _sum); __m256 _k04 = _mm256_loadu_ps(kptr); __m256 _k05 = _mm256_loadu_ps(kptr + 8); __m256 _k06 = _mm256_loadu_ps(kptr + 16); __m256 _k07 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k04, _r04, _sum); _sum = _mm256_comp_fmadd_ps(_k05, _r05, _sum); _sum = _mm256_comp_fmadd_ps(_k06, _r06, _sum); _sum = _mm256_comp_fmadd_ps(_k07, _r07, _sum); //======================================== r0 += 8; _r00 = _mm256_broadcast_ss(r0); _r01 = _mm256_broadcast_ss(r0 + 1); _r02 = _mm256_broadcast_ss(r0 + 2); _r03 = _mm256_broadcast_ss(r0 + 3); _r04 = _mm256_broadcast_ss(r0 + 4); _r05 = _mm256_broadcast_ss(r0 + 5); _r06 = _mm256_broadcast_ss(r0 + 6); _r07 = _mm256_broadcast_ss(r0 + 7); _k00 = _mm256_loadu_ps(kptr); _k01 = _mm256_loadu_ps(kptr + 8); _k02 = _mm256_loadu_ps(kptr + 16); _k03 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k00, _r00, _sum); _sum = _mm256_comp_fmadd_ps(_k01, _r01, _sum); _sum = _mm256_comp_fmadd_ps(_k02, _r02, _sum); _sum = _mm256_comp_fmadd_ps(_k03, _r03, _sum); _k04 = _mm256_loadu_ps(kptr); _k05 = _mm256_loadu_ps(kptr + 8); _k06 = _mm256_loadu_ps(kptr + 16); _k07 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k04, _r04, _sum); _sum = _mm256_comp_fmadd_ps(_k05, _r05, _sum); _sum = _mm256_comp_fmadd_ps(_k06, _r06, _sum); _sum = _mm256_comp_fmadd_ps(_k07, _r07, _sum); //=============== __m256 _r10 = _mm256_broadcast_ss(r1); __m256 _r11 = _mm256_broadcast_ss(r1 + 1); __m256 _r12 = _mm256_broadcast_ss(r1 + 2); __m256 _r13 = _mm256_broadcast_ss(r1 + 3); __m256 _r14 = _mm256_broadcast_ss(r1 + 4); __m256 _r15 = _mm256_broadcast_ss(r1 + 5); __m256 _r16 = _mm256_broadcast_ss(r1 + 6); __m256 _r17 = _mm256_broadcast_ss(r1 + 7); __m256 _k10 = _mm256_loadu_ps(kptr); __m256 _k11 = _mm256_loadu_ps(kptr + 8); __m256 _k12 = _mm256_loadu_ps(kptr + 16); __m256 _k13 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k10, _r10, _sum); _sum = _mm256_comp_fmadd_ps(_k11, _r11, _sum); _sum = _mm256_comp_fmadd_ps(_k12, _r12, _sum); _sum = _mm256_comp_fmadd_ps(_k13, _r13, _sum); __m256 _k14 = _mm256_loadu_ps(kptr); __m256 _k15 = _mm256_loadu_ps(kptr + 8); __m256 _k16 = _mm256_loadu_ps(kptr + 16); __m256 _k17 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k14, _r14, _sum); _sum = _mm256_comp_fmadd_ps(_k15, _r15, _sum); _sum = _mm256_comp_fmadd_ps(_k16, _r16, _sum); _sum = _mm256_comp_fmadd_ps(_k17, _r17, _sum); //======================================= r1 += 8; _r10 = _mm256_broadcast_ss(r1); _r11 = _mm256_broadcast_ss(r1 + 1); _r12 = _mm256_broadcast_ss(r1 + 2); _r13 = _mm256_broadcast_ss(r1 + 3); _r14 = _mm256_broadcast_ss(r1 + 4); _r15 = _mm256_broadcast_ss(r1 + 5); _r16 = _mm256_broadcast_ss(r1 + 6); _r17 = _mm256_broadcast_ss(r1 + 7); _k10 = _mm256_loadu_ps(kptr); _k11 = _mm256_loadu_ps(kptr + 8); _k12 = _mm256_loadu_ps(kptr + 16); _k13 = _mm256_loadu_ps(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k10, _r10, _sum); _sum = _mm256_comp_fmadd_ps(_k11, _r11, _sum); _sum = _mm256_comp_fmadd_ps(_k12, _r12, _sum); _sum = _mm256_comp_fmadd_ps(_k13, _r13, _sum); _k14 = _mm256_loadu_ps(kptr); _k15 = _mm256_loadu_ps(kptr + 8); _k16 = _mm256_loadu_ps(kptr + 16); _k17 = _mm256_loadu_ps(kptr + 24); _sum = _mm256_comp_fmadd_ps(_k14, _r14, _sum); _sum = _mm256_comp_fmadd_ps(_k15, _r15, _sum); _sum = _mm256_comp_fmadd_ps(_k16, _r16, _sum); _sum = _mm256_comp_fmadd_ps(_k17, _r17, _sum); kptr -= 224; _mm256_storeu_ps(outptr0, _sum); outptr0 += 8; } r0 += 8; r1 += 8; } } } }
sparselu.c
/**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /**********************************************************************************************/ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <libgen.h> #include "bots.h" #include "sparselu.h" #include "read_memory.h" /*********************************************************************** * checkmat: **********************************************************************/ //float tmp[bots_arg_size][bots_arg_size][bots_arg_size_1*bots_arg_size_1]; int checkmat (float *M, float *N) { //printf("11111\n"); int i, j; float r_err; for (i = 0; i < bots_arg_size_1; i++) { for (j = 0; j < bots_arg_size_1; j++) { r_err = M[i*bots_arg_size_1+j] - N[i*bots_arg_size_1+j]; if (r_err < 0.0 ) r_err = -r_err; r_err = r_err / M[i*bots_arg_size_1+j]; if(r_err > EPSILON) { printf("Checking failure: A[%d][%d]=%20.12E B[%d][%d]=%20.12E; Relative Error=%20.12E\n", i,j, M[i*bots_arg_size_1+j], i,j, N[i*bots_arg_size_1+j], r_err); bots_message("Checking failure: A[%d][%d]=%f B[%d][%d]=%f; Relative Error=%f\n", i,j, M[i*bots_arg_size_1+j], i,j, N[i*bots_arg_size_1+j], r_err); return FALSE; } } } return TRUE; } /*********************************************************************** * genmat: **********************************************************************/ void genmat (float *M[]) { int null_entry, init_val, i, j, ii, jj; float *p; float *prow; float rowsum; init_val = 1325; /* generating the structure */ for (ii=0; ii < bots_arg_size; ii++) { for (jj=0; jj < bots_arg_size; jj++) { /* computing null entries */ null_entry=FALSE; if ((ii<jj) && (ii%3 !=0)) null_entry = TRUE; if ((ii>jj) && (jj%3 !=0)) null_entry = TRUE; if (ii%2==1) null_entry = TRUE; if (jj%2==1) null_entry = TRUE; if (ii==jj) null_entry = FALSE; if (ii==jj-1) null_entry = FALSE; if (ii-1 == jj) null_entry = FALSE; /* allocating matrix */ if (null_entry == FALSE){ // M[ii*bots_arg_size+jj] = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); M[ii*bots_arg_size+jj] = (float*)((void*)tmp + tmp_pos); tmp_pos += bots_arg_size_1*bots_arg_size_1*sizeof(float); if ((M[ii*bots_arg_size+jj] == NULL)) { bots_message("Error: Out of memory\n"); exit(101); } /* initializing matrix */ /* Modify diagonal element of each row in order */ /* to ensure matrix is diagonally dominant and */ /* well conditioned. */ prow = p = M[ii*bots_arg_size+jj]; for (i = 0; i < bots_arg_size_1; i++) { rowsum = 0.0; for (j = 0; j < bots_arg_size_1; j++) { init_val = (3125 * init_val) % 65536; (*p) = (float)((init_val - 32768.0) / 16384.0); rowsum += abs(*p); p++; } if (ii == jj) *(prow+i) = rowsum * (float) bots_arg_size + abs(*(prow+i)); prow += bots_arg_size_1; } } else { M[ii*bots_arg_size+jj] = NULL; } } } } /*********************************************************************** * print_structure: **********************************************************************/ void print_structure(char *name, float *M[]) { int ii, jj; bots_message("Structure for matrix %s @ 0x%p\n",name, M); for (ii = 0; ii < bots_arg_size; ii++) { for (jj = 0; jj < bots_arg_size; jj++) { if (M[ii*bots_arg_size+jj]!=NULL) {bots_message("x");} else bots_message(" "); } bots_message("\n"); } bots_message("\n"); } /*********************************************************************** * allocate_clean_block: **********************************************************************/ float * allocate_clean_block() { int i,j; float *p, *q; //printf("1\n"); // p = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); p = (float*)((void*)tmp + tmp_pos); tmp_pos += bots_arg_size_1*bots_arg_size_1*sizeof(float); q=p; if (p!=NULL){ for (i = 0; i < bots_arg_size_1; i++) for (j = 0; j < bots_arg_size_1; j++){(*p)=0.0; p++;} } else { bots_message("Error: Out of memory\n"); exit (101); } return (q); } /*********************************************************************** * lu0: **********************************************************************/ void lu0(float *diag) { int i, j, k; //if(recompute == 0) flag1 = -1;//if(recompute == 0) for (k=flag1+1; k<bots_arg_size_1; k++) { for (i=k+1; i<bots_arg_size_1; i++) { diag[i*bots_arg_size_1+k] = diag[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) diag[i*bots_arg_size_1+j] = diag[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k] * diag[k*bots_arg_size_1+j]; } //kai } } /*********************************************************************** * bdiv: **********************************************************************/ void bdiv(float *diag, float *row) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) { for (k=0; k<bots_arg_size_1; k++) { row[i*bots_arg_size_1+k] = row[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) row[i*bots_arg_size_1+j] = row[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*diag[k*bots_arg_size_1+j]; } } } /*********************************************************************** * bmod: **********************************************************************/ void bmod(float *row, float *col, float *inner) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) inner[i*bots_arg_size_1+j] = inner[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } /*********************************************************************** * bmod: **********************************************************************/ void vbmod(float *row, float *col, float *inner) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) inner[i*bots_arg_size_1+j] = inner[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } /*********************************************************************** * fwd: **********************************************************************/ void fwd(float *diag, float *col) { int i, j, k; for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) for (i=k+1; i<bots_arg_size_1; i++) col[i*bots_arg_size_1+j] = col[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } void sparselu_init (float ***pBENCH, char *pass) { tmp_pos = 0; *pBENCH = (float **) malloc(bots_arg_size*bots_arg_size*sizeof(float *)); // printf("%s\n", pass): tmp = malloc((bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); //*pBENCH = (float **)tmp + tmp_pos; //tmp_pos += bots_arg_size*bots_arg_size*sizeof(float *); genmat(*pBENCH); //crucial_data(tmp, "float", (bots_arg_size*bots_arg_size*bots_arg_size_1*bots_arg_size_1)); //kai /*consistent_data(&flag1, "int", 1); consistent_data(&flag2, "int", 1); consistent_data(&flag3, "int", 1); consistent_data(&flag4, "int", 1); consistent_data(&flag5, "int", 1);*/ /* spec print_structure(pass, *pBENCH); */ } void sparselu_par_call(float **BENCH) { //printf("1111\n"); int ii, jj, kk; bots_message("Computing SparseLU Factorization (%dx%d matrix with %dx%d blocks) ", bots_arg_size,bots_arg_size,bots_arg_size_1,bots_arg_size_1); //kai //flush_whole_cache(); //start_crash(); float *tmpt; tmpt = malloc((bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); int t_flag1,t_flag2,t_flag3,t_flag4,t_flag5,t_flag6,t_flag7,t_flag8,t_flag9; ppid = pid; addr[count_addr++] = tmpt; addr[count_addr++] = &t_flag1; addr[count_addr++] = &t_flag2; addr[count_addr++] = &t_flag3; addr[count_addr++] = &t_flag4; addr[count_addr++] = &t_flag5; addr[count_addr++] = &t_flag6; addr[count_addr++] = &t_flag7; addr[count_addr++] = &t_flag8; addr[count_addr++] = &t_flag9; ReadVarriable(addr,count_addr); printf("flag1 = %d\n",t_flag1); printf("flag2 = %d\n",t_flag2); printf("flag3 = %d\n",t_flag3); printf("flag4 = %d\n",t_flag4); printf("flag5 = %d\n",t_flag5); printf("flag6 = %d\n",t_flag6); printf("flag7 = %d\n",t_flag7); printf("flag8 = %d\n",t_flag8); printf("flag9 = %d\n",t_flag9); //kk=0;flag1 = -1;flag2=kk; flag3 = kk; flag4 = kk; //memcpy(tmp,tmpt,(bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); #pragma omp parallel #pragma omp single nowait //flag5=-1; for (kk=0; kk<bots_arg_size; kk++) { /* */ lu0(BENCH[kk*bots_arg_size+kk]); //if(recompute == 0) flag2=kk; flag2=kk; for (jj=flag2+1; jj<bots_arg_size; jj++) { if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj) shared(BENCH) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } //kai //flag2 = kk+1; } //if(recompute == 0) flag3=kk; flag3=kk; for (ii=flag3+1; ii<bots_arg_size; ii++) { if (BENCH[ii*bots_arg_size+kk] != NULL) #pragma omp task untied firstprivate(kk, ii) shared(BENCH) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } //kai //flag3 = kk+1; } /* if(kk == flag5) { recompute = 1; float *ttmp = (float*) tmp; memcpy(tmp,tmpt,(bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); flag1 = t_flag1;flag2=t_flag2; flag3 =t_flag3; flag4 = t_flag4; } else{ recompute = 0; }*/ if(recompute == 0) flag4=kk; #pragma omp taskwait for (ii=flag4+1; ii<bots_arg_size; ii++) { if(kk == flag5) printf("ii = %d\n",ii); if (BENCH[ii*bots_arg_size+kk] != NULL){ for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj, ii) shared(BENCH) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); bmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } //kai //flag4 = kk+1; if(kk == flag5 && ii ==flag4 &&jj==flag6) { //memcpy(tmpt,tmp,(bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); memcpy(tmp,tmpt,(bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); if (strcmp(tmp,tmpt) == 0) { printf("Equal\n"); } else{ printf("Error!\n"); } } } } #pragma omp taskwait //flag5 = kk; recompute = 0; } //kai // end_crash(); bots_message(" completed!\n"); } void sparselu_seq_call(float **BENCH) { int ii, jj, kk; for (kk=0; kk<bots_arg_size; kk++) { lu0(BENCH[kk*bots_arg_size+kk]); for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); bmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } } void sparselu_fini (float **BENCH, char *pass) { /* spec print_structure(pass, BENCH); */ return; } /* * changes for SPEC, original source * int sparselu_check(float **SEQ, float **BENCH) { int ii,jj,ok=1; for (ii=0; ((ii<bots_arg_size) && ok); ii++) { for (jj=0; ((jj<bots_arg_size) && ok); jj++) { if ((SEQ[ii*bots_arg_size+jj] == NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] == NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = checkmat(SEQ[ii*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } if (ok) return BOTS_RESULT_SUCCESSFUL; else return BOTS_RESULT_UNSUCCESSFUL; } */ /* * SPEC modified check, print out values * */ void vgenmat (float *M[]) { int null_entry, init_val, i, j, ii, jj; float *p; float *prow; float rowsum; init_val = 1325; /* generating the structure */ for (ii=0; ii < bots_arg_size; ii++) { for (jj=0; jj < bots_arg_size; jj++) { /* computing null entries */ null_entry=FALSE; if ((ii<jj) && (ii%3 !=0)) null_entry = TRUE; if ((ii>jj) && (jj%3 !=0)) null_entry = TRUE; if (ii%2==1) null_entry = TRUE; if (jj%2==1) null_entry = TRUE; if (ii==jj) null_entry = FALSE; if (ii==jj-1) null_entry = FALSE; if (ii-1 == jj) null_entry = FALSE; /* allocating matrix */ if (null_entry == FALSE){ M[ii*bots_arg_size+jj] = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); // M[ii*bots_arg_size+jj] = (float*)((void*)tmp + tmp_pos); // tmp_pos += bots_arg_size_1*bots_arg_size_1*sizeof(float); if ((M[ii*bots_arg_size+jj] == NULL)) { bots_message("Error: Out of memory\n"); exit(101); } /* initializing matrix */ /* Modify diagonal element of each row in order */ /* to ensure matrix is diagonally dominant and */ /* well conditioned. */ prow = p = M[ii*bots_arg_size+jj]; for (i = 0; i < bots_arg_size_1; i++) { rowsum = 0.0; for (j = 0; j < bots_arg_size_1; j++) { init_val = (3125 * init_val) % 65536; (*p) = (float)((init_val - 32768.0) / 16384.0); rowsum += abs(*p); p++; } if (ii == jj) *(prow+i) = rowsum * (float) bots_arg_size + abs(*(prow+i)); prow += bots_arg_size_1; } } else { M[ii*bots_arg_size+jj] = NULL; } } } } void vlu0(float *diag) { int i, j, k; for (k=0; k<bots_arg_size_1; k++) for (i=k+1; i<bots_arg_size_1; i++) { diag[i*bots_arg_size_1+k] = diag[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) diag[i*bots_arg_size_1+j] = diag[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k] * diag[k*bots_arg_size_1+j]; } } void vsparselu_init (float ***pBENCH, char *pass) { *pBENCH = (float **) malloc(bots_arg_size*bots_arg_size*sizeof(float *)); vgenmat(*pBENCH); /* spec print_structure(pass, *pBENCH); */ } void vsparselu_par_call(float **BENCH) { int ii, jj, kk; bots_message("Computing SparseLU Factorization (%dx%d matrix with %dx%d blocks) ", bots_arg_size,bots_arg_size,bots_arg_size_1,bots_arg_size_1); #pragma omp parallel #pragma omp single nowait for (kk=0; kk<bots_arg_size; kk++) { vlu0(BENCH[kk*bots_arg_size+kk]); for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj) shared(BENCH) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) #pragma omp task untied firstprivate(kk, ii) shared(BENCH) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } #pragma omp taskwait for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj, ii) shared(BENCH) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); vbmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } #pragma omp taskwait } bots_message("pre verify completed!\n"); } int sparselu_check(float **SEQ, float **BENCH) { vsparselu_init(&SEQ, NULL); vsparselu_par_call(SEQ); int ii,jj,ok=1; for (ii=0; ((ii<bots_arg_size) && ok); ii++) { for (jj=0; ((jj<bots_arg_size) && ok); jj++) { if ((SEQ[ii*bots_arg_size+jj] == NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] == NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = checkmat(SEQ[ii*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } FILE *file; char result_file[128] = "/home/cc/nvc/tests/recompute_result.out.jie"; sprintf(result_file + strlen(result_file), "%d", pid); file = fopen(result_file,"w"); if(ok) { fprintf(file,"SUCCESS\n"); } else{ fprintf(file,"UNSUCCESS\n"); } fclose(file); if (ok) return BOTS_RESULT_SUCCESSFUL; else return BOTS_RESULT_UNSUCCESSFUL; /* int i, j, ok; bots_message("Output size: %d\n",bots_arg_size); for (i = 0; i < bots_arg_size; i+=50) { for (j = 0; j < bots_arg_size; j+=40) { ok = checkmat1(BENCH[i*bots_arg_size+j]); } } return BOTS_RESULT_SUCCESSFUL; */ } int checkmat1 (float *N) { int i, j; for (i = 0; i < bots_arg_size_1; i+=20) { for (j = 0; j < bots_arg_size_1; j+=20) { bots_message("Output Matrix: A[%d][%d]=%8.12f \n", i,j, N[i*bots_arg_size_1+j]); } } //printf("111111111\n"); return TRUE; }
libtorch_utils.h
#ifndef libtorch_UTILS #define libtorch_UTILS /* Copyright (c) 2019, Sanaxen All rights reserved. Use of this source code is governed by a MIT license that can be found in the LICENSE file. */ #include <random> #include "util/utils.h" #ifdef USE_IMAGE_UTIL #include "util/Image.hpp" #endif namespace cpp_torch { inline void nop() { // do nothing } /** * error exception class **/ class error_exception : public std::exception { public: explicit error_exception(const std::string &msg) : msg_(msg) { fprintf(stderr, "ERROR:%s\n", msg.c_str()); fflush(stderr); } const char *what() const throw() override { return msg_.c_str(); } private: std::string msg_; }; inline size_t tensor_flatten_size(torch::Tensor& t) { size_t s = 1; if (t.dim()) { for (int i = 0; i < t.sizes().size(); i++) { s *= t.sizes()[i]; } return s; } return 0; } inline void dump_dim(const std::string & s, torch::Tensor& t) { printf("%s dim:%d ", s.c_str(), t.dim()); if (t.dim()) { for (int i = 0; i < t.sizes().size() - 1; i++) { printf("%d x", t.sizes()[i]); } printf("%d\n", t.sizes()[t.sizes().size() - 1]); } fflush(stdout); } inline void dump_dim(char* s, torch::Tensor& t) { dump_dim(std::string(s), t); } void label2vec(const std::vector<tiny_dnn::label_t>& labels, std::vector<tiny_dnn::vec_t>& vec, int max_label) { vec.clear(); vec.resize(labels.size()); #pragma omp parallel for for (int i = 0; i < labels.size(); i++) { tiny_dnn::vec_t t(max_label, 0); t[labels[i]] = 1.0; vec[i] = t; } } template < typename initial_vector> inline void toTorchTensors(initial_vector& vec, std::vector<torch::Tensor>& tensor_vect) { tensor_vect.resize(vec.size()); #pragma omp parallel for for (int i = 0; i < vec.size(); i++) { torch::Tensor& tensor = torch::tensor({ vec[i] }); tensor_vect[i] = tensor; } } template < typename initial_vector> inline torch::Tensor toTorchTensors(initial_vector& vec) { return torch::tensor({ vec }); } inline std::vector<tiny_dnn::tensor_t> toTensor_t(torch::Tensor& x, int batch, int channel, int h, int w) { std::vector<tiny_dnn::tensor_t> y; const int size = channel * h*w; torch::Tensor& xx = x.view({ batch, 1,1, size }); y.resize(batch); #pragma omp parallel for for (int i = 0; i < batch; i++) { tiny_dnn::tensor_t t; tiny_dnn::vec_t v(size); for (int j = 0; j < size; j++) { v[j] = xx[i][0][0][j].template item<float_t>(); } t.push_back(v); y[i] = t; } return y; } inline tiny_dnn::tensor_t toTensor_t(torch::Tensor& x, int channel, int h, int w) { const int size = channel * h*w; torch::Tensor& xx = x.view({ 1, 1,1, size }); tiny_dnn::tensor_t t; tiny_dnn::vec_t v(size); #pragma omp parallel for for (int j = 0; j < size; j++) { v[j] = xx[0][0][0][j].template item<float_t>(); } t.push_back(v); return t; } inline tiny_dnn::vec_t toTensor_t(torch::Tensor& x, int size) { torch::Tensor& xx = x.view({ 1, 1,1, size }); tiny_dnn::vec_t v(size); #pragma omp parallel for for (int j = 0; j < size; j++) { v[j] = xx[0][0][0][j].template item<float_t>(); } return v; } inline int get_BATCH(const std::vector<torch::Tensor>& images, torch::Tensor& batch_images, const int batchSize, std::vector<int>& index) { int batchNum = images.size() / batchSize; if (batchNum == 0) { throw error_exception("input size < batch size"); } batch_images = images[index[0]]; for (int i = 1; i < index.size(); i++) { batch_images = torch::cat({ batch_images, images[index[i]] }, 0); } return batchNum; } void TensorToImageFile(torch::Tensor image_tensor, const std::string& filename, const int scale = 1.0) { #ifdef USE_IMAGE_UTIL const int channels = image_tensor.sizes()[0]; const int h = image_tensor.sizes()[1]; const int w = image_tensor.sizes()[2]; if (channels == 0 || channels > 3) { dump_dim("image_tensor", image_tensor); throw error_exception("tensor dimension != CxHxW"); } tiny_dnn::tensor_t& img = toTensor_t(image_tensor.view({ channels, h,w }), channels, h, w); const int sz = img[0].size(); #pragma omp parallel for for (int i = 0; i < sz; i++) { img[0][i] *= scale; } Image rgb_img = vec_t2image(img[0], channels, h, w); ImageWrite(filename.c_str(), &rgb_img); #else throw error_exception("undefined USE_IMAGE_UTIL"); #endif } inline int get_BATCH(const std::vector<torch::Tensor>& images, const std::vector<torch::Tensor>& labels, torch::Tensor& batch_images, torch::Tensor& batch_labels, const int batchSize, std::vector<int>& index) { int batchNum = images.size() / batchSize; if (batchNum == 0) { throw error_exception("input size < batch size"); } batch_images = images[index[0]]; batch_labels = labels[index[0]]; for (int i = 1; i < index.size(); i++) { batch_images = torch::cat({ batch_images, images[index[i]] }, 0); batch_labels = torch::cat({ batch_labels, labels[index[i]] }, 0); } return batchNum; } template < typename Model> class network_torch { std::vector<float_t> Tolerance_Set; float loss_value = 0.0; public: int in_channels = 1; int in_H = 1; int in_W = 1; int out_channels = 1; int out_H = 1; int out_W = 1; tiny_dnn::timer time_measurement; torch::Device device; Model model; /** * @param model_ model of neural networks * @param optimizer_ optimizing algorithm for training * @param device_ Device Type(kCPU, kCUDA) * assume */ network_torch(Model& model_, torch::Device device_) :model(model_), device(device_) { try { model.get()->to(device); } catch (std::exception& e) { printf("%s\n", e.what()); exit(0); } } inline void input_dim(int c, int w, int h) { in_channels = c; in_H = h; in_W = w; } inline void output_dim(int c, int w, int h) { out_channels = c; out_H = h; out_W = w; } bool classification = false; bool batch_shuffle = true; bool pre_make_batch = true; bool stop_training_ = false; /** * request to finish an ongoing training * * It is safe to test the current network performance in @a * on_batch_enumerate * and * @a on_epoch_enumerate callbacks during training. */ inline void stop_ongoing_training() { stop_training_ = true; } /** * @param images array of input data * @param batch_x input data batch * assume */ inline void generate_BATCH( std::vector<torch::Tensor> &images, std::vector< torch::Tensor>& batch_x ) { bool shuffle = batch_shuffle; const int batchNum = (int64_t)((float)images.size() / (float)kTrainBatchSize + 0.5); batch_x = std::vector< torch::Tensor>(batchNum); std::random_device rnd; std::mt19937 mt(rnd()); std::uniform_int_distribution<> rand_index(0, (int)images.size() - 1); #pragma omp parallel for for (int batch_idx = 0; batch_idx < batchNum; batch_idx++) { std::vector<int> index(kTrainBatchSize); if (shuffle) { for (int k = 0; k < kTrainBatchSize; k++) { index[k] = rand_index(mt); } } else { for (int k = 0; k < kTrainBatchSize; k++) { index[k] = (batch_idx*kTrainBatchSize + k) % images.size(); } } get_BATCH(images, batch_x[batch_idx], kTrainBatchSize, index); if (tensor_flatten_size(batch_x[batch_idx]) < kTrainBatchSize*in_channels*in_H*in_W) { dump_dim("batch_x", batch_x[batch_idx]); std::cout << tensor_flatten_size(batch_x[batch_idx]) << " < " << kTrainBatchSize << "*" << in_channels << "*" << in_H << "* " << in_W << "=" << kTrainBatchSize*in_channels*in_H*in_W << std::endl; throw error_exception("tensor size error."); } batch_x[batch_idx] = batch_x[batch_idx].view({ kTrainBatchSize, in_channels, in_H, in_W }); } } /** * @param images array of input data * @param labels array of labels output * @param batch_x input data batch * @param batch_y output data batch * assume */ inline void generate_BATCH( std::vector<torch::Tensor> &images, std::vector<torch::Tensor> &labels, std::vector< torch::Tensor>& batch_x, std::vector< torch::Tensor>& batch_y ) { bool shuffle = batch_shuffle; const int batchNum = (int64_t)((float)images.size() / (float)kTrainBatchSize + 0.5); batch_x = std::vector< torch::Tensor>(batchNum); batch_y = std::vector< torch::Tensor>(batchNum); std::random_device rnd; std::mt19937 mt(rnd()); std::uniform_int_distribution<> rand_index(0, (int)images.size() - 1); #pragma omp parallel for for (int batch_idx = 0; batch_idx < batchNum; batch_idx++) { std::vector<int> index(kTrainBatchSize); if (shuffle) { for (int k = 0; k < kTrainBatchSize; k++) { index[k] = rand_index(mt); } } else { for (int k = 0; k < kTrainBatchSize; k++) { index[k] = (batch_idx*kTrainBatchSize + k) % images.size(); } } get_BATCH(images, labels, batch_x[batch_idx], batch_y[batch_idx], kTrainBatchSize, index); if (tensor_flatten_size(batch_x[batch_idx]) < kTrainBatchSize*in_channels*in_H*in_W) { dump_dim("batch_x", batch_x[batch_idx]); std::cout << tensor_flatten_size(batch_x[batch_idx]) << " < " << kTrainBatchSize << "*" << in_channels << "*" << in_H << "* " << in_W << "=" <<kTrainBatchSize*in_channels*in_H*in_W << std::endl; throw error_exception("tensor size error."); } if (tensor_flatten_size(batch_y[batch_idx]) < kTrainBatchSize*out_channels*out_H*out_W) { dump_dim("batch_y", batch_y[batch_idx]); std::cout << tensor_flatten_size(batch_y[batch_idx]) << " < " << kTrainBatchSize << "*" << out_channels << "*" << out_H << "* " << out_W << "=" << kTrainBatchSize*out_channels*out_H*out_W << std::endl; throw error_exception("tensor size error."); } batch_x[batch_idx] = batch_x[batch_idx].view({ kTrainBatchSize, in_channels, in_H, in_W }); batch_y[batch_idx] = batch_y[batch_idx].view({ kTrainBatchSize, out_channels, out_H, out_W }); } } /** * @param optimizer optimizing algorithm for training * @param images array of input data * @param labels array of labels output * @param kTrainBatchSize number of mini-batch * @param kNumberOfEpochs number of training epochs * @param on_batch_enumerate callback for each mini-batch enumerate * @param on_epoch_enumerate callback for each epoch * assume */ bool fit( torch::optim::Optimizer* optimizer, std::vector<torch::Tensor> &images, std::vector<torch::Tensor> &labels, int kTrainBatchSize, int kNumberOfEpochs, std::function <void(void)> on_batch_enumerate = {}, std::function <void(void)> on_epoch_enumerate = {} ) { if (images.size() != labels.size()) { return false; } if (images.size() < kTrainBatchSize || labels.size() < kTrainBatchSize) { return false; } time_measurement.start(); int batchNum; std::vector< torch::Tensor> batch_x; std::vector< torch::Tensor> batch_y; if (pre_make_batch) { generate_BATCH(images, labels, batch_x, batch_y); batchNum = batch_x.size(); for (int i = 0; i < batchNum; i++) { batch_x[i] = batch_x[i].to(device); batch_y[i] = batch_y[i].to(device); } } optimizer->zero_grad(); stop_training_ = false; model.get()->train(true); for (size_t epoch = 0; epoch < kNumberOfEpochs && !stop_training_; ++epoch) { if (!pre_make_batch) { generate_BATCH(images, labels, batch_x, batch_y); batchNum = batch_x.size(); for (int i = 0; i < batchNum; i++) { batch_x[i] = batch_x[i].to(device); batch_y[i] = batch_y[i].to(device); } } loss_value = 0.0; float loss_ave = 0.0; for (int batch_idx = 0; batch_idx < batchNum && !stop_training_; batch_idx++) { torch::Tensor& data = batch_x[batch_idx]; torch::Tensor& targets = batch_y[batch_idx]; //data = data.to(device); //targets = targets.to(device); optimizer->zero_grad(); auto output = model.get()->forward(data); //dump_dim(output); //dump_dim(targets); targets = targets.reshape_as(output); torch::Tensor loss; if (classification) { loss = torch::nll_loss(output, targets.argmax(1)); } else { loss = torch::mse_loss(output, targets); } AT_ASSERT(!std::isnan(loss.template item<float_t>())); loss.backward(); optimizer->step(); loss_value = loss.template item<float_t>(); loss_ave += loss_value; on_batch_enumerate(); model.get()->train(true); } if (stop_training_) break; loss_value = loss_ave / batchNum; on_epoch_enumerate(); model.get()->train(true); } time_measurement.stop(); return true; } /** * @param optimizer optimizing algorithm for training * @param images array of input data * @param labels array of labels output * @param kTrainBatchSize number of mini-batch * @param kNumberOfEpochs number of training epochs * @param on_batch_enumerate callback for each mini-batch enumerate * @param on_epoch_enumerate callback for each epoch * assume */ bool fit( torch::optim::Optimizer* optimizer, tiny_dnn::tensor_t &images, tiny_dnn::tensor_t &labels, int kTrainBatchSize, int kNumberOfEpochs, std::function <void(void)> on_batch_enumerate = {}, std::function <void(void)> on_epoch_enumerate = {} ) { std::vector<torch::Tensor> images_torch; std::vector<torch::Tensor> labels_torch; toTorchTensors(images, images_torch); toTorchTensors(labels, labels_torch); return fit(optimizer, images_torch, labels_torch, kTrainBatchSize, kNumberOfEpochs, on_batch_enumerate, on_epoch_enumerate); } /** * @param optimizer optimizing algorithm for training * @param images array of input data * @param class_labels array of label-id for each input data(0-origin) label-id=on-hot-vector * @param kTrainBatchSize number of mini batch * @param kNumberOfEpochs number of training epochs * @param on_batch_enumerate callback for each mini-batch enumerate * @param on_epoch_enumerate callback for each epoch * assume */ bool train( torch::optim::Optimizer* optimizer, tiny_dnn::tensor_t &images, std::vector<tiny_dnn::label_t> &class_labels, int kTrainBatchSize, int kNumberOfEpochs, std::function <void(void)> on_batch_enumerate = {}, std::function <void(void)> on_epoch_enumerate = {} ) { std::vector<tiny_dnn::vec_t> one_hot_vec; label2vec(class_labels, one_hot_vec); std::vector<torch::Tensor> images_torch; std::vector<torch::Tensor> labels_torch; toTorchTensors(images, images_torch); toTorchTensors(one_hot_vec, labels_torch); return fit(optimizer, images_torch, labels_torch, kTrainBatchSize, kNumberOfEpochs, on_batch_enumerate, on_epoch_enumerate); } bool test( std::vector<torch::Tensor> &images, std::vector<torch::Tensor> &labels, int kTestBatchSize ) { if (images.size() != labels.size()) { return false; } if (images.size() < kTestBatchSize || labels.size() < kTestBatchSize) { return false; } model.get()->train(false); float loss_ave = 0.0; int correct = 0; int testNum = images.size() / kTestBatchSize; if (testNum == 0) { throw error_exception("input size < test batch size"); } for (size_t test = 0; test < testNum; ++test) { torch::Tensor batch_x; torch::Tensor batch_y; std::vector<int> index(kTestBatchSize); for (int k = 0; k < kTestBatchSize; k++) { index[k] = (kTestBatchSize * test + k) % images.size(); } get_BATCH(images, labels, batch_x, batch_y, kTestBatchSize, index); torch::Tensor& data = batch_x.view({ kTestBatchSize,in_channels, in_H, in_W }); torch::Tensor& targets = batch_y.view({ kTestBatchSize, out_channels, out_H, out_W }); data = data.to(device); targets = targets.to(device); torch::Tensor output = model.get()->forward(data); targets = targets.reshape_as(output); torch::Tensor loss; if (classification) { loss = torch::nll_loss(output, targets.argmax(1)); } else { loss = torch::mse_loss(output, targets); } AT_ASSERT(!std::isnan(loss.template item<float_t>())); loss_value = loss.template item<float_t>(); loss_ave += loss_value; if (classification) { auto pred = output.argmax(1); correct += pred.eq(targets.argmax(1)).sum().template item<int64_t>(); } // if (classification_one_hot_vector) // { //#if 1 // auto pred = output.argmax(1); // correct += pred.eq(targets.argmax(1)).sum().template item<int64_t>(); //#else //#pragma omp parallel for // for (int k = 0; k < kTestBatchSize; k++) // { // correct += (vec_max_index(output[k]) == vec_max_index(targets[k])) ? 1 : 0; // // { // //std::vector<tiny_dnn::tensor_t>& x = toTensor_t(output[k], 1, 1, 1, out_data_size()); // //std::vector<tiny_dnn::tensor_t>& y = toTensor_t(targets[k], 1, 1, 1, out_data_size()); // //AT_ASSERT(vec_max_index(x[0][0])== vec_max_index(output[k])); // //AT_ASSERT(vec_max_index(y[0][0]) == vec_max_index(targets[k])); // // //tiny_dnn::tensor_t& x = toTensor_t(output[k], 1, 1, out_data_size()); // //tiny_dnn::tensor_t& y = toTensor_t(targets[k], 1, 1, out_data_size()); // //AT_ASSERT(vec_max_index(x[0]) == vec_max_index(output[k])); // //AT_ASSERT(vec_max_index(y[0]) == vec_max_index(targets[k])); // // //tiny_dnn::vec_t& x = toTensor_t(output[k], out_data_size()); // //tiny_dnn::vec_t& y = toTensor_t(targets[k], out_data_size()); // //AT_ASSERT(vec_max_index(x) == vec_max_index(output[k])); // //AT_ASSERT(vec_max_index(y) == vec_max_index(targets[k])); // } // } //#endif // } } if (classification) { std::printf(" Accuracy: %.3f%% Loss: %.3f\n", 100.0*static_cast<float_t>(correct) / images.size(), loss_ave / testNum); } else { std::printf("Loss: %.3f\n", loss_ave / testNum); } return true; } /** * @param images array of input data * @param labels array of output data * @param kTestBatchSize number of mini batch * assume */ bool test( tiny_dnn::tensor_t &images, tiny_dnn::tensor_t &labels, int kTestBatchSize ) { std::vector<torch::Tensor> images_torch; std::vector<torch::Tensor> labels_torch; toTorchTensors(images, images_torch); toTorchTensors(labels, labels_torch); return test(images_torch, labels_torch, kTestBatchSize); } /** * @param images array of input data * @param labels array of lable(on-hot-vector) data * @param kTestBatchSize number of mini batch * assume */ bool test( tiny_dnn::tensor_t &images, std::vector<tiny_dnn::label_t> &class_labels, int kTestBatchSize ) { std::vector<tiny_dnn::vec_t> one_hot_vec; label2vec(class_labels, one_hot_vec); std::vector<torch::Tensor> images_torch; std::vector<torch::Tensor> labels_torch; toTorchTensors(images, images_torch); toTorchTensors(one_hot_vec, labels_torch); return test(images_torch, labels_torch, kTestBatchSize); } torch::Tensor fprop(torch::Tensor &in) { model.get()->train(false); return model.get()->forward(in); } /** * executes forward-propagation and returns output **/ inline torch::Tensor predict(torch::Tensor& X) { model.get()->train(false); torch::Tensor y = model.get()->forward(X.to(device)); return y; } /** * executes forward-propagation and returns output **/ inline std::vector<tiny_dnn::tensor_t> predict(torch::Tensor& X, const int batch) { model.get()->train(false); torch::Tensor y = model.get()->forward(X.to(device)); std::vector<tiny_dnn::tensor_t> t; toTensor_t(y, t, batch, out_channels, out_H, out_W); return t; } /** * executes forward-propagation and returns output **/ inline tiny_dnn::vec_t predict(tiny_dnn::vec_t& X) { model.get()->train(false); torch::Tensor images_torch = toTorchTensors(X).view({ 1, in_channels, in_H, in_W }).to(device); torch::Tensor y = model.get()->forward(images_torch); tiny_dnn::vec_t t = toTensor_t(y, out_data_size()); return t; } /** * executes forward-propagation and returns output **/ inline tiny_dnn::label_t predict_label(tiny_dnn::vec_t& X) { model.get()->train(false); torch::Tensor images_torch = toTorchTensors(X).view({ 1, in_channels, in_H, in_W }).to(device); torch::Tensor y = model.get()->forward(images_torch); tiny_dnn::vec_t t = toTensor_t(y, out_data_size()); return vec_max_index(t); } inline void label2vec(const std::vector<tiny_dnn::label_t>& labels, std::vector<tiny_dnn::vec_t>& vec) { const size_t outdim = out_data_size(); vec.clear(); vec.resize(labels.size()); const size_t sz = labels.size(); #pragma omp parallel for for (int i = 0; i < sz; i++) { tiny_dnn::vec_t t(outdim, 0); t[labels[i]] = 1.0; vec[i] = t; } } inline void label2vec(const tiny_dnn::label_t& labels, tiny_dnn::vec_t& vec) { const size_t outdim = out_data_size(); tiny_dnn::vec_t t(outdim, 0); t[labels] = 1.0; vec = t; } inline tiny_dnn::label_t vec_max_index(torch::Tensor &out) { return tiny_dnn::label_t(out.view({ out_data_size() }).argmax(0).template item<float_t>()); } inline tiny_dnn::label_t vec_max_index(tiny_dnn::vec_t &out) { return tiny_dnn::label_t(max_index(out)); } inline tiny_dnn::label_t vec_max_index(tiny_dnn::tensor_t &out) { return tiny_dnn::label_t(max_index(out[0])); } float_t get_loss(std::vector<tiny_dnn::vec_t> &in, std::vector<tiny_dnn::label_t> &t, int batchSize) { std::vector<tiny_dnn::vec_t> vec; label2vec(t, vec); return get_loss(in, vec, batchSize); } float_t get_loss( std::vector<tiny_dnn::vec_t> &in, std::vector<tiny_dnn::vec_t> &t, int BatchSize) { float_t sum_loss = float_t(0); std::vector<torch::Tensor> images; std::vector<torch::Tensor> labels; toTorchTensors(in, images); toTorchTensors(t, labels); const int batchNum = in.size() / BatchSize; if (batchNum == 0) { throw error_exception("input size < Batch Size"); } std::vector< torch::Tensor> batch_x(batchNum); std::vector< torch::Tensor> batch_y(batchNum); std::vector<float_t> loss_list(in.size(), 0.0); #pragma omp parallel for for (int i = 0; i < batchNum; i++) { //if (!pre_make_batch) { std::vector<int> index(BatchSize); for (int k = 0; k < BatchSize; k++) { index[k] = (i* BatchSize + k) % images.size(); } get_BATCH(images, labels, batch_x[i], batch_y[i], BatchSize, index); batch_x[i] = batch_x[i].view({ BatchSize, in_channels, in_H, in_W }); batch_y[i] = batch_y[i].view({ BatchSize, out_channels, out_H, out_W }); } torch::Tensor& input = batch_x[i].to(device); torch::Tensor& targets = batch_y[i].to(device); torch::Tensor predicted = predict(input).to(device); //dump_dim(std::string("predicted"), predicted); //dump_dim(std::string("targets"), targets); torch::Tensor loss; if (classification) { loss = torch::nll_loss(predicted, targets.view_as(predicted).argmax(1)); } else { loss = torch::mse_loss(predicted.view_as(targets), targets); } AT_ASSERT(!std::isnan(loss.template item<float_t>())); //dump_dim(std::string("loss"), loss); //std::cout << loss << std::endl; loss_list[i] = loss.template item<float_t>(); } for (size_t i = 0; i < in.size(); i++) { sum_loss += loss_list[i]; } return sum_loss; } void set_tolerance(const float max_tol, const float min_tol, int div = 5) { if (div < 3) div = 3; Tolerance_Set.resize(div); for (int i = 0; i < div; i++) { Tolerance_Set[i] = (max_tol + i*(min_tol - max_tol) / (div - 1.0)); } } std::vector<float_t>& get_tolerance() { return Tolerance_Set; } /* * output vector output[0..tolerance_set.size()-1]=num_success, output[tolerance_set.size()]=image of size, */ std::vector<int> get_accuracy(tiny_dnn::tensor_t& images, tiny_dnn::tensor_t& labels, std::vector<float_t>& tolerance_set) { std::vector<int> result(tolerance_set.size()+1); if (images.size() == 0) { return result; } result[tolerance_set.size()] = images.size(); for (int i = 0; i < images.size(); i++) { tiny_dnn::vec_t& predict_y = predict(images[i]); const tiny_dnn::vec_t& actual = labels[i]; AT_ASSERT(predict_y.size() == actual.size()); float sum = 0.0; for (int k = 0; k < predict_y.size(); k++) { sum += (predict_y[k] - actual[k])*(predict_y[k] - actual[k]); } sum /= predict_y.size(); for (int j = 0; j < tolerance_set.size(); j++) { if (sum < tolerance_set[j]) { result[j]++; } } } return result; } tiny_dnn::result get_accuracy( tiny_dnn::tensor_t& images, tiny_dnn::tensor_t& labels) { tiny_dnn::result result; if (images.size() == 0) { result.num_total = 1; return result; } const size_t sz = images.size(); #if 10 std::vector< tiny_dnn::label_t> predicted_list(sz, 0); std::vector< tiny_dnn::label_t>actual_list(sz, 0); #pragma omp parallel for for (int i = 0; i < sz; i++) { tiny_dnn::vec_t& predict_y = predict(images[i]); predicted_list[i] = vec_max_index(predict_y); actual_list[i] = vec_max_index(labels[i]); } for (int i = 0; i < sz; i++) { if (predicted_list[i] == actual_list[i]) result.num_success++; result.num_total++; result.confusion_matrix[predicted_list[i]][actual_list[i]]++; } #else for (int i = 0; i < sz; i++) { tiny_dnn::vec_t& predict_y = predict(images[i]); const tiny_dnn::label_t predicted = vec_max_index(predict_y); const tiny_dnn::label_t actual = vec_max_index(labels[i]); if (predicted == actual) result.num_success++; result.num_total++; result.confusion_matrix[predicted][actual]++; } #endif return result; } std::vector<int> test_tolerance(tiny_dnn::tensor_t& images, tiny_dnn::tensor_t& labels) { AT_ASSERT(Tolerance_Set.size() != 0); return get_accuracy(images, labels, Tolerance_Set); } // labels[#] = 0,1,..class-1 tiny_dnn::result get_accuracy(tiny_dnn::tensor_t& images, std::vector <tiny_dnn::label_t>& labels) { std::vector<tiny_dnn::vec_t> vec; label2vec(labels, vec); //on-hot-vector return get_accuracy(images, vec); } tiny_dnn::result test(tiny_dnn::tensor_t& images, tiny_dnn::tensor_t& labels) { return get_accuracy(images, labels); } // labels[#] = on-hot-vector tiny_dnn::result test(tiny_dnn::tensor_t& images, std::vector <tiny_dnn::label_t>& labels) { return get_accuracy(images, labels); } inline int in_data_size() const { return in_channels * in_H*in_W; } inline int out_data_size() const { return out_channels * out_H*out_W; } inline void save(std::string& filename) { torch::save(model, filename); } inline void load(std::string& filename) { try { torch::load(model, filename); } catch (c10::Error& err) { printf("load error[%s]\n", err.what()); } } }; void print_ConfusionMatrix(tiny_dnn::result& res) { //ConfusionMatrix std::cout << "ConfusionMatrix:" << std::endl; res.print_detail(std::cout); std::cout << res.num_success << "/" << res.num_total << std::endl; res.print_summary(std::cout); //printf("accuracy:%.3f%%\n", res.accuracy()); } void print_ConfusionMatrix(std::vector<int>& res, std::vector<float_t>& tol) { //ConfusionMatrix std::cout << "ConfusionMatrix:" << std::endl; for (int i = 0; i < res.size()-1; i++) { printf("tolerance:%.4f %d / %d accuracy:%.3f%%\n", tol[i], res[i], res.back(), 100.0*(float_t)res[i] / (float_t)res.back()); } } } #endif
saxpy.c
/** * @file saxpy.c * * @mainpage saxpy * * @author Xin Wu (PC²) * @date 05.04.2020 * @copyright CC BY-SA 2.0 * * saxpy performs the \c saxpy operation on host as well as accelerator. * The performance (in MB/s) for different implementations is also compared. * * The \c saxpy operation is defined as: * * y := a * x + y * * where: * * - a is a scalar. * - x and y are single-precision vectors each with n elements. */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <omp.h> #include "hsaxpy.h" #include "asaxpy.h" #include "check1ns.h" #include "wtcalc.h" #define TWO26 (1 << 26) #define NLUP (32) /** * @brief Main entry point for saxpy. */ int main(int argc, char *argv[]) { int i, n, iret, ial; size_t nbytes; float a = 2.0f, *x, *y, *yhost, *yaccl, maxabserr; struct timespec rt[2]; double wt; // walltime /* * We need 1 ns time resolution. */ check1ns(); printf("The system supports 1 ns time resolution\n"); /* * check the number of accelerators */ if (0 == omp_get_num_devices()) { printf("No accelerator found ... exit\n"); exit(EXIT_FAILURE); } /* * preparation */ n = TWO26; nbytes = sizeof(float) * n; iret = 0; if (NULL == (x = (float *) malloc(nbytes))) iret = -1; if (NULL == (y = (float *) malloc(nbytes))) iret = -1; if (NULL == (yhost = (float *) malloc(nbytes))) iret = -1; if (NULL == (yaccl = (float *) malloc(nbytes))) iret = -1; if (0 != iret) { printf("error: memory allocation\n"); free(x); free(y); free(yhost); free(yaccl); exit(EXIT_FAILURE); } #pragma omp parallel for default(none) \ shared(a, x, y, yhost, yaccl, n) private(i) for (i = 0; i < n; ++i) { x[i] = rand() % 32 / 32.0f; y[i] = rand() % 32 / 32.0f; yhost[i] = a * x[i] + y[i]; // yhost will be used as reference value yaccl[i] = 0.0f; } printf("total size of x and y is %9.1f MB\n", 2.0 * nbytes / (1 << 20)); printf("tests are averaged over %2d loops\n", NLUP); /* * saxpy on host */ /* * See hsaxpy.c for details: */ memcpy(yaccl, y, nbytes); wtcalc = -1.0; // skip 1st run for timing hsaxpy(n, a, x, yaccl); // check yaccl maxabserr = -1.0f; for (i = 0; i < n; ++i) { maxabserr = fabsf(yaccl[i] - yhost[i]) > maxabserr? fabsf(yaccl[i] - yhost[i]) : maxabserr; } // skip 2nd run for timing hsaxpy(n, a, x, yaccl); // timing : start wtcalc = 0.0; clock_gettime(CLOCK_REALTIME, rt + 0); for (int ilup = 0; ilup < 1; ++ilup) { hsaxpy(n, a, x, yaccl); } clock_gettime(CLOCK_REALTIME, rt + 1); wt=(rt[1].tv_sec - rt[0].tv_sec) + 1.0e-9 * (rt[1].tv_nsec - rt[0].tv_nsec); printf("saxpy on host: %9.1f MB/s %9.1f MB/s maxabserr = %9.1f\n", 3.0 * nbytes / ((1 << 20) * wt), 3.0 * nbytes / ((1 << 20) * wtcalc), maxabserr); /* * saxpy on accl */ for (ial = 0; ial < 6; ++ial) { /* * See asaxpy.c for details: * * ial: * * 0: <<<2^7 , 2^7 >>>, auto scheduling * 1: <<<2^16, 2^10>>>, manual scheduling * 2: <<<2^15, 2^7 >>>, manual scheduling, 16x loop unrolling (2^15*2^7*16==2^26) * 3: <<<2^12, 2^7 >>>, auto scheduling, 16x loop unrolling * 4: de-linearize the vector and then collapse the ji-loop. * otherwise: axpy in MKL */ memcpy(yaccl, y, nbytes); wtcalc = -1.0; // skip 1st run for timing asaxpy(n, a, x, yaccl, ial); // check yaccl maxabserr = -1.0f; for (i = 0; i < n; ++i) { maxabserr = fabsf(yaccl[i] - yhost[i]) > maxabserr? fabsf(yaccl[i] - yhost[i]) : maxabserr; } // skip 2nd run for timing asaxpy(n, a, x, yaccl, ial); // timing : start wtcalc = 0.0; clock_gettime(CLOCK_REALTIME, rt + 0); for (int ilup = 0; ilup < NLUP; ++ilup) { asaxpy(n, a, x, yaccl, ial); } clock_gettime(CLOCK_REALTIME, rt + 1); wt=(rt[1].tv_sec - rt[0].tv_sec) + 1.0e-9 * (rt[1].tv_nsec - rt[0].tv_nsec); printf("saxpy on accl (impl. %d)\ntotal: %9.1f MB/s kernel: %9.1f MB/s maxabserr = %9.1f\n\n", ial, NLUP * 3.0 * nbytes / ((1 << 20) * wt), NLUP * 3.0 * nbytes / ((1 << 20) * wtcalc), maxabserr); } /* * release memory */ free(x); free(y); free(yhost); free(yaccl); return 0; }
LAGraph_BF_full2.c
//------------------------------------------------------------------------------ // LAGraph_BF_full2.c: Bellman-Ford single-source shortest paths, returns tree, // while diagonal of input matrix A needs not to be explicit 0, using the // frontier idea from Roi Lipman //------------------------------------------------------------------------------ // LAGraph, (c) 2021 by The LAGraph Contributors, All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause // See additional acknowledgments in the LICENSE file, // or contact permission@sei.cmu.edu for the full terms. // Contributed by Jinhao Chen and Timothy A. Davis, Texas A&M University //------------------------------------------------------------------------------ // LAGraph_BF_full2: Bellman-Ford single source shortest paths, returning both // the path lengths and the shortest-path tree. // LAGraph_BF_full2 performs a Bellman-Ford to find out shortest path, parent // nodes along the path and the hops (number of edges) in the path from given // source vertex s in the range of [0, n) on graph given as matrix A with size // n*n. The sparse matrix A has entry A(i, j) if there is an edge from vertex i // to vertex j with weight w, then A(i, j) = w. // LAGraph_BF_full2 returns GrB_SUCCESS if it succeeds. In this case, there // are no negative-weight cycles in the graph, and d, pi, and h are returned. // The vector d has d(k) as the shortest distance from s to k. pi(k) = p+1, // where p is the parent node of k-th node in the shortest path. In particular, // pi(s) = 0. h(k) = hop(s, k), the number of edges from s to k in the shortest // path. // If the graph has a negative-weight cycle, GrB_NO_VALUE is returned, and the // GrB_Vectors d(k), pi(k) and h(k) (i.e., *pd_output, *ppi_output and // *ph_output respectively) will be NULL when negative-weight cycle detected. // Otherwise, other errors such as GrB_OUT_OF_MEMORY, GrB_INVALID_OBJECT, and // so on, can be returned, if these errors are found by the underlying // GrB_* functions. //------------------------------------------------------------------------------ #define LG_FREE_WORK \ { \ GrB_free(&d); \ GrB_free(&dtmp); \ GrB_free(&dfrontier); \ GrB_free(&Atmp); \ GrB_free(&BF_Tuple3); \ GrB_free(&BF_lMIN_Tuple3); \ GrB_free(&BF_PLUSrhs_Tuple3); \ GrB_free(&BF_EQ_Tuple3); \ GrB_free(&BF_lMIN_Tuple3_Monoid); \ GrB_free(&BF_lMIN_PLUSrhs_Tuple3); \ LAGraph_Free ((void**)&I, NULL); \ LAGraph_Free ((void**)&J, NULL); \ LAGraph_Free ((void**)&w, NULL); \ LAGraph_Free ((void**)&W, NULL); \ LAGraph_Free ((void**)&h, NULL); \ LAGraph_Free ((void**)&pi, NULL); \ } #define LG_FREE_ALL \ { \ LG_FREE_WORK ; \ GrB_free (pd_output); \ GrB_free (ppi_output); \ GrB_free (ph_output); \ } #include <LAGraph.h> #include <LAGraphX.h> #include <LG_internal.h> // from src/utility typedef void (*LAGraph_binary_function) (void *, const void *, const void *) ; //------------------------------------------------------------------------------ // data type for each entry of the adjacent matrix A and "distance" vector d; // <INFINITY,INFINITY,INFINITY> corresponds to nonexistence of a path, and // the value <0, 0, NULL> corresponds to a path from a vertex to itself //------------------------------------------------------------------------------ typedef struct { double w; // w corresponds to a path weight. GrB_Index h; // h corresponds to a path size or number of hops. GrB_Index pi;// pi corresponds to the penultimate vertex along a path. // vertex indexed as 1, 2, 3, ... , V, and pi = 0 (as nil) // for u=v, and pi = UINT64_MAX (as inf) for (u,v) not in E } BF2_Tuple3_struct; //------------------------------------------------------------------------------ // binary functions, z=f(x,y), where Tuple3xTuple3 -> Tuple3 //------------------------------------------------------------------------------ void BF2_lMIN2 ( BF2_Tuple3_struct *z, const BF2_Tuple3_struct *x, const BF2_Tuple3_struct *y ) { if (x->w < y->w || (x->w == y->w && x->h < y->h) || (x->w == y->w && x->h == y->h && x->pi < y->pi)) { if (z != x) { *z = *x; } } else { *z = *y; } } void BF2_PLUSrhs2 ( BF2_Tuple3_struct *z, const BF2_Tuple3_struct *x, const BF2_Tuple3_struct *y ) { z->w = x->w + y->w ; z->h = x->h + y->h ; z->pi = (x->pi != UINT64_MAX && y->pi != 0) ? y->pi : x->pi ; } void BF2_EQ ( bool *z, const BF2_Tuple3_struct *x, const BF2_Tuple3_struct *y ) { (*z) = (x->w == y->w && x->h == y->h && x->pi == y->pi) ; } // Given a n-by-n adjacency matrix A and a source vertex s. // If there is no negative-weight cycle reachable from s, return the distances // of shortest paths from s and parents along the paths as vector d. Otherwise, // returns d=NULL if there is a negtive-weight cycle. // pd_output is pointer to a GrB_Vector, where the i-th entry is d(s,i), the // sum of edges length in the shortest path // ppi_output is pointer to a GrB_Vector, where the i-th entry is pi(i), the // parent of i-th vertex in the shortest path // ph_output is pointer to a GrB_Vector, where the i-th entry is h(s,i), the // number of edges from s to i in the shortest path // A has weights on corresponding entries of edges // s is given index for source vertex GrB_Info LAGraph_BF_full2 ( GrB_Vector *pd_output, //the pointer to the vector of distance GrB_Vector *ppi_output, //the pointer to the vector of parent GrB_Vector *ph_output, //the pointer to the vector of hops const GrB_Matrix A, //matrix for the graph const GrB_Index s //given index of the source ) { GrB_Info info; char *msg = NULL ; // tmp vector to store distance vector after n (i.e., V) loops GrB_Vector d = NULL, dtmp = NULL, dfrontier = NULL; GrB_Matrix Atmp = NULL; GrB_Type BF_Tuple3; GrB_BinaryOp BF_lMIN_Tuple3; GrB_BinaryOp BF_PLUSrhs_Tuple3; GrB_BinaryOp BF_EQ_Tuple3; GrB_Monoid BF_lMIN_Tuple3_Monoid; GrB_Semiring BF_lMIN_PLUSrhs_Tuple3; GrB_Index nrows, ncols, n, nz; // n = # of row/col, nz = # of nnz in graph GrB_Index *I = NULL, *J = NULL; // for col/row indices of entries from A GrB_Index *h = NULL, *pi = NULL; double *w = NULL; BF2_Tuple3_struct *W = NULL; LG_ASSERT (A != NULL && pd_output != NULL && ppi_output != NULL && ph_output != NULL, GrB_NULL_POINTER) ; *pd_output = NULL; *ppi_output = NULL; *ph_output = NULL; GRB_TRY (GrB_Matrix_nrows (&nrows, A)) ; GRB_TRY (GrB_Matrix_ncols (&ncols, A)) ; GRB_TRY (GrB_Matrix_nvals (&nz, A)); LG_ASSERT_MSG (nrows == ncols, -1002, "A must be square") ; n = nrows; LG_ASSERT_MSG (s < n, GrB_INVALID_INDEX, "invalid source node") ; //-------------------------------------------------------------------------- // create all GrB_Type GrB_BinaryOp GrB_Monoid and GrB_Semiring //-------------------------------------------------------------------------- // GrB_Type GRB_TRY (GrB_Type_new(&BF_Tuple3, sizeof(BF2_Tuple3_struct))); // GrB_BinaryOp GRB_TRY (GrB_BinaryOp_new(&BF_EQ_Tuple3, (LAGraph_binary_function) (&BF2_EQ), GrB_BOOL, BF_Tuple3, BF_Tuple3)); GRB_TRY (GrB_BinaryOp_new(&BF_lMIN_Tuple3, (LAGraph_binary_function) (&BF2_lMIN2), BF_Tuple3, BF_Tuple3, BF_Tuple3)); GRB_TRY (GrB_BinaryOp_new(&BF_PLUSrhs_Tuple3, (LAGraph_binary_function)(&BF2_PLUSrhs2), BF_Tuple3, BF_Tuple3, BF_Tuple3)); // GrB_Monoid BF2_Tuple3_struct BF_identity = (BF2_Tuple3_struct) { .w = INFINITY, .h = UINT64_MAX, .pi = UINT64_MAX }; GRB_TRY (GrB_Monoid_new_UDT(&BF_lMIN_Tuple3_Monoid, BF_lMIN_Tuple3, &BF_identity)); //GrB_Semiring GRB_TRY (GrB_Semiring_new(&BF_lMIN_PLUSrhs_Tuple3, BF_lMIN_Tuple3_Monoid, BF_PLUSrhs_Tuple3)); //-------------------------------------------------------------------------- // allocate arrays used for tuplets //-------------------------------------------------------------------------- LAGRAPH_TRY (LAGraph_Malloc ((void **) &I, nz, sizeof(GrB_Index), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &J, nz, sizeof(GrB_Index), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &w, nz, sizeof(double), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &W, nz, sizeof(BF2_Tuple3_struct), msg)) ; //-------------------------------------------------------------------------- // create matrix Atmp based on A, while its entries become BF_Tuple3 type //-------------------------------------------------------------------------- GRB_TRY (GrB_Matrix_extractTuples_FP64(I, J, w, &nz, A)); int nthreads, nthreads_outer, nthreads_inner ; LG_TRY (LAGraph_GetNumThreads (&nthreads_outer, &nthreads_inner, msg)) ; nthreads = nthreads_outer * nthreads_inner ; printf ("nthreads %d\n", nthreads) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (GrB_Index k = 0; k < nz; k++) { if (w[k] == 0) //diagonal entries { W[k] = (BF2_Tuple3_struct) { .w = 0, .h = 0, .pi = 0 }; } else { W[k] = (BF2_Tuple3_struct) { .w = w[k], .h = 1, .pi = I[k] + 1 }; } } GRB_TRY (GrB_Matrix_new(&Atmp, BF_Tuple3, n, n)); GRB_TRY (GrB_Matrix_build_UDT(Atmp, I, J, W, nz, BF_lMIN_Tuple3)); LAGraph_Free ((void**)&I, NULL); LAGraph_Free ((void**)&J, NULL); LAGraph_Free ((void**)&W, NULL); LAGraph_Free ((void**)&w, NULL); //-------------------------------------------------------------------------- // create and initialize "distance" vector d //-------------------------------------------------------------------------- GRB_TRY (GrB_Vector_new(&d, BF_Tuple3, n)); // initial distance from s to itself BF2_Tuple3_struct d0 = (BF2_Tuple3_struct) { .w = 0, .h = 0, .pi = 0 }; GRB_TRY (GrB_Vector_setElement_UDT(d, &d0, s)); //-------------------------------------------------------------------------- // start the Bellman Ford process //-------------------------------------------------------------------------- // copy d to dtmp in order to create a same size of vector GRB_TRY (GrB_Vector_dup(&dtmp, d)); GRB_TRY (GrB_Vector_dup(&dfrontier, d)); bool same= false; // variable indicating if d == dtmp int64_t iter = 0; // number of iterations // terminate when no new path is found or more than V-1 loops while (!same && iter < n - 1) { // execute semiring on d and A, and save the result to dtmp GRB_TRY (GrB_vxm(dfrontier, GrB_NULL, GrB_NULL, BF_lMIN_PLUSrhs_Tuple3, dfrontier, Atmp, GrB_NULL)); // dtmp[i] = min(d[i], dfrontier[i]). GrB_Vector_eWiseAdd_BinaryOp(dtmp, GrB_NULL, GrB_NULL, BF_lMIN_Tuple3, d, dfrontier, GrB_NULL); LG_TRY (LAGraph_Vector_IsEqual_op(&same, dtmp, d, BF_EQ_Tuple3, NULL)); if (!same) { GrB_Vector ttmp = dtmp; dtmp = d; d = ttmp; } iter ++; } // check for negative-weight cycle only when there was a new path in the // last loop, otherwise, there can't be a negative-weight cycle. if (!same) { // execute semiring again to check for negative-weight cycle GRB_TRY (GrB_vxm(dfrontier, GrB_NULL, GrB_NULL, BF_lMIN_PLUSrhs_Tuple3, dfrontier, Atmp, GrB_NULL)); // dtmp[i] = min(d[i], dfrontier[i]). GrB_Vector_eWiseAdd_BinaryOp(dtmp, GrB_NULL, GrB_NULL, BF_lMIN_Tuple3, d, dfrontier, GrB_NULL); // if d != dtmp, then there is a negative-weight cycle in the graph LG_TRY (LAGraph_Vector_IsEqual_op(&same, dtmp, d, BF_EQ_Tuple3, NULL)); if (!same) { // printf("A negative-weight cycle found. \n"); LG_FREE_ALL; return (GrB_NO_VALUE) ; } } //-------------------------------------------------------------------------- // extract tuple from "distance" vector d and create GrB_Vectors for output //-------------------------------------------------------------------------- LAGRAPH_TRY (LAGraph_Malloc ((void **) &I, n, sizeof(GrB_Index), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &W, n, sizeof(BF2_Tuple3_struct), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &w, n, sizeof(double), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &h, n, sizeof(GrB_Index), msg)) ; LAGRAPH_TRY (LAGraph_Malloc ((void **) &pi, n, sizeof(GrB_Index), msg)) ; nz = n ; GRB_TRY (GrB_Vector_extractTuples_UDT (I, (void *) W, &nz, d)); for (GrB_Index k = 0; k < nz; k++) { w [k] = W[k].w ; h [k] = W[k].h ; pi[k] = W[k].pi; } GRB_TRY (GrB_Vector_new(pd_output, GrB_FP64, n)); GRB_TRY (GrB_Vector_new(ppi_output, GrB_UINT64, n)); GRB_TRY (GrB_Vector_new(ph_output, GrB_UINT64, n)); GRB_TRY (GrB_Vector_build (*pd_output , I, w , nz, GrB_MIN_FP64 )); GRB_TRY (GrB_Vector_build (*ppi_output, I, pi, nz, GrB_MIN_UINT64)); GRB_TRY (GrB_Vector_build (*ph_output , I, h , nz, GrB_MIN_UINT64)); LG_FREE_WORK; return (GrB_SUCCESS) ; }
ccm.h
#pragma once #include <ctime> #include <deque> #include <queue> #include "hash.h" #include "update.h" #include "median.h" #include "compact_vector/compact_vector.hpp" namespace sketch { inline namespace common { namespace detail { template<typename T1, unsigned int BITS, typename T2, typename Allocator> static inline void zero_memory(compact::vector<T1, BITS, T2, Allocator> &v, size_t newsz=0) { std::memset(v.get(), 0, v.bytes()); // zero array } template<typename T1, unsigned int BITS, typename T2, typename Allocator> static inline void zero_memory(compact::ts_vector<T1, BITS, T2, Allocator> &v, size_t newsz=0) { std::memset(v.get(), 0, v.bytes()); // zero array } } } inline namespace cm { using common::detail::tmpbuffer; using common::Allocator; using std::int64_t; #if NOT_THREADSAFE template<size_t NBITS> class DefaultStaticCompactVectorType: public ::compact::vector<uint64_t, NBITS, uint64_t, Allocator<uint64_t>> { public: DefaultStaticCompactVectorType(size_t nb, size_t nelem): ::compact::vector<uint64_t, NBITS, uint64_t, Allocator<uint64_t>>(nelem) {} }; using DefaultCompactVectorType = ::compact::vector<uint64_t, 0, uint64_t, Allocator<uint64_t>>; #else using DefaultCompactVectorType = ::compact::ts_vector<uint64_t, 0, uint64_t, Allocator<uint64_t>>; template<size_t NBITS> class DefaultStaticCompactVectorType: public ::compact::ts_vector<uint64_t, NBITS, uint64_t, Allocator<uint64_t>> { public: DefaultStaticCompactVectorType(size_t nb, size_t nelem): ::compact::ts_vector<uint64_t, NBITS, uint64_t, Allocator<uint64_t>>(nelem) {} }; #endif namespace detail { template<typename T, typename AllocatorType> static inline double sqrl2(const std::vector<T, AllocatorType> &v, uint32_t nhashes, uint32_t l2sz) { tmpbuffer<double, 8> mem(nhashes); double *ptr = mem.get(); #if defined(_BLAZE_MATH_CUSTOMMATRIX_H_) blaze::CustomMatrix<T, blaze::aligned, blaze::unpadded> data(v.data(), nhashes, size_t(1) << l2sz); for(size_t i = 0; i < data.rows(); ++i) { ptr[i] = blaze::norm(row(data, i)); } #else using VT = typename vec::SIMDTypes<T>::VType; using VS = vec::SIMDTypes<T>; VT sum = VS::set1(0); static constexpr size_t ct = VS::COUNT; for(size_t i = 0; i < nhashes; ++i) { const T *p1 = &v[i << l2sz], *p2 = &v[(i+1)<<l2sz]; if(VS::is_aligned) { while(p2 - p1 > ct) { const auto el = *reinterpret_cast<const VT *>(p1); sum = VS::add(sum, VS::mul(el, el)); p1 += ct; } } else { while(p2 - p1 > ct) { const auto el = VT::loadu(p1); sum = VS::add(sum, VS::mul(el, el)); p1 += ct; } } T full_sum = sum.sum(); while(p1 < p2) full_sum += *p1 * *p1, ++p1; ptr[i] = full_sum; } #endif return std::sqrt(median(ptr, nhashes)); } template<typename T, typename AllocatorType> static inline double sqrl2(const std::vector<T, AllocatorType> &v, const std::vector<T, AllocatorType> &v2, uint32_t nhashes, uint32_t l2sz) { assert(v.size() == v2.size()); tmpbuffer<double, 8> mem(nhashes); double *ptr = mem.get(); #if defined(_BLAZE_MATH_CUSTOMMATRIX_H_) using CM = blaze::CustomMatrix<T, blaze::aligned, blaze::unpadded>; const CM lv(v.data(), nhashes, size_t(1) << l2sz); const CM rv(v2.data(), nhashes, size_t(1) << l2sz); for(auto i = 0u; i < lv.rows(); ++i) { ptr[i] = blaze::norm(row(lv, i) * row(rv, i)); // Elementwise multiplication } #else using VT = typename vec::SIMDTypes<T>::VType; using VS = vec::SIMDTypes<T>; VT sum = VS::set1(0); for(size_t i = 0; i < nhashes; ++i) { auto p1 = &v[i << l2sz], p2 = &v2[i << l2sz], p1e = &v[(i + 1) << l2sz]; T full_sum = std::abs(*p1++ * *p2++); while(p1 != p1e) full_sum += std::pow(*p1++ * *p2++, 2); ptr[i] = std::sqrt(full_sum); } #endif return median(ptr, nhashes); } template<typename T1, unsigned int BITS, typename T2, typename Allocator> static inline double sqrl2(const compact::vector<T1, BITS, T2, Allocator> &v, uint32_t nhashes, uint32_t l2sz) { tmpbuffer<double, 8> mem(nhashes); double *ptr = mem.get(); for(size_t i = 0; i < nhashes; ++i) { size_t start = i << l2sz, end = (i + 1) << l2sz; double sum = 0; while(start != end) { int64_t val = v[start++]; sum += val * val; } ptr[i] = std::sqrt(sum); } return median(ptr, nhashes); } template<typename T1, unsigned int BITS, typename T2, typename Allocator> static inline double sqrl2(const compact::vector<T1, BITS, T2, Allocator> &v, const compact::vector<T1, BITS, T2, Allocator> &v2, uint32_t nhashes, uint32_t l2sz) { tmpbuffer<double, 8> mem(nhashes); double *ptr = mem.get(); for(size_t i = 0; i < nhashes; ++i) { size_t start = i << l2sz, end = (i + 1) << l2sz; double sum = 0; while(start != end) { sum += v[start] * v2[start]; ++start; } ptr[i] = std::sqrt(sum); } return median(ptr, nhashes); } template<typename T1, unsigned int BITS, typename T2, typename Allocator> static inline double sqrl2(const compact::ts_vector<T1, BITS, T2, Allocator> &v, uint32_t nhashes, uint32_t l2sz) { tmpbuffer<double> mem(nhashes); double *ptr = mem.get(); for(size_t i = 0; i < nhashes; ++i) { size_t start = i << l2sz, end = (i + 1) << l2sz; double sum = 0; do { int64_t val = v[start++]; sum += val * val; } while(start != end); ptr[i] = std::sqrt(sum); } return median(ptr, nhashes); } template<typename T1, unsigned int BITS, typename T2, typename Allocator> static inline double sqrl2(const compact::ts_vector<T1, BITS, T2, Allocator> &v, const compact::ts_vector<T1, BITS, T2, Allocator> &v2, uint32_t nhashes, uint32_t l2sz) { tmpbuffer<double, 8> mem(nhashes); double *ptr = mem.get(); for(size_t i = 0; i < nhashes; ++i) { size_t start = i << l2sz, end = (i + 1) << l2sz; double sum = 0; do { sum += v[start] * v2[start]; ++start; } while(start != end); ptr[i] = std::sqrt(sum); } return median(ptr, nhashes); } template<typename T> struct IndexedValue { using Type = typename std::decay_t<decltype(*(std::declval<T>().cbegin()))>; }; } // namespace detail template<typename UpdateStrategy=update::Increment, typename VectorType=DefaultCompactVectorType, typename HashStruct=WangHash, bool conservative_update=true> class ccmbase_t { static_assert(!std::is_same<UpdateStrategy, update::CountSketch>::value || std::is_signed<typename detail::IndexedValue<VectorType>::Type>::value, "If CountSketch is used, value must be signed."); protected: VectorType data_; UpdateStrategy updater_; unsigned nhashes_; unsigned l2sz_:16; unsigned nbits_:16; HashStruct hf_; uint64_t mask_; uint64_t subtbl_sz_; std::vector<uint64_t, common::Allocator<uint64_t>> seeds_; public: using counter_register_type = typename std::decay<decltype(data_[0])>::type; static constexpr bool supports_deletion() { return !conservative_update; } size_t size() const {return data_.size();} std::pair<size_t, size_t> est_memory_usage() const { return std::make_pair(sizeof(*this), seeds_.size() * sizeof(seeds_[0]) + data_.bytes()); } size_t seeds_size() const {return seeds_.size();} void clear() { common::detail::zero_memory(data_, ilog2(subtbl_sz_)); } double l2est() const { return detail::sqrl2(data_, nhashes_, l2sz_); } double join_size_l2est(const ccmbase_t &o) const { PREC_REQ(o.size() == this->size(), "tables must have the same size\n"); return detail::sqrl2(data_, o.data_, nhashes_, l2sz_); } template<typename Func> void for_each_register(const Func &func) { for(size_t i = 0; i < data_.size(); ++i) func(data_[i]); } template<typename Func> void for_each_register(const Func &func) const { for(size_t i = 0; i < data_.size(); ++i) func(data_[i]); } ccmbase_t(ccmbase_t &&o): data_(std::move(o.data_)), updater_(std::move(o.updater_)), nhashes_(o.nhashes_), l2sz_(o.l2sz_), nbits_(o.nbits_), hf_(std::move(o.hf_)), mask_(o.mask_), subtbl_sz_(o.subtbl_sz_), seeds_(std::move(o.seeds_)) { } ccmbase_t(const ccmbase_t &o) = default; //ccmbase_t(ccmbase_t &&o) = default; template<typename... Args> ccmbase_t(int nbits, int l2sz, int64_t nhashes=4, uint64_t seed=0, Args &&... args): data_(nbits, nhashes << l2sz), updater_(seed + l2sz * nbits * nhashes), nhashes_(nhashes), l2sz_(l2sz), nbits_(nbits), hf_(std::forward<Args>(args)...), mask_((1ull << l2sz) - 1), subtbl_sz_(1ull << l2sz) { if(HEDLEY_UNLIKELY(nbits < 0)) throw std::runtime_error("Number of bits cannot be negative."); if(HEDLEY_UNLIKELY(l2sz < 0)) throw std::runtime_error("l2sz cannot be negative."); if(HEDLEY_UNLIKELY(nhashes < 0)) throw std::runtime_error("nhashes cannot be negative."); std::mt19937_64 mt(seed + 4); while(seeds_.size() < static_cast<unsigned>(nhashes)) seeds_.emplace_back(mt()); clear(); VERBOSE_ONLY(std::fprintf(stderr, "data size: %zu. nbits per entry: %u\n", data_.size(), nbits);) } VectorType &ref() {return data_;} template<typename T, typename=std::enable_if_t<!std::is_arithmetic<T>::value>> auto addh(const T &x) { uint64_t hv = hf_(x); return add(hv); } auto addh(uint64_t val) {return add(val);} auto addh_val(uint64_t val) {return add(val);} template<typename T> T hash(T val) const { return hf_(val); } uint64_t subhash(uint64_t val, uint64_t seedind) const { return hash(((val ^ seeds_[seedind]) & mask_) + (val & mask_)); } double wj_est(const ccmbase_t &o) const { std::fprintf(stderr, "[%s:%s:%d] Warning: This function should not be used.\n"); #if WJMETH0 tmpbuffer<double> counts(nhashes_); auto p = counts.get(); #elif MINMETH double minest = std::numeric_limits<double>::max(); #else double minest = 0.; #endif for(size_t i = 0; i < nhashes_; ++i) { uint64_t n = 0, d = 0; uint64_t d1, d2; for(size_t j = (i << l2sz_), e = (i + 1) << l2sz_; j < e; ++j) { d1 = data_[j] > 0 ? data_[i]: -data_[i], d2 = o.data_[j] >0 ? o.data_[j]: -o.data_[j]; n += std::min(d1, d2); d += std::max(d1, d2); } #if WJMETH0 *p++ = double(n) / d; #elif MINMETH minest = std::min(double(n) / d, minest); #else minest += double(n) / d; #endif } #if WJMETH0 return median(counts.get(), nhashes_); #elif MINMETH return minest; #else return minest / nhashes_; #endif } uint64_t mask() const {return mask_;} auto np() const {return l2sz_;} auto &at_pos(uint64_t hv, uint64_t seedind) { return data_[(hv & mask_) + (seedind << np())]; } const auto &at_pos(uint64_t hv, uint64_t seedind) const { return data_[(hv & mask_) + (seedind << np())]; } bool may_contain(uint64_t val) const { throw std::runtime_error("This needs to be rewritten after subhash refactoring."); return true; } using Space = vec::SIMDTypes<uint64_t>; uint32_t may_contain(Space::VType val) const { throw std::runtime_error("This needs to be rewritten after subhash refactoring."); return true; } static constexpr bool is_increment = std::is_same<UpdateStrategy, update::Increment>::value; ssize_t add(const uint64_t val) { unsigned nhdone = 0; ssize_t ret; CONST_IF(conservative_update) { std::vector<uint64_t> indices, best_indices; indices.reserve(nhashes_); //std::fprintf(stderr, "Doing SIMD stuff\n"); //std::fprintf(stderr, "Doing Leftover stuff\n"); while(nhdone < nhashes_) { assert(seeds_.data()); uint64_t hv = hash(val, nhdone); auto index = subtbl_sz_ * nhdone++ + (hv & mask_); indices.push_back(index); } #if 0 if(val == 137) { for(const auto v: indices) std::fprintf(stderr, "index for 137: %u\n", unsigned(v)); } #endif best_indices.push_back(indices[0]); ssize_t minval = data_.operator[](indices[0]); for(size_t i(1); i < indices.size(); ++i) { unsigned score; if((score = data_.operator[](indices[i])) == minval) { best_indices.push_back(indices[i]); } else if(score < minval) { best_indices.clear(); best_indices.push_back(indices[i]); minval = score; } } //std::fprintf(stderr, "Now update\n"); updater_(best_indices, data_, nbits_); ret = minval; //std::fprintf(stderr, "Now updated\n"); } else { // not conservative update. This means we support deletions ret = std::numeric_limits<decltype(ret)>::max(); const auto maxv = 1ull << nbits_; std::vector<uint64_t> indices{0}; while(nhdone < nhashes_) { uint64_t hv = hash(val, nhdone); auto ind = (hv & mask_) + subtbl_sz_ * nhdone++; indices[0] = ind; updater_(indices, data_, maxv); ret = std::min(ret, ssize_t(data_[ind])); } } return ret + is_increment; } auto hash(uint64_t x, unsigned index) const { return hash(x ^ seeds_[index]); } uint64_t est_count(uint64_t val) const { uint64_t ret = std::numeric_limits<uint64_t>::max(); for(unsigned i = 0; i < nhashes_; ++i) { auto hv = hash(val, i); ret = std::min(ret, uint64_t(data_[(hv & mask_) + subtbl_sz_ * i])); } return updater_.est_count(ret); } ccmbase_t operator+(const ccmbase_t &other) const { ccmbase_t cpy = *this; cpy += other; return cpy; } ccmbase_t operator&(const ccmbase_t &other) const { ccmbase_t cpy = *this; cpy &= other; return cpy; } ccmbase_t &operator&=(const ccmbase_t &other) { if(seeds_.size() != other.seeds_.size() || !std::equal(seeds_.cbegin(), seeds_.cend(), other.seeds_.cbegin())) throw std::runtime_error("Could not add sketches together with different hash functions."); for(size_t i(0), e(data_.size()); i < e; ++i) { data_[i] = std::min(static_cast<unsigned>(data_[i]), static_cast<unsigned>(other.data_[i])); } return *this; } ccmbase_t &operator+=(const ccmbase_t &other) { if(seeds_.size() != other.seeds_.size() || !std::equal(seeds_.cbegin(), seeds_.cend(), other.seeds_.cbegin())) throw std::runtime_error("Could not add sketches together with different hash functions."); for(size_t i(0), e(data_.size()); i < e; ++i) { data_[i] = updater_.combine(data_[i], other.data_[i]); } return *this; } }; template<typename HashStruct=WangHash, typename CounterType=int32_t, typename=typename std::enable_if<std::is_signed<CounterType>::value>::type> class csbase_t { /* * Commentary: because of chance, one can end up with a negative number as an estimate. * Either the item collided with another item which was quite large and it was outweighed * or it and others in the bucket were not heavy enough and by chance it did * not weigh over the other items with the opposite sign. Treat these as 0s. */ std::vector<CounterType, Allocator<CounterType>> core_; uint32_t np_, nh_; const HashStruct hf_; uint64_t mask_; std::vector<CounterType, Allocator<CounterType>> seeds_; uint64_t seedseed_; CounterType *data() {return core_.data();} const CounterType *data() const {return core_.data();} public: template<typename...Args> csbase_t(unsigned np, unsigned nh=1, unsigned seedseed=137, Args &&...args): core_(uint64_t(nh) << np), np_(np), nh_(nh), hf_(std::forward<Args>(args)...), mask_((1ull << np_) - 1), seeds_(nh_), seedseed_(seedseed) { //DEPRECATION_WARNING("csbase_t will be deprecated in favor of cs4wbase_t moving forward."); DefaultRNGType gen(np + nh + seedseed); for(auto &el: seeds_) el = gen(); } double l2est() const { return sqrl2(core_, nh_, np_); } CounterType addh_val(uint64_t val) { std::vector<CounterType> counts(nh_); auto cptr = counts.data(); uint64_t v = hf_(val); cptr[0] = add(v, 0); for(unsigned ind = 1;ind < nh_; ++ind) cptr[ind] = add(hf_(seeds_[ind] ^ val), ind); return median(cptr, nh_); } template<typename T> CounterType addh_val(const T &x) { uint64_t hv = hf_(x); return addh_val(hv); } template<typename T, typename=std::enable_if_t<!std::is_arithmetic<T>::value>> void addh(const T &x) { uint64_t hv = hf_(x); addh(hv); } void addh(uint64_t val) { uint64_t v = hf_(val); auto it = seeds_.begin(); add(v, 0); unsigned ind = 1; while(ind < nh_) add(hf_(*it++ ^ val), ind++); } template<typename Func> void for_each_register(const Func &func) { for(size_t i = 0; i < core_.size(); ++i) func(core_[i]); } template<typename Func> void for_each_register(const Func &func) const { for(size_t i = 0; i < core_.size(); ++i) func(core_[i]); } void subh(uint64_t val) { uint64_t v = hf_(val); auto it = seeds_.begin(); sub(v, 0); unsigned ind = 1; while(ind < nh_) sub(hf_(*it++ ^ val), ind++); } auto subh_val(uint64_t val) { tmpbuffer<CounterType> counts(nh_); auto cptr = counts.get(); uint64_t v = hf_(val); auto it = seeds_.begin(); *cptr++ = sub(v, 0); unsigned ind = 1; while(ind < nh_) *cptr++ = sub(hf_(*it++ ^ val), ind++); return median(counts.get(), nh_); } INLINE size_t index(uint64_t hv, unsigned subidx) const noexcept { return (hv & mask_) + (subidx << np_); } INLINE auto add(uint64_t hv, unsigned subidx) noexcept { #if !NDEBUG at_pos(hv, subidx) += sign(hv); return at_pos(hv, subidx); #else return at_pos(hv, subidx) += sign(hv); #endif } INLINE auto vatpos(uint64_t hv, unsigned subidx) const noexcept { return at_pos(hv, subidx) * sign(hv); } INLINE auto sub(uint64_t hv, unsigned subidx) noexcept { return at_pos(hv, subidx) -= sign(hv); } INLINE auto &at_pos(uint64_t hv, unsigned subidx) noexcept { assert(index(hv, subidx) < core_.size() || !std::fprintf(stderr, "hv & mask_: %zu. subidx %d. np: %d. nh: %d. size: %zu\n", size_t(hv&mask_), subidx, np_, nh_, core_.size())); return core_[index(hv, subidx)]; } INLINE auto at_pos(uint64_t hv, unsigned subidx) const noexcept { assert((hv & mask_) + (subidx << np_) < core_.size()); return core_[index(hv, subidx)]; } INLINE int sign(uint64_t hv) const { return hv & (1ul << np_) ? 1: -1; } CounterType est_count(uint64_t val) const { common::detail::tmpbuffer<CounterType> mem(nh_); CounterType *ptr = mem.get(); uint64_t v = hf_(val); auto it = seeds_.begin(); *ptr++ = vatpos(v, 0); for(unsigned ind = 1;ind < nh_; ++it, ++ptr, ++ind) { auto hv = hf_(*it ^ val); *ptr = vatpos(hv, ind); } //std::for_each(mem.get(), mem.get() + nh_, [p=mem.get()](const auto &x) {std::fprintf(stderr, "Count estimate for ind %zd is %u\n", &x - p, int32_t(x));}); /// return median(mem.get(), nh_); } csbase_t &operator+=(const csbase_t &o) { precondition_require(o.size() == this->size(), "tables must have the same size\n"); using VS = vec::SIMDTypes<CounterType>; using VT = typename VS::VType; VT sum = VS::set1(0); static constexpr uint32_t lim = ilog2(VS::COUNT); if(np_ > lim && VS::aligned(o.data()) && VS::aligned(data())) { size_t i = 0; do { VS::store(data() + i, VS::add(VS::load(o.data() + i), VS::load(data() + i))); i += VS::COUNT; } while(i < core_.size()); } else { for(size_t i = 0; i < core_.size(); ++i) core_[i] += o.core_[i]; } return *this; } csbase_t operator+(const csbase_t &o) const { auto tmp = *this; tmp += o; return tmp; } csbase_t &operator-=(const csbase_t &o) { // TODO: SIMD optimize (but how often is this needed?) PREC_REQ(core_.size() == o.core_.size(), "mismatched sizes"); for(size_t i = 0; i < core_.size(); ++i) core_[i] -= o.core_[i]; return *this; } csbase_t operator-(const csbase_t &o) const { auto tmp = *this; tmp -= o; return tmp; } csbase_t fold(int n=1) const { PREC_REQ(n >= 1, "n < 0 is meaningless and n = 1 uses a copy instead."); PREC_REQ(n <= np_, "Can't fold to less than 1"); csbase_t ret(np_ - n, nh_, seedseed_); schism::Schismatic<uint32_t> div(core_.size()); // More cache-efficient way to traverse than iterating over the final sketch for(size_t i = 0; i < core_.size(); ++i) ret.core_[div.mod(i)] += core_[i]; return ret; } }; template<typename CounterType=int32_t, typename HasherSetType=KWiseHasherSet<4>> class cs4wbase_t { /* * Commentary: because of chance, one can end up with a negative number as an estimate. * Either the item collided with another item which was quite large and it was outweighed * or it and others in the bucket were not heavy enough and by chance it did * not weigh over the other items with the opposite sign. Treat these as 0s. */ static_assert(std::is_signed<CounterType>::value, "CounterType must be signed"); // Note: in order to hash other types, you'd need to subclass the HasherSet // class in hash.h and provide an overload for your type, or hash the items // yourself and insert them first. // This is more cumbersome. std::vector<CounterType, Allocator<CounterType>> core_; uint32_t np_, nh_; uint64_t mask_; uint64_t seedseed_; const HasherSetType hf_; CounterType *data() {return core_.data();} const CounterType *data() const {return core_.data();} // TODO: use a simpler hash function under the assumption that it doesn't matter? size_t size() const {return core_.size();} public: cs4wbase_t(unsigned np, unsigned nh=1, unsigned seedseed=137): np_(np), nh_(nh), mask_((1ull << np_) - 1), seedseed_(seedseed), hf_(nh_, seedseed) { assert(hf_.size() == nh_); nh_ += (nh % 2 == 0); core_.resize(nh_ << np_); POST_REQ(core_.size() == (nh_ << np_), "core must be properly sized"); } double l2est() const { return sqrl2(core_, nh_, np_); } CounterType addh_val(uint64_t val) { std::vector<CounterType> counts(nh_); auto cptr = counts.data(); for(unsigned added = 0; added < nh_; ++added) cptr[added] = add(val, added); return median(cptr, nh_); } auto addh(uint64_t val) {return addh_val(val);} auto nhashes() const {return nh_;} auto p() const {return np_;} template<typename T, typename=std::enable_if_t<std::is_arithmetic<T>::value>> auto addh_val(T x) { uint64_t hv = hf_(static_cast<uint64_t>(x)); return addh_val(hv); } template<typename T, typename=std::enable_if_t<!std::is_arithmetic<T>::value>> auto addh_val(const T &x) { uint64_t hv = hf_(x); return addh_val(hv); } template<typename T, typename=std::enable_if_t<std::is_arithmetic<T>::value>> auto addh(T x) {return addh_val(static_cast<uint64_t>(x));} void subh(uint64_t val) { for(unsigned added = 0; added < nh_; ++added) sub(val, added); } auto subh_val(uint64_t val) { tmpbuffer<CounterType> counts(nh_); auto cptr = counts.get(); for(unsigned added = 0; added < nh_; ++added) cptr[added] = sub(val, added); return median(cptr, nh_); } INLINE size_t index(uint64_t hv, unsigned subidx) const noexcept { return (hv & mask_) + (subidx << np_); } INLINE auto add(uint64_t hv, unsigned subidx) noexcept { hv = hf_(hv, subidx); auto &ref = at_pos(hv, subidx); if(ref != std::numeric_limits<CounterType>::max()) // easy branch to predict ref += sign(hv); return ref * sign(hv); } INLINE auto sub(uint64_t hv, unsigned subidx) noexcept { hv = hf_(hv, subidx); auto &ref = at_pos(hv, subidx); if(ref != std::numeric_limits<CounterType>::min()) // easy branch to predict ref -= sign(hv); return ref * sign(hv); } CounterType update(uint64_t val, const double increment=1.) { std::vector<CounterType> counts(nh_); auto cptr = counts.data(); for(unsigned added = 0; added < nh_; ++added) { auto hv = hf_(val, added); auto &ref = at_pos(hv, added); auto shv = sign(hv); ref += increment * shv; cptr[added] = shv * ref; } return median(cptr, nh_); } INLINE auto &at_pos(uint64_t hv, unsigned subidx) noexcept { assert(index(hv, subidx) < core_.size() || !std::fprintf(stderr, "hv & mask_: %zu. subidx %d. np: %d. nh: %d. size: %zu\n", size_t(hv&mask_), subidx, np_, nh_, core_.size())); return core_[index(hv, subidx)]; } INLINE auto at_pos(uint64_t hv, unsigned subidx) const noexcept { assert((hv & mask_) + (subidx << np_) < core_.size()); return core_[index(hv, subidx)]; } double dot_product(const cs4wbase_t &o) const { auto myp = data(), op = o.data(); common::detail::tmpbuffer<CounterType> mem(nh_); auto memp = mem.get(); const size_t tsz = (1ull << np_); double ret = 0.; for(unsigned i = 0u; i < nh_; ++i) { auto lmyp = myp + tsz, lop = op + tsz; #if _OPENMP > 201307L #pragma omp simd #endif for(size_t j = 0; j < tsz; ++j) ret += lmyp[i] * lop[i]; memp[i] = ret; } return median(memp, nh_); } INLINE int sign(uint64_t hv) const noexcept { return hv & (1ul << np_) ? 1: -1; } using Space = vec::SIMDTypes<uint64_t>; INLINE void subh(Space::VType hv) noexcept { hv.for_each([&](auto x) {for(size_t i = 0; i < nh_; sub(x, i++));}); } INLINE void addh(Space::VType hv) noexcept { hv.for_each([&](auto x) {for(size_t i = 0; i < nh_; add(x, i++));}); } CounterType est_count(uint64_t val) const { common::detail::tmpbuffer<CounterType> mem(nh_); CounterType *ptr = mem.get(), *p = ptr; for(unsigned i = 0; i < nh_; ++i) { auto v = hf_(val, i); *p++ = at_pos(v, i) * sign(v); } return median(ptr, nh_); } cs4wbase_t &operator+=(const cs4wbase_t &o) { precondition_require(o.size() == this->size(), "tables must have the same size\n"); using OT = typename vec::SIMDTypes<CounterType>::Type; using VS = vec::SIMDTypes<CounterType>; static constexpr uint32_t lim = ilog2(VS::COUNT); if(np_ > lim && VS::aligned(o.data()) && VS::aligned(data())) { size_t i = 0; do { VS::store(reinterpret_cast<OT *>(data() + i), VS::add(VS::load(reinterpret_cast<const OT *>(o.data() + i)), VS::load(reinterpret_cast<const OT *>(data() + i))) ); i += VS::COUNT; } while(i < core_.size()); } else { for(size_t i = 0; i < core_.size(); ++i) core_[i] += o.core_[i]; } return *this; } cs4wbase_t operator+(const cs4wbase_t &o) const { auto tmp = *this; tmp += o; return tmp; } cs4wbase_t &operator-=(const cs4wbase_t &o) { // TODO: SIMD optimize (but how often is this needed?) PREC_REQ(size() == o.size(), "mismatched sizes"); for(size_t i = 0; i < size(); ++i) core_[i] -= o.core_[i]; return *this; } cs4wbase_t operator-(const cs4wbase_t &o) const { auto tmp = *this; tmp -= o; return tmp; } cs4wbase_t fold(int n=1) const { PREC_REQ(n >= 1, "n < 0 is meaningless and n = 1 uses a copy instead."); PREC_REQ(n <= int(np_), "Can't fold to less than 1"); cs4wbase_t ret(np_ - n, nh_, seedseed_); unsigned destmod = (1ull << ret.p()) - 1; // More cache-efficient way to traverse than iterating over the final sketch const size_t coresubsz = 1ull << p(); for(auto h = 0u; h < nh_; ++h) { auto destptr = &ret.core_[h << ret.p()]; auto coreptr = &core_[h << p()]; for(size_t i = 0; i < coresubsz; ++i) destptr[i & destmod] += coreptr[i]; } return ret; } void read(std::FILE *fp) { std::fread(&np_, sizeof(np_), 1, fp); std::fread(&nh_, sizeof(nh_), 1, fp); std::fread(&seedseed_, sizeof(seedseed_), 1, fp); core_.resize(size_t(nh_) << np_); std::fread(data(), sizeof(CounterType), core_.size(), fp); mask_ = (1ull << np_) - 1; } void write(std::FILE *fp) const { std::fwrite(&np_, sizeof(np_), 1, fp); std::fwrite(&nh_, sizeof(nh_), 1, fp); std::fwrite(&seedseed_, sizeof(seedseed_), 1, fp); std::fwrite(data(), sizeof(CounterType), core_.size(), fp); } void read(std::string p) const { std::FILE *ofp = std::fopen(p.data(), "rb"); if(!ofp) throw std::invalid_argument("File not found"); read(ofp); std::fclose(ofp); } void write(std::string p) const { std::FILE *ofp = std::fopen(p.data(), "wb"); if(!ofp) throw std::invalid_argument("File not found"); write(ofp); std::fclose(ofp); } }; template<typename VectorType=DefaultCompactVectorType, typename HashStruct=WangHash> class cmmbase_t: protected ccmbase_t<update::Increment, VectorType, HashStruct> { uint64_t stream_size_; using BaseType = ccmbase_t<update::Increment, VectorType, HashStruct>; public: cmmbase_t(int nbits, int l2sz, int nhashes=4, uint64_t seed=0): BaseType(nbits, l2sz, nhashes, seed), stream_size_(0) { throw NotImplementedError("count min mean sketch not completed."); } void add(uint64_t val) {this->addh(val);} void addh(uint64_t val) { ++stream_size_; BaseType::addh(val); } uint64_t est_count(uint64_t val) const { return BaseType::est_count(val); // TODO: this (This is just } }; template<typename CMType, template<typename...> class QueueContainer=std::deque, typename...Args> class SlidingWindow { using qc = QueueContainer<uint64_t, Args...>; qc hashes_; public: CMType cm_; size_t queue_size_; SlidingWindow(size_t queue_size, CMType &&cm, qc &&hashes=qc()): hashes_(std::move(hashes)), cm_(std::move(cm)), queue_size_(queue_size) { } void addh(uint64_t v) { cm_.addh(v); if(hashes_.size() == queue_size_) { cm_.subh(hashes_.front()); hashes_.pop_front(); hashes_.push_back(v); } } CMType &sketch() { return cm_; } const CMType &sketch() const { return cm_; } CMType &&release() { return std::move(cm_); } }; using ccm_t = ccmbase_t<>; using cmm_t = cmmbase_t<>; using cs_t = csbase_t<>; using cs4w_t = cs4wbase_t<>; using pccm_t = ccmbase_t<update::PowerOfTwo>; } // namespace cm } // namespace sketch
par_relax.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$ ***********************************************************************EHEADER*/ /****************************************************************************** * * Relaxation scheme * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "Common.h" #include "_hypre_lapack.h" #include "../sstruct_ls/gselim.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGRelax *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGRelax( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_type, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; HYPRE_BigInt global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int n = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt first_ind = hypre_ParVectorFirstIndex(u); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Real *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); HYPRE_Real *f_data = hypre_VectorData(f_local); hypre_Vector *Vtemp_local = hypre_ParVectorLocalVector(Vtemp); HYPRE_Real *Vtemp_data = hypre_VectorData(Vtemp_local); HYPRE_Real *Vext_data = NULL; HYPRE_Real *v_buf_data; HYPRE_Real *tmp_data; hypre_Vector *Ztemp_local; HYPRE_Real *Ztemp_data; hypre_CSRMatrix *A_CSR; HYPRE_Int *A_CSR_i; HYPRE_Int *A_CSR_j; HYPRE_Real *A_CSR_data; hypre_Vector *f_vector; HYPRE_Real *f_vector_data; HYPRE_Int i, j, jr; HYPRE_Int ii, jj; HYPRE_Int ns, ne, size, rest; HYPRE_Int column; HYPRE_Int relax_error = 0; HYPRE_Int num_sends; HYPRE_Int num_recvs; HYPRE_Int index, start; HYPRE_Int num_procs, num_threads, my_id, ip, p; HYPRE_Int vec_start, vec_len; hypre_MPI_Status *status; hypre_MPI_Request *requests; HYPRE_Real *A_mat; HYPRE_Real *b_vec; HYPRE_Real zero = 0.0; HYPRE_Real res, res0, res2; HYPRE_Real one_minus_weight; HYPRE_Real one_minus_omega; HYPRE_Real prod; one_minus_weight = 1.0 - relax_weight; one_minus_omega = 1.0 - omega; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_threads = hypre_NumThreads(); /*----------------------------------------------------------------------- * Switch statement to direct control based on relax_type: * relax_type = 0 -> Jacobi or CF-Jacobi * relax_type = 1 -> Gauss-Seidel <--- very slow, sequential * relax_type = 2 -> Gauss_Seidel: interior points in parallel , * boundary sequential * relax_type = 3 -> hybrid: SOR-J mix off-processor, SOR on-processor * with outer relaxation parameters (forward solve) * relax_type = 4 -> hybrid: SOR-J mix off-processor, SOR on-processor * with outer relaxation parameters (backward solve) * relax_type = 5 -> hybrid: GS-J mix off-processor, chaotic GS on-node * relax_type = 6 -> hybrid: SSOR-J mix off-processor, SSOR on-processor * with outer relaxation parameters * relax_type = 7 -> Jacobi (uses Matvec), only needed in CGNR * relax_type = 19-> Direct Solve, (old version) * relax_type = 29-> Direct solve: use gaussian elimination & BLAS * (with pivoting) (old version) *-----------------------------------------------------------------------*/ switch (relax_type) { case 0: /* Weighted Jacobi */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_points == 0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= one_minus_weight; u_data[i] += relax_weight * res / A_diag_data[A_diag_i[i]]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= one_minus_weight; u_data[i] += relax_weight * res / A_diag_data[A_diag_i[i]]; } } } if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } } break; case 5: /* Hybrid: Jacobi off-processor, chaotic Gauss-Seidel on-processor */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_points == 0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } } break; case 3: /* Hybrid: Jacobi off-processor, Gauss-Seidel on-processor (forward loop) */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } #ifdef HYPRE_USING_PERSISTENT_COMM // JSP: persistent comm can be similarly used for other smoothers hypre_ParCSRPersistentCommHandle *persistent_comm_handle; #endif if (num_procs > 1) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); #ifdef HYPRE_USING_PERSISTENT_COMM persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(1, comm_pkg); v_buf_data = (HYPRE_Real *)persistent_comm_handle->send_data; Vext_data = (HYPRE_Real *)persistent_comm_handle->recv_data; #else v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); #endif if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } HYPRE_Int begin = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0); HYPRE_Int end = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = begin; i < end; i++) { v_buf_data[i - begin] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,i)]; } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle); #else comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); #endif /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle); #else hypre_ParCSRCommHandleDestroy(comm_handle); #endif comm_handle = NULL; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RELAX] -= hypre_MPI_Wtime(); #endif if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) res -= A_diag_data[jj] * u_data[ii]; else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) res -= A_diag_data[jj] * u_data[ii]; else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } } #ifndef HYPRE_USING_PERSISTENT_COMM if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RELAX] += hypre_MPI_Wtime(); #endif } break; case 1: /* Gauss-Seidel VERY SLOW */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); status = hypre_CTAlloc(hypre_MPI_Status, num_recvs+num_sends, HYPRE_MEMORY_HOST); requests= hypre_CTAlloc(hypre_MPI_Request, num_recvs+num_sends, HYPRE_MEMORY_HOST); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ /* for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } */ } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ for (p = 0; p < num_procs; p++) { jr = 0; if (p != my_id) { for (i = 0; i < num_sends; i++) { ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (ip == p) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1)-vec_start; for (j=vec_start; j < vec_start+vec_len; j++) v_buf_data[j] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; hypre_MPI_Isend(&v_buf_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } } hypre_MPI_Waitall(jr,requests,status); hypre_MPI_Barrier(comm); } else { if (num_procs > 1) { for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1)-vec_start; hypre_MPI_Irecv(&Vext_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } hypre_MPI_Waitall(jr,requests,status); } if (relax_points == 0) { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } if (num_procs > 1) hypre_MPI_Barrier(comm); } } if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(status, HYPRE_MEMORY_HOST); hypre_TFree(requests, HYPRE_MEMORY_HOST); } } break; case 2: /* Gauss-Seidel: relax interior points in parallel, boundary sequentially */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); status = hypre_CTAlloc(hypre_MPI_Status, num_recvs+num_sends, HYPRE_MEMORY_HOST); requests= hypre_CTAlloc(hypre_MPI_Request, num_recvs+num_sends, HYPRE_MEMORY_HOST); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ /* for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } */ /*----------------------------------------------------------------- * Relax interior points first *-----------------------------------------------------------------*/ if (relax_points == 0) { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ((A_offd_i[i+1]-A_offd_i[i]) == zero && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } else { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && (A_offd_i[i+1]-A_offd_i[i]) == zero && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } for (p = 0; p < num_procs; p++) { jr = 0; if (p != my_id) { for (i = 0; i < num_sends; i++) { ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (ip == p) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1)-vec_start; for (j=vec_start; j < vec_start+vec_len; j++) v_buf_data[j] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; hypre_MPI_Isend(&v_buf_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } } hypre_MPI_Waitall(jr,requests,status); hypre_MPI_Barrier(comm); } else { if (num_procs > 1) { for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1)-vec_start; hypre_MPI_Irecv(&Vext_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } hypre_MPI_Waitall(jr,requests,status); } if (relax_points == 0) { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ((A_offd_i[i+1]-A_offd_i[i]) != zero && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && (A_offd_i[i+1]-A_offd_i[i]) != zero && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } if (num_procs > 1) hypre_MPI_Barrier(comm); } } if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(status, HYPRE_MEMORY_HOST); hypre_TFree(requests, HYPRE_MEMORY_HOST); } } break; case 4: /* Hybrid: Jacobi off-processor, Gauss-Seidel/SOR on-processor (backward loop) */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = hypre_CTAlloc(HYPRE_Real, n, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) res -= A_diag_data[jj] * u_data[ii]; else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } hypre_TFree(tmp_data, HYPRE_MEMORY_HOST); } else { for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = hypre_CTAlloc(HYPRE_Real, n, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) res -= A_diag_data[jj] * u_data[ii]; else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } hypre_TFree(tmp_data, HYPRE_MEMORY_HOST); } else { for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = hypre_CTAlloc(HYPRE_Real, n, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } hypre_TFree(tmp_data, HYPRE_MEMORY_HOST); } else { for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = hypre_CTAlloc(HYPRE_Real, n, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,res0,res2,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } hypre_TFree(tmp_data, HYPRE_MEMORY_HOST); } else { for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } } break; case 6: /* Hybrid: Jacobi off-processor, Symm. Gauss-Seidel/ SSOR on-processor with outer relaxation parameter */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,res0,res2,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,res0,res2,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } } break; case 7: /* Jacobi (uses ParMatvec) */ { /*----------------------------------------------------------------- * Copy f into temporary vector. *-----------------------------------------------------------------*/ PUSH_RANGE("RELAX",4); #if defined(HYPRE_USING_GPU) && defined(HYPRE_USING_UNIFIED_MEMORY) hypre_SeqVectorPrefetchToDevice(hypre_ParVectorLocalVector(Vtemp)); hypre_SeqVectorPrefetchToDevice(hypre_ParVectorLocalVector(f)); VecCopy(Vtemp_data,f_data,hypre_VectorSize(hypre_ParVectorLocalVector(Vtemp)),HYPRE_STREAM(4)); #else hypre_ParVectorCopy(f,Vtemp); #endif /*----------------------------------------------------------------- * Perform Matvec Vtemp=f-Au *-----------------------------------------------------------------*/ hypre_ParCSRMatrixMatvec(-relax_weight,A, u, relax_weight, Vtemp); #if defined(HYPRE_USING_GPU) && defined(HYPRE_USING_UNIFIED_MEMORY) VecScale(u_data,Vtemp_data,l1_norms,n,HYPRE_STREAM(4)); #else for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ u_data[i] += Vtemp_data[i] / l1_norms[i]; } #endif POP_RANGE; } break; case 8: /* hybrid L1 Symm. Gauss-Seidel */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } } break; case 13: /* hybrid L1 Gauss-Seidel forward solve */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } } break; case 14: /* hybrid L1 Gauss-Seidel backward solve */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } } break; case 19: /* Direct solve: use gaussian elimination */ { HYPRE_Int n_global = (HYPRE_Int) global_num_rows; HYPRE_Int first_index = (HYPRE_Int) first_ind; /*----------------------------------------------------------------- * Generate CSR matrix from ParCSRMatrix A *-----------------------------------------------------------------*/ #ifdef HYPRE_NO_GLOBAL_PARTITION /* all processors are needed for these routines */ A_CSR = hypre_ParCSRMatrixToCSRMatrixAll(A); f_vector = hypre_ParVectorToVectorAll(f); if (n) { #else if (n) { A_CSR = hypre_ParCSRMatrixToCSRMatrixAll(A); f_vector = hypre_ParVectorToVectorAll(f); #endif A_CSR_i = hypre_CSRMatrixI(A_CSR); A_CSR_j = hypre_CSRMatrixJ(A_CSR); A_CSR_data = hypre_CSRMatrixData(A_CSR); f_vector_data = hypre_VectorData(f_vector); A_mat = hypre_CTAlloc(HYPRE_Real, n_global*n_global, HYPRE_MEMORY_HOST); b_vec = hypre_CTAlloc(HYPRE_Real, n_global, HYPRE_MEMORY_HOST); /*--------------------------------------------------------------- * Load CSR matrix into A_mat. *---------------------------------------------------------------*/ for (i = 0; i < n_global; i++) { for (jj = A_CSR_i[i]; jj < A_CSR_i[i+1]; jj++) { column = A_CSR_j[jj]; A_mat[i*n_global+column] = A_CSR_data[jj]; } b_vec[i] = f_vector_data[i]; } hypre_gselim(A_mat,b_vec,n_global,relax_error); for (i = 0; i < n; i++) { u_data[i] = b_vec[first_index+i]; } hypre_TFree(A_mat, HYPRE_MEMORY_HOST); hypre_TFree(b_vec, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } #ifdef HYPRE_NO_GLOBAL_PARTITION else { hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } #endif } break; case 98: /* Direct solve: use gaussian elimination & BLAS (with pivoting) */ { HYPRE_Int n_global = (HYPRE_Int) global_num_rows; HYPRE_Int first_index = (HYPRE_Int) first_ind; HYPRE_Int info; HYPRE_Int one_i = 1; HYPRE_Int *piv; /*----------------------------------------------------------------- * Generate CSR matrix from ParCSRMatrix A *-----------------------------------------------------------------*/ #ifdef HYPRE_NO_GLOBAL_PARTITION /* all processors are needed for these routines */ A_CSR = hypre_ParCSRMatrixToCSRMatrixAll(A); f_vector = hypre_ParVectorToVectorAll(f); if (n) { #else if (n) { A_CSR = hypre_ParCSRMatrixToCSRMatrixAll(A); f_vector = hypre_ParVectorToVectorAll(f); #endif A_CSR_i = hypre_CSRMatrixI(A_CSR); A_CSR_j = hypre_CSRMatrixJ(A_CSR); A_CSR_data = hypre_CSRMatrixData(A_CSR); f_vector_data = hypre_VectorData(f_vector); A_mat = hypre_CTAlloc(HYPRE_Real, n_global*n_global, HYPRE_MEMORY_HOST); b_vec = hypre_CTAlloc(HYPRE_Real, n_global, HYPRE_MEMORY_HOST); /*--------------------------------------------------------------- * Load CSR matrix into A_mat. *---------------------------------------------------------------*/ for (i = 0; i < n_global; i++) { for (jj = A_CSR_i[i]; jj < A_CSR_i[i+1]; jj++) { /* need col major */ column = A_CSR_j[jj]; A_mat[i + n_global*column] = A_CSR_data[jj]; } b_vec[i] = f_vector_data[i]; } piv = hypre_CTAlloc(HYPRE_Int, n_global, HYPRE_MEMORY_HOST); /* write over A with LU */ hypre_dgetrf(&n_global, &n_global, A_mat, &n_global, piv, &info); /*now b_vec = inv(A)*b_vec */ hypre_dgetrs("N", &n_global, &one_i, A_mat, &n_global, piv, b_vec, &n_global, &info); hypre_TFree(piv, HYPRE_MEMORY_HOST); for (i = 0; i < n; i++) { u_data[i] = b_vec[first_index+i]; } hypre_TFree(A_mat, HYPRE_MEMORY_HOST); hypre_TFree(b_vec, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } #ifdef HYPRE_NO_GLOBAL_PARTITION else { hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } #endif } break; } return(relax_error); } /*------------------------------------------------------------------------- * * Gaussian Elimination * *------------------------------------------------------------------------ */ HYPRE_Int hypre_GaussElimSetup (hypre_ParAMGData *amg_data, HYPRE_Int level, HYPRE_Int relax_type) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_GS_ELIM_SETUP] -= hypre_MPI_Wtime(); #endif /* Par Data Structure variables */ hypre_ParCSRMatrix *A = hypre_ParAMGDataAArray(amg_data)[level]; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int global_num_rows = (HYPRE_Int) hypre_ParCSRMatrixGlobalNumRows(A); MPI_Comm comm = hypre_ParCSRMatrixComm(A); MPI_Comm new_comm; /* Generate sub communicator */ hypre_GenerateSubComm(comm, num_rows, &new_comm); if (num_rows) { hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Real *A_mat, *A_mat_local; HYPRE_Int *comm_info, *info, *displs; HYPRE_Int *mat_info, *mat_displs; HYPRE_Int new_num_procs, A_mat_local_size, i, jj, column; HYPRE_BigInt first_row_index = hypre_ParCSRMatrixFirstRowIndex(A); hypre_MPI_Comm_size(new_comm, &new_num_procs); comm_info = hypre_CTAlloc(HYPRE_Int, 2*new_num_procs+1, HYPRE_MEMORY_HOST); mat_info = hypre_CTAlloc(HYPRE_Int, new_num_procs, HYPRE_MEMORY_HOST); mat_displs = hypre_CTAlloc(HYPRE_Int, new_num_procs+1, HYPRE_MEMORY_HOST); info = &comm_info[0]; displs = &comm_info[new_num_procs]; hypre_MPI_Allgather(&num_rows, 1, HYPRE_MPI_INT, info, 1, HYPRE_MPI_INT, new_comm); displs[0] = 0; mat_displs[0] = 0; for (i=0; i < new_num_procs; i++) { displs[i+1] = displs[i]+info[i]; mat_displs[i+1] = global_num_rows*displs[i+1]; mat_info[i] = global_num_rows*info[i]; } hypre_ParAMGDataBVec(amg_data) = hypre_CTAlloc(HYPRE_Real, global_num_rows, HYPRE_MEMORY_HOST); A_mat_local_size = global_num_rows*num_rows; A_mat_local = hypre_CTAlloc(HYPRE_Real, A_mat_local_size, HYPRE_MEMORY_HOST); A_mat = hypre_CTAlloc(HYPRE_Real, global_num_rows*global_num_rows, HYPRE_MEMORY_HOST); /* load local matrix into A_mat_local */ for (i = 0; i < num_rows; i++) { for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { /* need col major */ column = A_diag_j[jj]+first_row_index; A_mat_local[i*global_num_rows + column] = A_diag_data[jj]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { /* need col major */ column = col_map_offd[A_offd_j[jj]]; A_mat_local[i*global_num_rows + column] = A_offd_data[jj]; } } hypre_MPI_Allgatherv( A_mat_local, A_mat_local_size, HYPRE_MPI_REAL, A_mat, mat_info, mat_displs, HYPRE_MPI_REAL, new_comm); if (relax_type == 99) { HYPRE_Real *AT_mat; AT_mat = hypre_CTAlloc(HYPRE_Real, global_num_rows*global_num_rows, HYPRE_MEMORY_HOST); for (i=0; i < global_num_rows; i++) for (jj=0; jj < global_num_rows; jj++) AT_mat[i*global_num_rows + jj] = A_mat[i+ jj*global_num_rows]; hypre_ParAMGDataAMat(amg_data) = AT_mat; hypre_TFree(A_mat, HYPRE_MEMORY_HOST); } else hypre_ParAMGDataAMat(amg_data) = A_mat; hypre_ParAMGDataCommInfo(amg_data) = comm_info; hypre_ParAMGDataNewComm(amg_data) = new_comm; hypre_TFree(mat_info, HYPRE_MEMORY_HOST); hypre_TFree(mat_displs, HYPRE_MEMORY_HOST); hypre_TFree(A_mat_local, HYPRE_MEMORY_HOST); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_GS_ELIM_SETUP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } HYPRE_Int hypre_GaussElimSolve (hypre_ParAMGData *amg_data, HYPRE_Int level, HYPRE_Int relax_type) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_GS_ELIM_SOLVE] -= hypre_MPI_Wtime(); #endif hypre_ParCSRMatrix *A = hypre_ParAMGDataAArray(amg_data)[level]; HYPRE_Int n = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); HYPRE_Int error_flag = 0; if (n) { MPI_Comm new_comm = hypre_ParAMGDataNewComm(amg_data); hypre_ParVector *f = hypre_ParAMGDataFArray(amg_data)[level]; hypre_ParVector *u = hypre_ParAMGDataUArray(amg_data)[level]; HYPRE_Real *A_mat = hypre_ParAMGDataAMat(amg_data); HYPRE_Real *b_vec = hypre_ParAMGDataBVec(amg_data); HYPRE_Real *f_data = hypre_VectorData(hypre_ParVectorLocalVector(f)); HYPRE_Real *u_data = hypre_VectorData(hypre_ParVectorLocalVector(u)); HYPRE_Real *A_tmp; HYPRE_Int *comm_info = hypre_ParAMGDataCommInfo(amg_data); HYPRE_Int *displs, *info; HYPRE_Int n_global = (HYPRE_Int) hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int new_num_procs, i, my_info; HYPRE_Int first_index = (HYPRE_Int) hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int one_i = 1; hypre_MPI_Comm_size(new_comm, &new_num_procs); info = &comm_info[0]; displs = &comm_info[new_num_procs]; hypre_MPI_Allgatherv ( f_data, n, HYPRE_MPI_REAL, b_vec, info, displs, HYPRE_MPI_REAL, new_comm ); A_tmp = hypre_CTAlloc(HYPRE_Real, n_global*n_global, HYPRE_MEMORY_HOST); for (i=0; i < n_global*n_global; i++) A_tmp[i] = A_mat[i]; if (relax_type == 9) { hypre_gselim(A_tmp,b_vec,n_global,error_flag); } else if (relax_type == 99) /* use pivoting */ { HYPRE_Int *piv; piv = hypre_CTAlloc(HYPRE_Int, n_global, HYPRE_MEMORY_HOST); /* write over A with LU */ hypre_dgetrf(&n_global, &n_global, A_tmp, &n_global, piv, &my_info); /*now b_vec = inv(A)*b_vec */ hypre_dgetrs("N", &n_global, &one_i, A_tmp, &n_global, piv, b_vec, &n_global, &my_info); hypre_TFree(piv, HYPRE_MEMORY_HOST); } for (i = 0; i < n; i++) { u_data[i] = b_vec[first_index+i]; } hypre_TFree(A_tmp, HYPRE_MEMORY_HOST); } if (error_flag) hypre_error(HYPRE_ERROR_GENERIC); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_GS_ELIM_SOLVE] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } #if 0 HYPRE_Int gselim(HYPRE_Real *A, HYPRE_Real *x, HYPRE_Int n) { HYPRE_Int err_flag = 0; HYPRE_Int j,k,m; HYPRE_Real factor; HYPRE_Real divA; if (n==1) /* A is 1x1 */ { if (A[0] != 0.0) { x[0] = x[0]/A[0]; return(err_flag); } else { err_flag = 1; return(err_flag); } } else /* A is nxn. Forward elimination */ { for (k = 0; k < n-1; k++) { if (A[k*n+k] != 0.0) { divA = 1.0/A[k*n+k]; for (j = k+1; j < n; j++) { if (A[j*n+k] != 0.0) { factor = A[j*n+k]*divA; for (m = k+1; m < n; m++) { A[j*n+m] -= factor * A[k*n+m]; } /* Elimination step for rhs */ x[j] -= factor * x[k]; } } } } /* Back Substitution */ for (k = n-1; k > 0; --k) { if (A[k*n+k] != 0.0) { x[k] /= A[k*n+k]; for (j = 0; j < k; j++) { if (A[j*n+k] != 0.0) { x[j] -= x[k] * A[j*n+k]; } } } } if (A[0] != 0.0) x[0] /= A[0]; return(err_flag); } } #endif
par_csr_matop_device.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "_hypre_utilities.h" #include "_hypre_parcsr_mv.h" #include "_hypre_utilities.hpp" #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) HYPRE_Int hypre_ParcsrGetExternalRowsDeviceInit( hypre_ParCSRMatrix *A, HYPRE_Int indices_len, HYPRE_BigInt *indices, hypre_ParCSRCommPkg *comm_pkg, HYPRE_Int want_data, void **request_ptr) { HYPRE_Int i, j; HYPRE_Int num_sends, num_rows_send, num_nnz_send, num_recvs, num_rows_recv, num_nnz_recv; HYPRE_Int *d_send_i, *send_i, *d_send_map, *d_recv_i, *recv_i; HYPRE_BigInt *d_send_j, *d_recv_j; HYPRE_Int *send_jstarts, *recv_jstarts; HYPRE_Complex *d_send_a = NULL, *d_recv_a = NULL; hypre_ParCSRCommPkg *comm_pkg_j; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; /* HYPRE_Int global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); */ /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* HYPRE_Int local_num_rows = hypre_CSRMatrixNumRows(A_diag); */ /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /* HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); */ /* HYPRE_Int first_row = hypre_ParCSRMatrixFirstRowIndex(A); */ HYPRE_Int first_col = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *d_col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A); MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Int num_procs; HYPRE_Int my_id; void **vrequest; hypre_CSRMatrix *A_ext; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); /* number of sends (#procs) */ num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); /* number of rows to send */ num_rows_send = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); /* number of recvs (#procs) */ num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); /* number of rows to recv */ num_rows_recv = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs); /* must be true if indices contains proper offd indices */ hypre_assert(indices_len == num_rows_recv); /* send_i/recv_i: * the arrays to send and recv: we first send and recv the row lengths */ d_send_i = hypre_TAlloc(HYPRE_Int, num_rows_send + 1, HYPRE_MEMORY_DEVICE); d_send_map = hypre_TAlloc(HYPRE_Int, num_rows_send, HYPRE_MEMORY_DEVICE); send_i = hypre_TAlloc(HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST); recv_i = hypre_TAlloc(HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_HOST); d_recv_i = hypre_TAlloc(HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_DEVICE); /* fill the send array with row lengths */ hypre_TMemcpy(d_send_map, hypre_ParCSRCommPkgSendMapElmts(comm_pkg), HYPRE_Int, num_rows_send, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_Memset(d_send_i, 0, sizeof(HYPRE_Int), HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(num_rows_send, d_send_map, A_diag_i, A_offd_i, d_send_i+1); /* send array send_i out: deviceTohost first and MPI (async) * note the shift in recv_i by one */ hypre_TMemcpy(send_i, d_send_i+1, HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, send_i, recv_i+1); hypreDevice_IntegerInclusiveScan(num_rows_send + 1, d_send_i); /* total number of nnz to send */ hypre_TMemcpy(&num_nnz_send, d_send_i+num_rows_send, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); /* prepare data to send out. overlap with the above commmunication */ d_send_j = hypre_TAlloc(HYPRE_BigInt, num_nnz_send, HYPRE_MEMORY_DEVICE); if (want_data) { d_send_a = hypre_TAlloc(HYPRE_Complex, num_nnz_send, HYPRE_MEMORY_DEVICE); } if (d_col_map_offd_A == NULL) { d_col_map_offd_A = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(d_col_map_offd_A, col_map_offd_A, HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDeviceColMapOffd(A) = d_col_map_offd_A; } /* job == 2, d_send_i is input that contains row ptrs (length num_rows_send) */ hypreDevice_CopyParCSRRows(num_rows_send, d_send_map, 2, num_procs > 1, first_col, d_col_map_offd_A, A_diag_i, A_diag_j, A_diag_a, A_offd_i, A_offd_j, A_offd_a, d_send_i, d_send_j, d_send_a); /* pointers to each proc in send_j */ send_jstarts = hypre_TAlloc(HYPRE_Int, num_sends + 1, HYPRE_MEMORY_HOST); send_jstarts[0] = 0; for (i = 1; i <= num_sends; i++) { send_jstarts[i] = send_jstarts[i-1]; for ( j = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i-1); j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); j++ ) { send_jstarts[i] += send_i[j]; } } hypre_assert(send_jstarts[num_sends] == num_nnz_send); /* finish the above communication: send_i/recv_i */ hypre_ParCSRCommHandleDestroy(comm_handle); /* adjust recv_i to ptrs */ recv_i[0] = 0; for (i = 1; i <= num_rows_recv; i++) { recv_i[i] += recv_i[i-1]; } num_nnz_recv = recv_i[num_rows_recv]; /* allocate device memory for j and a */ d_recv_j = hypre_TAlloc(HYPRE_BigInt, num_nnz_recv, HYPRE_MEMORY_DEVICE); if (want_data) { d_recv_a = hypre_TAlloc(HYPRE_Complex, num_nnz_recv, HYPRE_MEMORY_DEVICE); } recv_jstarts = hypre_TAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); recv_jstarts[0] = 0; for (i = 1; i <= num_recvs; i++) { j = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i); recv_jstarts[i] = recv_i[j]; } /* ready to send and recv: create a communication package for data */ comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm (comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends (comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs (comm_pkg_j) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = send_jstarts; hypre_ParCSRCommPkgNumRecvs (comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgRecvProcs (comm_pkg_j) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = recv_jstarts; /* init communication */ /* ja */ comm_handle_j = hypre_ParCSRCommHandleCreate_v2(21, comm_pkg_j, HYPRE_MEMORY_DEVICE, d_send_j, HYPRE_MEMORY_DEVICE, d_recv_j); if (want_data) { /* a */ comm_handle_a = hypre_ParCSRCommHandleCreate_v2(1, comm_pkg_j, HYPRE_MEMORY_DEVICE, d_send_a, HYPRE_MEMORY_DEVICE, d_recv_a); } else { comm_handle_a = NULL; } hypre_TMemcpy(d_recv_i, recv_i, HYPRE_Int, num_rows_recv+1, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); /* create A_ext: on device */ A_ext = hypre_CSRMatrixCreate(num_rows_recv, hypre_ParCSRMatrixGlobalNumCols(A), num_nnz_recv); hypre_CSRMatrixI (A_ext) = d_recv_i; hypre_CSRMatrixBigJ(A_ext) = d_recv_j; hypre_CSRMatrixData(A_ext) = d_recv_a; hypre_CSRMatrixMemoryLocation(A_ext) = HYPRE_MEMORY_DEVICE; /* output */ vrequest = hypre_TAlloc(void *, 3, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) A_ext; *request_ptr = (void *) vrequest; /* free */ hypre_TFree(send_i, HYPRE_MEMORY_HOST); hypre_TFree(recv_i, HYPRE_MEMORY_HOST); hypre_TFree(d_send_i, HYPRE_MEMORY_DEVICE); hypre_TFree(d_send_map, HYPRE_MEMORY_DEVICE); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); return hypre_error_flag; } hypre_CSRMatrix* hypre_ParcsrGetExternalRowsDeviceWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *A_ext = (hypre_CSRMatrix *) request[2]; HYPRE_BigInt *send_j = comm_handle_j ? (HYPRE_BigInt *) hypre_ParCSRCommHandleSendData(comm_handle_j) : NULL; HYPRE_Complex *send_a = comm_handle_a ? (HYPRE_Complex *) hypre_ParCSRCommHandleSendData(comm_handle_a) : NULL; hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_TFree(send_j, HYPRE_MEMORY_DEVICE); hypre_TFree(send_a, HYPRE_MEMORY_DEVICE); hypre_TFree(request, HYPRE_MEMORY_HOST); return A_ext; } hypre_CSRMatrix* hypre_MergeDiagAndOffdDevice(hypre_ParCSRMatrix *A) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int local_num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt glbal_num_cols = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_BigInt first_col = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_BigInt *d_col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A); hypre_CSRMatrix *B; HYPRE_Int B_nrows = local_num_rows; HYPRE_BigInt B_ncols = glbal_num_cols; HYPRE_Int *B_i = hypre_TAlloc(HYPRE_Int, B_nrows + 1, HYPRE_MEMORY_DEVICE); HYPRE_BigInt *B_j; HYPRE_Complex *B_a; HYPRE_Int B_nnz; HYPRE_Int num_procs; hypre_MPI_Comm_size(comm, &num_procs); hypre_Memset(B_i, 0, sizeof(HYPRE_Int), HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(B_nrows, NULL, A_diag_i, A_offd_i, B_i+1); hypreDevice_IntegerInclusiveScan(B_nrows+1, B_i); /* total number of nnz */ hypre_TMemcpy(&B_nnz, B_i+B_nrows, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); B_j = hypre_TAlloc(HYPRE_BigInt, B_nnz, HYPRE_MEMORY_DEVICE); B_a = hypre_TAlloc(HYPRE_Complex, B_nnz, HYPRE_MEMORY_DEVICE); if (d_col_map_offd_A == NULL) { d_col_map_offd_A = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(d_col_map_offd_A, col_map_offd_A, HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDeviceColMapOffd(A) = d_col_map_offd_A; } hypreDevice_CopyParCSRRows(B_nrows, NULL, 2, num_procs > 1, first_col, d_col_map_offd_A, A_diag_i, A_diag_j, A_diag_a, A_offd_i, A_offd_j, A_offd_a, B_i, B_j, B_a); /* output */ B = hypre_CSRMatrixCreate(B_nrows, B_ncols, B_nnz); hypre_CSRMatrixI (B) = B_i; hypre_CSRMatrixBigJ(B) = B_j; hypre_CSRMatrixData(B) = B_a; hypre_CSRMatrixMemoryLocation(B) = HYPRE_MEMORY_DEVICE; hypre_SyncCudaComputeStream(hypre_handle()); return B; } HYPRE_Int hypre_ExchangeExternalRowsDeviceInit( hypre_CSRMatrix *B_ext, hypre_ParCSRCommPkg *comm_pkg_A, HYPRE_Int want_data, void **request_ptr) { MPI_Comm comm = hypre_ParCSRCommPkgComm(comm_pkg_A); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A); HYPRE_Int *recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A); HYPRE_Int *recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A); HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg_A); HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg_A); HYPRE_Int *send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); HYPRE_Int num_elmts_send = send_map_starts[num_sends]; HYPRE_Int num_elmts_recv = recv_vec_starts[num_recvs]; HYPRE_Int *B_ext_i_d = hypre_CSRMatrixI(B_ext); HYPRE_BigInt *B_ext_j_d = hypre_CSRMatrixBigJ(B_ext); HYPRE_Complex *B_ext_a_d = hypre_CSRMatrixData(B_ext); HYPRE_Int B_ext_ncols = hypre_CSRMatrixNumCols(B_ext); HYPRE_Int B_ext_nrows = hypre_CSRMatrixNumRows(B_ext); HYPRE_Int B_ext_nnz = hypre_CSRMatrixNumNonzeros(B_ext); HYPRE_Int *B_ext_rownnz_d = hypre_TAlloc(HYPRE_Int, B_ext_nrows + 1, HYPRE_MEMORY_DEVICE); HYPRE_Int *B_ext_rownnz_h = hypre_TAlloc(HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST); HYPRE_Int *B_ext_i_h = hypre_TAlloc(HYPRE_Int, B_ext_nrows + 1, HYPRE_MEMORY_HOST); hypre_assert(num_elmts_recv == B_ext_nrows); /* output matrix */ hypre_CSRMatrix *B_int_d; HYPRE_Int B_int_nrows = num_elmts_send; HYPRE_Int B_int_ncols = B_ext_ncols; HYPRE_Int *B_int_i_h = hypre_TAlloc(HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_HOST); HYPRE_Int *B_int_i_d = hypre_TAlloc(HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_DEVICE); HYPRE_BigInt *B_int_j_d = NULL; HYPRE_Complex *B_int_a_d = NULL; HYPRE_Int B_int_nnz; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; hypre_ParCSRCommPkg *comm_pkg_j; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int i; HYPRE_Int num_procs, my_id; void **vrequest; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); jdata_send_map_starts = hypre_TAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); /*-------------------------------------------------------------------------- * B_ext_rownnz contains the number of elements of row j * (to be determined through send_map_elmnts on the receiving end) *--------------------------------------------------------------------------*/ HYPRE_THRUST_CALL(adjacent_difference, B_ext_i_d, B_ext_i_d + B_ext_nrows + 1, B_ext_rownnz_d); hypre_TMemcpy(B_ext_rownnz_h, B_ext_rownnz_d + 1, HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); /*-------------------------------------------------------------------------- * initialize communication: send/recv the row nnz * (note the use of comm_pkg_A, mode 12, as in transpose matvec *--------------------------------------------------------------------------*/ comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg_A, B_ext_rownnz_h, B_int_i_h + 1); jdata_recv_vec_starts = hypre_TAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); jdata_recv_vec_starts[0] = 0; B_ext_i_h[0] = 0; hypre_TMemcpy(B_ext_i_h + 1, B_ext_rownnz_h, HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); for (i = 1; i <= B_ext_nrows; i++) { B_ext_i_h[i] += B_ext_i_h[i-1]; } hypre_assert(B_ext_i_h[B_ext_nrows] == B_ext_nnz); for (i = 1; i <= num_recvs; i++) { jdata_recv_vec_starts[i] = B_ext_i_h[recv_vec_starts[i]]; } comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends(comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgNumRecvs(comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs(comm_pkg_j) = recv_procs; hypre_ParCSRCommPkgRecvProcs(comm_pkg_j) = send_procs; hypre_ParCSRCommHandleDestroy(comm_handle); /*-------------------------------------------------------------------------- * compute B_int: row nnz to row ptrs *--------------------------------------------------------------------------*/ B_int_i_h[0] = 0; for (i = 1; i <= B_int_nrows; i++) { B_int_i_h[i] += B_int_i_h[i-1]; } B_int_nnz = B_int_i_h[B_int_nrows]; B_int_j_d = hypre_TAlloc(HYPRE_BigInt, B_int_nnz, HYPRE_MEMORY_DEVICE); if (want_data) { B_int_a_d = hypre_TAlloc(HYPRE_Complex, B_int_nnz, HYPRE_MEMORY_DEVICE); } for (i = 0; i <= num_sends; i++) { jdata_send_map_starts[i] = B_int_i_h[send_map_starts[i]]; } /* note the order of send/recv is reversed */ hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = jdata_send_map_starts; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = jdata_recv_vec_starts; /* send/recv CSR rows */ if (want_data) { comm_handle_a = hypre_ParCSRCommHandleCreate_v2( 1, comm_pkg_j, HYPRE_MEMORY_DEVICE, B_ext_a_d, HYPRE_MEMORY_DEVICE, B_int_a_d ); } else { comm_handle_a = NULL; } comm_handle_j = hypre_ParCSRCommHandleCreate_v2(21, comm_pkg_j, HYPRE_MEMORY_DEVICE, B_ext_j_d, HYPRE_MEMORY_DEVICE, B_int_j_d ); hypre_TMemcpy(B_int_i_d, B_int_i_h, HYPRE_Int, B_int_nrows+1, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); /* create CSR: on device */ B_int_d = hypre_CSRMatrixCreate(B_int_nrows, B_int_ncols, B_int_nnz); hypre_CSRMatrixI(B_int_d) = B_int_i_d; hypre_CSRMatrixBigJ(B_int_d) = B_int_j_d; hypre_CSRMatrixData(B_int_d) = B_int_a_d; hypre_CSRMatrixMemoryLocation(B_int_d) = HYPRE_MEMORY_DEVICE; /* output */ vrequest = hypre_TAlloc(void *, 3, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) B_int_d; *request_ptr = (void *) vrequest; /* free */ hypre_TFree(B_ext_rownnz_d, HYPRE_MEMORY_DEVICE); hypre_TFree(B_ext_rownnz_h, HYPRE_MEMORY_HOST); hypre_TFree(B_ext_i_h, HYPRE_MEMORY_HOST); hypre_TFree(B_int_i_h, HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); return hypre_error_flag; } hypre_CSRMatrix* hypre_ExchangeExternalRowsDeviceWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *B_int_d = (hypre_CSRMatrix *) request[2]; /* communication done */ hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_TFree(request, HYPRE_MEMORY_HOST); return B_int_d; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ HYPRE_Int hypre_ParCSRMatrixExtractBExtDeviceInit( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int want_data, void **request_ptr) { hypre_assert( hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B)) == hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixOffd(B)) ); /* hypre_assert( hypre_GetActualMemLocation( hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B))) == HYPRE_MEMORY_DEVICE ); */ if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } hypre_ParcsrGetExternalRowsDeviceInit(B, hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A)), hypre_ParCSRMatrixColMapOffd(A), hypre_ParCSRMatrixCommPkg(A), want_data, request_ptr); return hypre_error_flag; } hypre_CSRMatrix* hypre_ParCSRMatrixExtractBExtDeviceWait(void *request) { return hypre_ParcsrGetExternalRowsDeviceWait(request); } hypre_CSRMatrix* hypre_ParCSRMatrixExtractBExtDevice( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int want_data ) { void *request; hypre_ParCSRMatrixExtractBExtDeviceInit(B, A, want_data, &request); return hypre_ParCSRMatrixExtractBExtDeviceWait(request); } /* return B = [Adiag, Aoffd] */ #if 1 __global__ void hypreCUDAKernel_ConcatDiagAndOffd(HYPRE_Int nrows, HYPRE_Int diag_ncol, HYPRE_Int *d_diag_i, HYPRE_Int *d_diag_j, HYPRE_Complex *d_diag_a, HYPRE_Int *d_offd_i, HYPRE_Int *d_offd_j, HYPRE_Complex *d_offd_a, HYPRE_Int *cols_offd_map, HYPRE_Int *d_ib, HYPRE_Int *d_jb, HYPRE_Complex *d_ab) { const HYPRE_Int row = hypre_cuda_get_grid_warp_id<1,1>(); if (row >= nrows) { return; } /* lane id inside the warp */ const HYPRE_Int lane_id = hypre_cuda_get_lane_id<1>(); HYPRE_Int i, j, k, p, istart, iend, bstart; /* diag part */ if (lane_id < 2) { j = read_only_load(d_diag_i + row + lane_id); } if (lane_id == 0) { k = read_only_load(d_ib + row); } istart = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 0); iend = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 1); bstart = __shfl_sync(HYPRE_WARP_FULL_MASK, k, 0); p = bstart - istart; for (i = istart + lane_id; i < iend; i += HYPRE_WARP_SIZE) { d_jb[p+i] = read_only_load(d_diag_j + i); d_ab[p+i] = read_only_load(d_diag_a + i); } /* offd part */ if (lane_id < 2) { j = read_only_load(d_offd_i + row + lane_id); } bstart += iend - istart; istart = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 0); iend = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 1); p = bstart - istart; for (i = istart + lane_id; i < iend; i += HYPRE_WARP_SIZE) { const HYPRE_Int t = read_only_load(d_offd_j + i); d_jb[p+i] = (cols_offd_map ? read_only_load(&cols_offd_map[t]) : t) + diag_ncol; d_ab[p+i] = read_only_load(d_offd_a + i); } } hypre_CSRMatrix* hypre_ConcatDiagAndOffdDevice(hypre_ParCSRMatrix *A) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *B = hypre_CSRMatrixCreate( hypre_CSRMatrixNumRows(A_diag), hypre_CSRMatrixNumCols(A_diag) + hypre_CSRMatrixNumCols(A_offd), hypre_CSRMatrixNumNonzeros(A_diag) + hypre_CSRMatrixNumNonzeros(A_offd) ); hypre_CSRMatrixInitialize_v2(B, 0, HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(hypre_CSRMatrixNumRows(B), NULL, hypre_CSRMatrixI(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixI(B)); HYPRE_THRUST_CALL( exclusive_scan, hypre_CSRMatrixI(B), hypre_CSRMatrixI(B) + hypre_CSRMatrixNumRows(B) + 1, hypre_CSRMatrixI(B) ); const dim3 bDim = hypre_GetDefaultCUDABlockDimension(); const dim3 gDim = hypre_GetDefaultCUDAGridDimension(hypre_CSRMatrixNumRows(A_diag), "warp", bDim); HYPRE_CUDA_LAUNCH( hypreCUDAKernel_ConcatDiagAndOffd, gDim, bDim, hypre_CSRMatrixNumRows(A_diag), hypre_CSRMatrixNumCols(A_diag), hypre_CSRMatrixI(A_diag), hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixJ(A_offd), hypre_CSRMatrixData(A_offd), NULL, hypre_CSRMatrixI(B), hypre_CSRMatrixJ(B), hypre_CSRMatrixData(B) ); return B; } #else hypre_CSRMatrix* hypre_ConcatDiagAndOffdDevice(hypre_ParCSRMatrix *A) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int A_diag_nnz = hypre_CSRMatrixNumNonzeros(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int A_offd_nnz = hypre_CSRMatrixNumNonzeros(A_offd); hypre_CSRMatrix *B; HYPRE_Int B_nrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int B_ncols = hypre_CSRMatrixNumCols(A_diag) + hypre_CSRMatrixNumCols(A_offd); HYPRE_Int B_nnz = A_diag_nnz + A_offd_nnz; HYPRE_Int *B_ii = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE); HYPRE_Int *B_j = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE); HYPRE_Complex *B_a = hypre_TAlloc(HYPRE_Complex, B_nnz, HYPRE_MEMORY_DEVICE); // Adiag HYPRE_Int *A_diag_ii = hypreDevice_CsrRowPtrsToIndices(B_nrows, A_diag_nnz, A_diag_i); HYPRE_THRUST_CALL( copy_n, thrust::make_zip_iterator(thrust::make_tuple(A_diag_ii, A_diag_j, A_diag_a)), A_diag_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_j, B_a)) ); hypre_TFree(A_diag_ii, HYPRE_MEMORY_DEVICE); // Aoffd HYPRE_Int *A_offd_ii = hypreDevice_CsrRowPtrsToIndices(B_nrows, A_offd_nnz, A_offd_i); HYPRE_THRUST_CALL( copy_n, thrust::make_zip_iterator(thrust::make_tuple(A_offd_ii, A_offd_a)), A_offd_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_a)) + A_diag_nnz ); hypre_TFree(A_offd_ii, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, A_offd_j, A_offd_j + A_offd_nnz, thrust::make_constant_iterator(hypre_CSRMatrixNumCols(A_diag)), B_j + A_diag_nnz, thrust::plus<HYPRE_Int>() ); // B HYPRE_THRUST_CALL( stable_sort_by_key, B_ii, B_ii + B_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_j, B_a)) ); HYPRE_Int *B_i = hypreDevice_CsrRowIndicesToPtrs(B_nrows, B_nnz, B_ii); hypre_TFree(B_ii, HYPRE_MEMORY_DEVICE); B = hypre_CSRMatrixCreate(B_nrows, B_ncols, B_nnz); hypre_CSRMatrixI(B) = B_i; hypre_CSRMatrixJ(B) = B_j; hypre_CSRMatrixData(B) = B_a; hypre_CSRMatrixMemoryLocation(B) = HYPRE_MEMORY_DEVICE; return B; } #endif /* return B = [Adiag, Aoffd; E] */ #if 1 HYPRE_Int hypre_ConcatDiagOffdAndExtDevice(hypre_ParCSRMatrix *A, hypre_CSRMatrix *E, hypre_CSRMatrix **B_ptr, HYPRE_Int *num_cols_offd_ptr, HYPRE_BigInt **cols_map_offd_ptr) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *E_diag, *E_offd, *B; HYPRE_Int *cols_offd_map, num_cols_offd; HYPRE_BigInt *cols_map_offd; hypre_CSRMatrixSplitDevice(E, hypre_ParCSRMatrixFirstColDiag(A), hypre_ParCSRMatrixLastColDiag(A), hypre_CSRMatrixNumCols(A_offd), hypre_ParCSRMatrixDeviceColMapOffd(A), &cols_offd_map, &num_cols_offd, &cols_map_offd, &E_diag, &E_offd); B = hypre_CSRMatrixCreate(hypre_ParCSRMatrixNumRows(A) + hypre_CSRMatrixNumRows(E), hypre_ParCSRMatrixNumCols(A) + num_cols_offd, hypre_CSRMatrixNumNonzeros(A_diag) + hypre_CSRMatrixNumNonzeros(A_offd) + hypre_CSRMatrixNumNonzeros(E)); hypre_CSRMatrixInitialize_v2(B, 0, HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(hypre_ParCSRMatrixNumRows(A), NULL, hypre_CSRMatrixI(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixI(B)); HYPRE_THRUST_CALL( exclusive_scan, hypre_CSRMatrixI(B), hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1, hypre_CSRMatrixI(B) ); dim3 bDim = hypre_GetDefaultCUDABlockDimension(); dim3 gDim = hypre_GetDefaultCUDAGridDimension(hypre_ParCSRMatrixNumRows(A), "warp", bDim); HYPRE_CUDA_LAUNCH( hypreCUDAKernel_ConcatDiagAndOffd, gDim, bDim, hypre_CSRMatrixNumRows(A_diag), hypre_CSRMatrixNumCols(A_diag), hypre_CSRMatrixI(A_diag), hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixJ(A_offd), hypre_CSRMatrixData(A_offd), cols_offd_map, hypre_CSRMatrixI(B), hypre_CSRMatrixJ(B), hypre_CSRMatrixData(B) ); hypre_TFree(cols_offd_map, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1, hypre_CSRMatrixI(E) + 1, HYPRE_Int, hypre_CSRMatrixNumRows(E), HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1, hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + hypre_CSRMatrixNumRows(E) + 1, thrust::make_constant_iterator(hypre_CSRMatrixNumNonzeros(A_diag) + hypre_CSRMatrixNumNonzeros(A_offd)), hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1, thrust::plus<HYPRE_Int>() ); gDim = hypre_GetDefaultCUDAGridDimension(hypre_CSRMatrixNumRows(E), "warp", bDim); hypre_assert(hypre_CSRMatrixNumCols(E_diag) == hypre_CSRMatrixNumCols(A_diag)); HYPRE_CUDA_LAUNCH( hypreCUDAKernel_ConcatDiagAndOffd, gDim, bDim, hypre_CSRMatrixNumRows(E_diag), hypre_CSRMatrixNumCols(E_diag), hypre_CSRMatrixI(E_diag), hypre_CSRMatrixJ(E_diag), hypre_CSRMatrixData(E_diag), hypre_CSRMatrixI(E_offd), hypre_CSRMatrixJ(E_offd), hypre_CSRMatrixData(E_offd), NULL, hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A), hypre_CSRMatrixJ(B), hypre_CSRMatrixData(B) ); hypre_CSRMatrixDestroy(E_diag); hypre_CSRMatrixDestroy(E_offd); *B_ptr = B; *num_cols_offd_ptr = num_cols_offd; *cols_map_offd_ptr = cols_map_offd; return hypre_error_flag; } #else HYPRE_Int hypre_ConcatDiagOffdAndExtDevice(hypre_ParCSRMatrix *A, hypre_CSRMatrix *E, hypre_CSRMatrix **B_ptr, HYPRE_Int *num_cols_offd_ptr, HYPRE_BigInt **cols_map_offd_ptr) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int A_nrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int A_ncols = hypre_CSRMatrixNumCols(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int A_diag_nnz = hypre_CSRMatrixNumNonzeros(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int A_offd_nnz = hypre_CSRMatrixNumNonzeros(A_offd); HYPRE_BigInt first_col_A = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_BigInt last_col_A = hypre_ParCSRMatrixLastColDiag(A); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A); HYPRE_Int *E_i = hypre_CSRMatrixI(E); HYPRE_BigInt *E_bigj = hypre_CSRMatrixBigJ(E); HYPRE_Complex *E_a = hypre_CSRMatrixData(E); HYPRE_Int E_nrows = hypre_CSRMatrixNumRows(E); HYPRE_Int E_nnz = hypre_CSRMatrixNumNonzeros(E); HYPRE_Int E_diag_nnz, E_offd_nnz; hypre_CSRMatrix *B; HYPRE_Int B_nnz = A_diag_nnz + A_offd_nnz + E_nnz; HYPRE_Int *B_ii = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE); HYPRE_Int *B_j = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE); HYPRE_Complex *B_a = hypre_TAlloc(HYPRE_Complex, B_nnz, HYPRE_MEMORY_DEVICE); // E hypre_CSRMatrixSplitDevice_core(0, E_nrows, E_nnz, NULL, E_bigj, NULL, NULL, first_col_A, last_col_A, num_cols_offd_A, NULL, NULL, NULL, NULL, &E_diag_nnz, NULL, NULL, NULL, NULL, &E_offd_nnz, NULL, NULL, NULL, NULL); HYPRE_Int *cols_offd_map, num_cols_offd; HYPRE_BigInt *cols_map_offd; HYPRE_Int *E_ii = hypreDevice_CsrRowPtrsToIndices(E_nrows, E_nnz, E_i); hypre_CSRMatrixSplitDevice_core(1, E_nrows, E_nnz, E_ii, E_bigj, E_a, NULL, first_col_A, last_col_A, num_cols_offd_A, col_map_offd_A, &cols_offd_map, &num_cols_offd, &cols_map_offd, &E_diag_nnz, B_ii + A_diag_nnz + A_offd_nnz, B_j + A_diag_nnz + A_offd_nnz, B_a + A_diag_nnz + A_offd_nnz, NULL, &E_offd_nnz, B_ii + A_diag_nnz + A_offd_nnz + E_diag_nnz, B_j + A_diag_nnz + A_offd_nnz + E_diag_nnz, B_a + A_diag_nnz + A_offd_nnz + E_diag_nnz, NULL); hypre_TFree(E_ii, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, B_ii + A_diag_nnz + A_offd_nnz, B_ii + B_nnz, thrust::make_constant_iterator(A_nrows), B_ii + A_diag_nnz + A_offd_nnz, thrust::plus<HYPRE_Int>() ); // Adiag HYPRE_Int *A_diag_ii = hypreDevice_CsrRowPtrsToIndices(A_nrows, A_diag_nnz, A_diag_i); HYPRE_THRUST_CALL( copy_n, thrust::make_zip_iterator(thrust::make_tuple(A_diag_ii, A_diag_j, A_diag_a)), A_diag_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_j, B_a)) ); hypre_TFree(A_diag_ii, HYPRE_MEMORY_DEVICE); // Aoffd HYPRE_Int *A_offd_ii = hypreDevice_CsrRowPtrsToIndices(A_nrows, A_offd_nnz, A_offd_i); HYPRE_THRUST_CALL( copy_n, thrust::make_zip_iterator(thrust::make_tuple(A_offd_ii, A_offd_a)), A_offd_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_a)) + A_diag_nnz ); hypre_TFree(A_offd_ii, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( gather, A_offd_j, A_offd_j + A_offd_nnz, cols_offd_map, B_j + A_diag_nnz); hypre_TFree(cols_offd_map, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, B_j + A_diag_nnz, B_j + A_diag_nnz + A_offd_nnz, thrust::make_constant_iterator(A_ncols), B_j + A_diag_nnz, thrust::plus<HYPRE_Int>() ); HYPRE_THRUST_CALL( transform, B_j + A_diag_nnz + A_offd_nnz + E_diag_nnz, B_j + B_nnz, thrust::make_constant_iterator(A_ncols), B_j + A_diag_nnz + A_offd_nnz + E_diag_nnz, thrust::plus<HYPRE_Int>() ); // B HYPRE_THRUST_CALL( stable_sort_by_key, B_ii, B_ii + B_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_j, B_a)) ); HYPRE_Int *B_i = hypreDevice_CsrRowIndicesToPtrs(A_nrows + E_nrows, B_nnz, B_ii); hypre_TFree(B_ii, HYPRE_MEMORY_DEVICE); B = hypre_CSRMatrixCreate(A_nrows + E_nrows, A_ncols + num_cols_offd, B_nnz); hypre_CSRMatrixI(B) = B_i; hypre_CSRMatrixJ(B) = B_j; hypre_CSRMatrixData(B) = B_a; hypre_CSRMatrixMemoryLocation(B) = HYPRE_MEMORY_DEVICE; *B_ptr = B; *num_cols_offd_ptr = num_cols_offd; *cols_map_offd_ptr = cols_map_offd; return hypre_error_flag; } #endif HYPRE_Int hypre_ParCSRMatrixGetRowDevice( hypre_ParCSRMatrix *mat, HYPRE_BigInt row, HYPRE_Int *size, HYPRE_BigInt **col_ind, HYPRE_Complex **values ) { HYPRE_Int nrows, local_row; HYPRE_BigInt row_start, row_end; hypre_CSRMatrix *Aa; hypre_CSRMatrix *Ba; if (!mat) { hypre_error_in_arg(1); return hypre_error_flag; } Aa = (hypre_CSRMatrix *) hypre_ParCSRMatrixDiag(mat); Ba = (hypre_CSRMatrix *) hypre_ParCSRMatrixOffd(mat); if (hypre_ParCSRMatrixGetrowactive(mat)) { return(-1); } hypre_ParCSRMatrixGetrowactive(mat) = 1; row_start = hypre_ParCSRMatrixFirstRowIndex(mat); row_end = hypre_ParCSRMatrixLastRowIndex(mat) + 1; nrows = row_end - row_start; if (row < row_start || row >= row_end) { return(-1); } local_row = row - row_start; /* if buffer is not allocated and some information is requested, allocate buffer with the max row_nnz */ if ( !hypre_ParCSRMatrixRowvalues(mat) && (col_ind || values) ) { HYPRE_Int max_row_nnz; HYPRE_Int *row_nnz = hypre_TAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(nrows, NULL, hypre_CSRMatrixI(Aa), hypre_CSRMatrixI(Ba), row_nnz); hypre_TMemcpy(size, row_nnz + local_row, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); max_row_nnz = HYPRE_THRUST_CALL(reduce, row_nnz, row_nnz + nrows, 0, thrust::maximum<HYPRE_Int>()); /* HYPRE_Int *max_row_nnz_d = HYPRE_THRUST_CALL(max_element, row_nnz, row_nnz + nrows); hypre_TMemcpy( &max_row_nnz, max_row_nnz_d, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE ); */ hypre_TFree(row_nnz, HYPRE_MEMORY_DEVICE); hypre_ParCSRMatrixRowvalues(mat) = (HYPRE_Complex *) hypre_TAlloc(HYPRE_Complex, max_row_nnz, hypre_ParCSRMatrixMemoryLocation(mat)); hypre_ParCSRMatrixRowindices(mat) = (HYPRE_BigInt *) hypre_TAlloc(HYPRE_BigInt, max_row_nnz, hypre_ParCSRMatrixMemoryLocation(mat)); } else { HYPRE_Int *size_d = hypre_TAlloc(HYPRE_Int, 1, HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(1, NULL, hypre_CSRMatrixI(Aa) + local_row, hypre_CSRMatrixI(Ba) + local_row, size_d); hypre_TMemcpy(size, size_d, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); hypre_TFree(size_d, HYPRE_MEMORY_DEVICE); } if (col_ind || values) { if (hypre_ParCSRMatrixDeviceColMapOffd(mat) == NULL) { hypre_ParCSRMatrixDeviceColMapOffd(mat) = hypre_TAlloc(HYPRE_BigInt, hypre_CSRMatrixNumCols(Ba), HYPRE_MEMORY_DEVICE); hypre_TMemcpy( hypre_ParCSRMatrixDeviceColMapOffd(mat), hypre_ParCSRMatrixColMapOffd(mat), HYPRE_BigInt, hypre_CSRMatrixNumCols(Ba), HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST ); } hypreDevice_CopyParCSRRows( 1, NULL, -1, Ba != NULL, hypre_ParCSRMatrixFirstColDiag(mat), hypre_ParCSRMatrixDeviceColMapOffd(mat), hypre_CSRMatrixI(Aa) + local_row, hypre_CSRMatrixJ(Aa), hypre_CSRMatrixData(Aa), hypre_CSRMatrixI(Ba) + local_row, hypre_CSRMatrixJ(Ba), hypre_CSRMatrixData(Ba), NULL, hypre_ParCSRMatrixRowindices(mat), hypre_ParCSRMatrixRowvalues(mat) ); } if (col_ind) { *col_ind = hypre_ParCSRMatrixRowindices(mat); } if (values) { *values = hypre_ParCSRMatrixRowvalues(mat); } hypre_SyncCudaComputeStream(hypre_handle()); return hypre_error_flag; } /* abs == 1, use absolute values * option == 0, drop all the entries that are smaller than tol * TODO more options */ HYPRE_Int hypre_ParCSRMatrixDropSmallEntriesDevice( hypre_ParCSRMatrix *A, HYPRE_Complex tol, HYPRE_Int abs, HYPRE_Int option) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *h_col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A); if (col_map_offd_A == NULL) { col_map_offd_A = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(col_map_offd_A, h_col_map_offd_A, HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDeviceColMapOffd(A) = col_map_offd_A; } hypre_CSRMatrixDropSmallEntriesDevice(A_diag, tol, abs, option); hypre_CSRMatrixDropSmallEntriesDevice(A_offd, tol, abs, option); hypre_ParCSRMatrixSetNumNonzeros(A); hypre_ParCSRMatrixDNumNonzeros(A) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(A); /* squeeze out zero columns of A_offd */ HYPRE_Int *tmp_j, *tmp_end, num_cols_A_offd_new; tmp_j = hypre_TAlloc(HYPRE_Int, hypre_CSRMatrixNumNonzeros(A_offd), HYPRE_MEMORY_DEVICE); hypre_TMemcpy(tmp_j, hypre_CSRMatrixJ(A_offd), HYPRE_Int, hypre_CSRMatrixNumNonzeros(A_offd), HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( sort, tmp_j, tmp_j + hypre_CSRMatrixNumNonzeros(A_offd) ); tmp_end = HYPRE_THRUST_CALL( unique, tmp_j, tmp_j + hypre_CSRMatrixNumNonzeros(A_offd) ); num_cols_A_offd_new = tmp_end - tmp_j; hypre_assert(num_cols_A_offd_new <= num_cols_A_offd); if (num_cols_A_offd_new < num_cols_A_offd) { hypre_CSRMatrixNumCols(A_offd) = num_cols_A_offd_new; HYPRE_Int *offd_mark = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_DEVICE); HYPRE_BigInt *col_map_offd_A_new = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd_new, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( scatter, thrust::counting_iterator<HYPRE_Int>(0), thrust::counting_iterator<HYPRE_Int>(num_cols_A_offd_new), tmp_j, offd_mark ); HYPRE_THRUST_CALL( gather, hypre_CSRMatrixJ(A_offd), hypre_CSRMatrixJ(A_offd) + hypre_CSRMatrixNumNonzeros(A_offd), offd_mark, hypre_CSRMatrixJ(A_offd) ); HYPRE_THRUST_CALL( gather, tmp_j, tmp_j + num_cols_A_offd_new, col_map_offd_A, col_map_offd_A_new ); hypre_TFree(offd_mark, HYPRE_MEMORY_DEVICE); hypre_TFree(col_map_offd_A, HYPRE_MEMORY_DEVICE); hypre_TFree(h_col_map_offd_A, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDeviceColMapOffd(A) = col_map_offd_A_new; hypre_ParCSRMatrixColMapOffd(A) = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd_new, HYPRE_MEMORY_HOST); hypre_TMemcpy(hypre_ParCSRMatrixColMapOffd(A), col_map_offd_A_new, HYPRE_BigInt, num_cols_A_offd_new, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); } hypre_TFree(tmp_j, HYPRE_MEMORY_DEVICE); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixTransposeDevice *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixTransposeDevice( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix **AT_ptr, HYPRE_Int data ) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *A_diagT; hypre_CSRMatrix *AT_offd; HYPRE_Int num_procs; HYPRE_Int num_cols_offd_AT = 0; HYPRE_BigInt *col_map_offd_AT = NULL; hypre_ParCSRMatrix *AT; hypre_MPI_Comm_size(hypre_ParCSRMatrixComm(A), &num_procs); if (num_procs > 1) { void *request; hypre_CSRMatrix *A_offdT, *Aext; HYPRE_Int *Aext_ii, *Aext_j, Aext_nnz; HYPRE_Complex *Aext_data; HYPRE_BigInt *tmp_bigj; hypre_CSRMatrixTranspose(A_offd, &A_offdT, data); hypre_CSRMatrixBigJ(A_offdT) = hypre_TAlloc(HYPRE_BigInt, hypre_CSRMatrixNumNonzeros(A_offdT), HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, hypre_CSRMatrixJ(A_offdT), hypre_CSRMatrixJ(A_offdT) + hypre_CSRMatrixNumNonzeros(A_offdT), thrust::make_constant_iterator(hypre_ParCSRMatrixFirstRowIndex(A)), hypre_CSRMatrixBigJ(A_offdT), thrust::plus<HYPRE_BigInt>() ); if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } hypre_ExchangeExternalRowsDeviceInit(A_offdT, hypre_ParCSRMatrixCommPkg(A), data, &request); hypre_CSRMatrixTranspose(A_diag, &A_diagT, data); Aext = hypre_ExchangeExternalRowsDeviceWait(request); hypre_CSRMatrixDestroy(A_offdT); // Aext contains offd of AT Aext_nnz = hypre_CSRMatrixNumNonzeros(Aext); Aext_ii = hypreDevice_CsrRowPtrsToIndices(hypre_CSRMatrixNumRows(Aext), Aext_nnz, hypre_CSRMatrixI(Aext)); hypre_ParCSRCommPkgCopySendMapElmtsToDevice(hypre_ParCSRMatrixCommPkg(A)); HYPRE_THRUST_CALL( gather, Aext_ii, Aext_ii + Aext_nnz, hypre_ParCSRCommPkgDeviceSendMapElmts(hypre_ParCSRMatrixCommPkg(A)), Aext_ii ); tmp_bigj = hypre_TAlloc(HYPRE_BigInt, Aext_nnz, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(tmp_bigj, hypre_CSRMatrixBigJ(Aext), HYPRE_BigInt, Aext_nnz, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( sort, tmp_bigj, tmp_bigj + Aext_nnz ); HYPRE_BigInt *new_end = HYPRE_THRUST_CALL( unique, tmp_bigj, tmp_bigj + Aext_nnz ); num_cols_offd_AT = new_end - tmp_bigj; col_map_offd_AT = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(col_map_offd_AT, tmp_bigj, HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); hypre_TFree(tmp_bigj, HYPRE_MEMORY_DEVICE); Aext_j = hypre_TAlloc(HYPRE_Int, Aext_nnz, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( lower_bound, col_map_offd_AT, col_map_offd_AT + num_cols_offd_AT, hypre_CSRMatrixBigJ(Aext), hypre_CSRMatrixBigJ(Aext) + Aext_nnz, Aext_j ); Aext_data = hypre_CSRMatrixData(Aext); hypre_CSRMatrixData(Aext) = NULL; hypre_CSRMatrixDestroy(Aext); if (data) { hypreDevice_StableSortByTupleKey(Aext_nnz, Aext_ii, Aext_j, Aext_data, 0); } else { HYPRE_THRUST_CALL( stable_sort, thrust::make_zip_iterator(thrust::make_tuple(Aext_ii, Aext_j)), thrust::make_zip_iterator(thrust::make_tuple(Aext_ii, Aext_j)) + Aext_nnz ); } AT_offd = hypre_CSRMatrixCreate(hypre_ParCSRMatrixNumCols(A), num_cols_offd_AT, Aext_nnz); hypre_CSRMatrixJ(AT_offd) = Aext_j; hypre_CSRMatrixData(AT_offd) = Aext_data; hypre_CSRMatrixInitialize_v2(AT_offd, 0, HYPRE_MEMORY_DEVICE); hypreDevice_CsrRowIndicesToPtrs_v2(hypre_CSRMatrixNumRows(AT_offd), Aext_nnz, Aext_ii, hypre_CSRMatrixI(AT_offd)); hypre_TFree(Aext_ii, HYPRE_MEMORY_DEVICE); } else { hypre_CSRMatrixTransposeDevice(A_diag, &A_diagT, data); AT_offd = hypre_CSRMatrixCreate(hypre_ParCSRMatrixNumCols(A), 0, 0); hypre_CSRMatrixInitialize_v2(AT_offd, 0, HYPRE_MEMORY_DEVICE); } AT = hypre_ParCSRMatrixCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumCols(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixColStarts(A), hypre_ParCSRMatrixRowStarts(A), num_cols_offd_AT, hypre_CSRMatrixNumNonzeros(A_diagT), hypre_CSRMatrixNumNonzeros(AT_offd)); hypre_ParCSRMatrixSetRowStartsOwner(AT, 0); hypre_ParCSRMatrixSetColStartsOwner(AT, 0); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(AT)); hypre_ParCSRMatrixDiag(AT) = A_diagT; hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(AT)); hypre_ParCSRMatrixOffd(AT) = AT_offd; if (num_cols_offd_AT) { hypre_ParCSRMatrixDeviceColMapOffd(AT) = col_map_offd_AT; hypre_ParCSRMatrixColMapOffd(AT) = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_HOST); hypre_TMemcpy(hypre_ParCSRMatrixColMapOffd(AT), col_map_offd_AT, HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); } *AT_ptr = AT; return hypre_error_flag; } HYPRE_Int hypre_ParCSRMatrixAddDevice( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, HYPRE_Complex beta, hypre_ParCSRMatrix *B, hypre_ParCSRMatrix **C_ptr ) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); HYPRE_Int num_cols_offd_C = 0; HYPRE_BigInt *d_col_map_offd_C = NULL; HYPRE_Int num_procs; hypre_MPI_Comm_size(hypre_ParCSRMatrixComm(A), &num_procs); hypre_CSRMatrix *C_diag = hypre_CSRMatrixAddDevice(alpha, A_diag, beta, B_diag); hypre_CSRMatrix *C_offd; //if (num_cols_offd_A || num_cols_offd_B) if (num_procs > 1) { hypre_ParCSRMatrixCopyColMapOffdToDevice(A); hypre_ParCSRMatrixCopyColMapOffdToDevice(B); HYPRE_BigInt *tmp = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_A + num_cols_offd_B, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(tmp, hypre_ParCSRMatrixDeviceColMapOffd(A), HYPRE_BigInt, num_cols_offd_A, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(tmp + num_cols_offd_A, hypre_ParCSRMatrixDeviceColMapOffd(B), HYPRE_BigInt, num_cols_offd_B, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( sort, tmp, tmp + num_cols_offd_A + num_cols_offd_B ); HYPRE_BigInt *new_end = HYPRE_THRUST_CALL( unique, tmp, tmp + num_cols_offd_A + num_cols_offd_B ); num_cols_offd_C = new_end - tmp; d_col_map_offd_C = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(d_col_map_offd_C, tmp, HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); /* reuse memory of tmp */ HYPRE_Int *offd_A2C = (HYPRE_Int *) tmp; HYPRE_Int *offd_B2C = offd_A2C + num_cols_offd_A; HYPRE_THRUST_CALL( lower_bound, d_col_map_offd_C, d_col_map_offd_C + num_cols_offd_C, hypre_ParCSRMatrixDeviceColMapOffd(A), hypre_ParCSRMatrixDeviceColMapOffd(A) + num_cols_offd_A, offd_A2C ); HYPRE_THRUST_CALL( lower_bound, d_col_map_offd_C, d_col_map_offd_C + num_cols_offd_C, hypre_ParCSRMatrixDeviceColMapOffd(B), hypre_ParCSRMatrixDeviceColMapOffd(B) + num_cols_offd_B, offd_B2C ); HYPRE_Int *C_offd_i, *C_offd_j, nnzC_offd; HYPRE_Complex *C_offd_a; hypreDevice_CSRSpAdd( hypre_CSRMatrixNumRows(A_offd), hypre_CSRMatrixNumRows(B_offd), num_cols_offd_C, hypre_CSRMatrixNumNonzeros(A_offd), hypre_CSRMatrixNumNonzeros(B_offd), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixJ(A_offd), alpha, hypre_CSRMatrixData(A_offd), offd_A2C, hypre_CSRMatrixI(B_offd), hypre_CSRMatrixJ(B_offd), beta, hypre_CSRMatrixData(B_offd), offd_B2C, NULL, &nnzC_offd, &C_offd_i, &C_offd_j, &C_offd_a ); hypre_TFree(tmp, HYPRE_MEMORY_DEVICE); C_offd = hypre_CSRMatrixCreate(hypre_CSRMatrixNumRows(A_offd), num_cols_offd_C, nnzC_offd); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_CSRMatrixData(C_offd) = C_offd_a; hypre_CSRMatrixMemoryLocation(C_offd) = HYPRE_MEMORY_DEVICE; } else { C_offd = hypre_CSRMatrixCreate(hypre_CSRMatrixNumRows(A_offd), 0, 0); hypre_CSRMatrixInitialize_v2(C_offd, 0, HYPRE_MEMORY_DEVICE); } /* Create ParCSRMatrix C */ HYPRE_BigInt *row_starts_C = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); HYPRE_BigInt *col_starts_C = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_TMemcpy(row_starts_C, hypre_ParCSRMatrixRowStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); hypre_TMemcpy(col_starts_C, hypre_ParCSRMatrixColStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); hypre_ParCSRMatrix *C = hypre_ParCSRMatrixCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixGlobalNumCols(A), row_starts_C, col_starts_C, num_cols_offd_C, hypre_CSRMatrixNumNonzeros(C_diag), hypre_CSRMatrixNumNonzeros(C_offd)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(C)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(C)); hypre_ParCSRMatrixDiag(C) = C_diag; hypre_ParCSRMatrixOffd(C) = C_offd; if (num_cols_offd_C) { hypre_ParCSRMatrixDeviceColMapOffd(C) = d_col_map_offd_C; hypre_ParCSRMatrixColMapOffd(C) = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); hypre_TMemcpy(hypre_ParCSRMatrixColMapOffd(C), d_col_map_offd_C, HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); } hypre_ParCSRMatrixSetNumNonzeros(C); hypre_ParCSRMatrixDNumNonzeros(C) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(C); /* create CommPkg of C */ hypre_MatvecCommPkgCreate(C); *C_ptr = C; return hypre_error_flag; } #endif // #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) /*-------------------------------------------------------------------------- * HYPRE_ParCSRDiagScale *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRDiagScale( HYPRE_ParCSRMatrix HA, HYPRE_ParVector Hy, HYPRE_ParVector Hx ) { hypre_ParCSRMatrix *A = (hypre_ParCSRMatrix *) HA; hypre_ParVector *y = (hypre_ParVector *) Hy; hypre_ParVector *x = (hypre_ParVector *) Hx; HYPRE_Real *x_data = hypre_VectorData(hypre_ParVectorLocalVector(x)); HYPRE_Real *y_data = hypre_VectorData(hypre_ParVectorLocalVector(y)); HYPRE_Real *A_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A)); HYPRE_Int *A_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A)); HYPRE_Int local_size = hypre_VectorSize(hypre_ParVectorLocalVector(x)); HYPRE_Int ierr = 0; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypreDevice_DiagScaleVector(local_size, A_i, A_data, y_data, 0.0, x_data); //hypre_SyncCudaComputeStream(hypre_handle()); #else /* #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) */ HYPRE_Int i; #if defined(HYPRE_USING_DEVICE_OPENMP) #pragma omp target teams distribute parallel for private(i) is_device_ptr(x_data,y_data,A_data,A_i) #elif defined(HYPRE_USING_OPENMP) #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < local_size; i++) { x_data[i] = y_data[i] / A_data[A_i[i]]; } #endif /* #if defined(HYPRE_USING_CUDA) */ return ierr; }